2016-10-15 3 views
-1

Ich möchte K-nearest neighbour Algorithmus zu S & P 500 Index zu prognostizieren, zukünftige Preis und entwickeln quantitative Algorithmus Handelsmodell mit Python über scikit- Bibliothek lernen. Obwohl ich grundlegendes Verständnis von kNN-Algorithmus habe, bin ich ein kompletter Anfänger der maschinellen Lernprogrammierung mit Python, also würde ich mich freuen, wenn mir jemand helfen kann.k-nächsten Nachbarn (KNN) Algorithmus in S & P 500 Index mit Python implementiert

geht hier meine Simulation Logik

  1. Nutzungsart: S & P-500-Index Monatspreis (investierbaren mit ETF)

  2. Logic

    • den Preis Richtung des nächsten Monats Predict (aufwärts oder abwärts) basierend auf dem kNN-Algorithmus jedes Monatsende ----> vorhergesagt: Kauf S & P 500 Index, unten: Bargeld halten (Hypothetischen Index von 3% Jahresrendite)

    • Trainingsdatensatz: recent Roll 12 Monatsdaten (Trainingsdatensatz wird ständig geändert, wie die Zeit vergeht, wie im Fall von gleitendem Durchschnitt)

    • Unabhängige Variable : recent 3, 6, 9, 12 moth Gegenzug den letzten 12 Monate rollend Standardabweichung der Monatsrendite

    • Dependent Variable: return nächsten Monat ausgedrückt als positive oder negative

Hier ist mein Code. Ich könnte Basic-Dataset codieren, habe aber keine Ahnung von Coding-Hauptalgorithmus und Simulationslogik. Jeder kann diesen Code vervollständigen?

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() 

Antwort

1

Ich habe es gemacht. Obwohl dies eine andere Version der Strategie ist, die den fraktalen Momentumwert verwendet, kann es hilfreich sein

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)) 
Verwandte Themen