S-&にK-nearest neighborアルゴリズムを実装して、将来の価格を予測し、ライブラリを学ぶ。 私はkNNアルゴリズムを基本的に理解していますが、私はPythonを使った機械学習コーディングの完全な初心者ですので、誰かが私を助けることができれば嬉しいです。ここでk-nearest neighbor(KNN)アルゴリズムをPythonでS&P 500インデックスに実装
が私のシミュレーションロジックは
資産行く:S & P 500インデックス月額価格(ETFと投資可能)
ロジック
は来月の価格方向を予測します月末ごとに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()