1. 程式人生 > >金融情感分析--股市預測(一)

金融情感分析--股市預測(一)

(PS:趨勢分析)

我選的是周大生2018年第二季度的股市行情,在這裡選擇周大生

直接複製貼上得到xlsx檔案(檔案內容如下)

(已在Win7、python3.6上執行成功)

""""
以周大生為例;
說明會時間:2018/4/20
前10天-後60天       4/10-6/20
"""
from pandas import DataFrame, Series
import pandas as pd;
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
from matplotlib import ticker as mticker
from matplotlib.finance import candlestick_ohlc
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY, YEARLY
from matplotlib.dates import MonthLocator, MONTHLY
import datetime
import pylab

MA1 = 10  # 移動平均線的日期間隔
MA2 = 50
# '股票程式碼,名稱,收盤價,最高價,最低價,開盤價,前收盤,漲跌額,漲跌幅,換手率,成交量,成交金額,總市值,流通市值
startdate = datetime.date(2018, 4, 10)
enddate = datetime.date(2017, 6, 20)
data = pd.DataFrame(pd.read_excel('G:/project/sentimation_analysis/data/周大生.xlsx', sheet_name=0, index_col='日期'))  # 讀取資料、設定日期為index
data = data.sort_index()  # 按日期升序排列
print (data)
# 抽取需要的列組成新的表
stdata = pd.DataFrame({'DateTime': data.index, 'Open': data.開盤價, 'High': data.最高價, 'Close': data.收盤價, 'Low': data.最低價})
stdata['DateTime'] = mdates.date2num(stdata['DateTime'].astype(datetime.date))  # 把日期轉化成天數,從公元0年開始算


# stdata=stdata.set_index('DateTime')
# stdata.drop(data.columns[6:],axis=1,inplace=True),stdata['Volume']=data.漲跌幅,del stdata['名稱']

def main():
    daysreshape = stdata.reset_index()
    daysreshape = daysreshape.reindex(columns=['DateTime', 'Open', 'High', 'Low', 'Close'])

    Av1 = pd.rolling_mean(daysreshape.Close.values, MA1)
    Av2 = pd.rolling_mean(daysreshape.Close.values, MA2)
    SP = len(daysreshape.DateTime.values[MA2 - 1:])
    fig = plt.figure(facecolor='#07000d', figsize=(15, 10))

    ax1 = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4, axisbg='#07000d')
    candlestick_ohlc(ax1, daysreshape.values[-SP:], width=.6, colorup='#ff1717', colordown='#53c156')
    Label1 = str(MA1) + ' SMA'
    Label2 = str(MA2) + ' SMA'

    ax1.plot(daysreshape.DateTime.values[-SP:], Av1[-SP:], '#e1edf9', label=Label1, linewidth=1.5)
    ax1.plot(daysreshape.DateTime.values[-SP:], Av2[-SP:], '#4ee6fd', label=Label2, linewidth=1.5)
    ax1.grid(True, color='w')
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    ax1.yaxis.label.set_color("w")
    ax1.spines['bottom'].set_color("#5998ff")
    ax1.spines['top'].set_color("#5998ff")
    ax1.spines['left'].set_color("#5998ff")
    ax1.spines['right'].set_color("#5998ff")
    ax1.tick_params(axis='y', colors='w')
    plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
    ax1.tick_params(axis='x', colors='w')
    plt.ylabel('Stock price and Volume')
    plt.show()


if __name__ == "__main__":
    main()

執行K線圖如下:

(情感分析和K線聯絡續集)