2016-10-15 17 views
-1

S-&にK-nearest neighborアルゴリズムを実装して、将来の価格を予測し、ライブラリを学ぶ。 私はkNNアルゴリズムを基本的に理解していますが、私はPythonを使った機械学習コーディングの完全な初心者ですので、誰かが私を助けることができれば嬉しいです。ここでk-nearest neighbor(KNN)アルゴリズムをPythonでS&P 500インデックスに実装

が私のシミュレーションロジックは

  1. 資産行く:S & P 500インデックス月額価格(ETFと投資可能)

  2. ロジック

    • は来月の価格方向を予測します月末ごとにkNNアルゴリズムに基づいて(上または下)---->予測上:購入S & P 500インデックス、下:現金を保持(3%の年間リターンの仮定のインデックス)

    • トレーニングデータセット:最近のローリング12の月次データは

    • 独立変数(時間が経つにつれて、トレーニングデータセットは、常に移動平均の場合と同様に、変更されました) :最近3、6、9、12蛾戻り、月次リターンの最近12月ローリング標準偏差

    • 従属変数:次の月のリターンが正または負として表さ

ここに私のコードです。私は基本的なデータセットをコードすることができますが、主なアルゴリズムとシミュレーションロジックをコーディングすることは考えていません。誰でもこのコードを完成できますか?

import pandas as pd 
import matplotlib.pyplot as plt 
import numpy as np 
import pandas_datareader.data as web 

def price(stock, start): 
    price = web.DataReader(name=stock, data_source='yahoo', start=start)['Adj Close'] 
    return price.div(price.iat[0]).resample('M').last().to_frame('price') 

a = price('SPY','2000-01-01') 
a['cash'] = [(1.03**(1/12))**x for x in range(len(a.index))] 
a['R3'] = a.price/a.price.shift(3) 
a['R6'] = a.price/a.price.shift(6) 
a['R9'] = a.price/a.price.shift(9)  
a['R12'] = a.price/a.price.shift(12)  
a['rollingstd'] = a.price.pct_change().rolling(12).std() 

答えて

1

私は作った。これはフラクタル勢力スコアを使用した別のバージョンの戦略ですが、役に立つかもしれません。

import pandas as pd 
import matplotlib.pyplot as plt 
import numpy as np 
import pandas_datareader.data as web 
from sklearn import neighbors, svm 
from sklearn.ensemble import RandomForestClassifier 

def price(stock, start): 
    price = web.DataReader(name=stock, data_source='yahoo', start=start)['Adj Close'] 
    return price.div(price.iat[0]).resample('M').last().to_frame('price') 

def fractal(a, p): 
    df = pd.DataFrame() 
    for count in range(1,p+1): 
     a['direction'] = np.where(a['price'].diff(count)>0,1,0) 
     a['abs'] = a['price'].diff(count).abs() 
     a['volatility'] = a.price.diff().abs().rolling(count).sum() 
     a['fractal'] = a['abs']/a['volatility']*a['direction'] 
     df = pd.concat([df, a['fractal']], axis=1) 
    return df 

def meanfractal(a, l=12): 
    a['meanfractal']= pd.DataFrame(fractal(a, l)).sum(1,skipna=False)/l 

a = price('^KS11','2000-01-01') 
a['cash'] = [(1.03**(1/12))**x for x in range(len(a.index))] 
a['meanfractal']= pd.DataFrame(fractal(a, 12)).sum(1,skipna=False)/12 
a['rollingstd'] = a.price.pct_change().shift(1).rolling(12).std() 
a['result'] = np.where(a.price > a.price.shift(1), 1,0)  
a = a.dropna() 

print(a) 

clf = neighbors.KNeighborsClassifier(n_neighbors=3) 
clf1 = svm.SVC() 
clf3 = RandomForestClassifier(n_estimators=5) 

a['predicted']= pd.Series() 
for i in range(12,len(a.index)): 
    x = a.iloc[i-12:i,6:8]  
    y = a['result'][i-12:i] 
    clf3.fit(x, y) 
    a['predicted'][i]= clf3.predict(x)[-1] 

a = a.dropna() 
a.price = a.price.div(a.price.ix[0]) 
print(a) 
accuracy=clf3.score(a.iloc[:,6:8],a['result']) 

a['결과'] = np.where(a.predicted.shift(1)==1,a.price/a.price.shift(1),1).cumprod() 
a['result'] = np.where(a.predicted.shift(1)==1,(a.price/a.price.shift(1)+1.0026)/2,1.0026).cumprod() 
a['동일비중'] = ((a.price/a.price.shift(1)+1.0026)/2).cumprod() 
a[['result','price','결과']].plot() 
plt.show() 
print ("Predicted model accuracy: "+ str(accuracy)) 
関連する問題