Home >  > 隐马尔科夫模型预测股价(优矿)

隐马尔科夫模型预测股价(优矿)

0

一、优矿
要登陆优矿,直接使用手机验证码登陆即可。
或者用账号:138+K134

二、效果

三、代码

from hmmlearn.hmm import GaussianHMM
import datetime
import numpy as np
from matplotlib import cm, pyplot as plt
import matplotlib.dates as dates
import pandas as pd
import seaborn as sns
sns.set_style('white')

beginDate = '20100401'
endDate = '20160317'
data = DataAPI.MktIdxdGet(ticker='000001',beginDate=beginDate,endDate=endDate,field=['tradeDate','closeIndex','lowestIndex','highestIndex','turnoverVol'],pandas="1")
data1 = DataAPI.FstTotalGet(exchangeCD=u"XSHE",beginDate=beginDate,endDate=endDate,field=['tradeVal'],pandas="1")
data2 = DataAPI.FstTotalGet(exchangeCD=u"XSHG",beginDate=beginDate,endDate=endDate,field=['tradeVal'],pandas="1")
tradeVal = data1 + data2
tradeDate = pd.to_datetime(data['tradeDate'][5:])
volume = data['turnoverVol'][5:]
closeIndex = data['closeIndex']
deltaIndex = np.log(np.array(data['highestIndex'])) - np.log(np.array(data['lowestIndex']))
deltaIndex = deltaIndex[5:]
logReturn1 = np.array(np.diff(np.log(closeIndex)))
logReturn1 = logReturn1[4:]
logReturn5 = np.log(np.array(closeIndex[5:])) - np.log(np.array(closeIndex[:-5]))
logReturnFst = np.array(np.diff(np.log(tradeVal['tradeVal'])))[4:]
closeIndex = closeIndex[5:]
X = np.column_stack([logReturn1,logReturn5,deltaIndex,volume,logReturnFst])

# Make an HMM instance and execute fit
model = GaussianHMM(n_components=6, covariance_type="diag", n_iter=1000).fit([X])
# Predict the optimal sequence of internal hidden state
hidden_states = model.predict(X)

#print("Transition matrix")
#print(model.transmat_)
#print()

#print("Means and vars of each hidden state")
#for i in range(model.n_components):
#    print("{0}th hidden state".format(i))
#    print("mean = ", model.means_[i])
#    print("var = ", np.diag(model.covars_[i]))


#整合数据
res = pd.DataFrame({'tradeDate':tradeDate,'logReturn1':logReturn1,'logReturn5':logReturn5,'volume':volume,'state':hidden_states}).set_index('tradeDate')

plt.figure(figsize=(15, 8))  
for i in range(model.n_components):
    idx = (hidden_states==i)
    plt.plot_date(tradeDate[idx],closeIndex[idx],'.',label='%dth hidden state'%i,lw=1)
    plt.legend()
    plt.grid(1)

plt.figure(figsize=(15, 8)) 
for i in range(model.n_components):
    idx = (hidden_states==i)
    idx = np.append(0,idx[:-1])#获得状态结果后第二天进行买入操作
    #fast factor backtest
    df = res.logReturn1
    res['sig_ret%s'%i] = df.multiply(idx,axis=0)
    
    plt.plot(np.exp(res['sig_ret%s'%i].cumsum()),label='%dth hidden state'%i)
    plt.legend()
    plt.grid(1)    
    
    
    
plt.figure(figsize=(15, 8))
idxlong = (hidden_states==1) + (hidden_states==5)  #做多状态
idxlong = np.append(0,idxlong[:-1])#获得状态结果后第二天进行买入操作
idxshort = (hidden_states==0) + (hidden_states==3) + (hidden_states==4) #做空状态
idxshort = np.append(0,idxshort[:-1])#获得状态结果后第二天进行买入操作
#fast factor backtest
df = res.logReturn1
res['sig_retbest'] =  df.multiply(idxlong,axis=0) - df.multiply(idxshort,axis=0)
    
plt.plot_date(tradeDate,np.exp(res['sig_retbest'].cumsum()),'-',label='our strategy')
plt.legend()
plt.grid(1)

参考:https://uqer.io/v3/community/share/56ec30bf228e5b887be50b35

暧昧帖

本文暂无标签

发表评论

*

*