bookloveru2
2021年8月16日3 分
最終更新: 2021年11月1日
# @title GluonTS(Amazonが開発)で時系列株価予測
# https://aws.amazon.com/jp/blogs/news/creating-neural-time-series-models-with-gluon-time-series/
# https://aws.amazon.com/jp/builders-flash/202102/ml-stock-price-forecast/?awsf.filter-name=*all
!pip install mxnet~=1.7 gluonts pandas-datareader scikit-learn
from gluonts.dataset.common import ListDataset
from gluonts.model.deepar import DeepAREstimator
from gluonts.mx.trainer import Trainer
from gluonts.dataset.util import to_pandas
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from pandas_datareader import data as pdr
import datetime
import yfinance as yf
start = "2020-1-1" #@param {type:"string"}
end = datetime.date.today()
ticker = "AMZN" #@param [""] {allow-input: true}
yf.pdr_override() # <== that's all it takes :-)
# download dataframe
df = pdr.get_data_yahoo(ticker, start, end)["Adj Close"]
# sklearnで学習用データとテスト用データを作成
training, test = train_test_split(df, test_size=0.3, shuffle=False)
# ディクショナリーの一覧としてメモリに格納されたデータにアクセスするため、ListDatasetを使用。
# 作成したtraining(ここでは訓練用に作成した70%のデータの日付までを切り出す。
# この日付以降のデータは、後にモデルテスト(30%)のために使用
training_data = ListDataset([{"start": training.index[0], "target": training}], freq = "d")
# データセットを使い訓練できるモデル DeepAREstimator オブジェクトのインスタンス化
estimator = DeepAREstimator(freq="d", prediction_length=30, trainer=Trainer(epochs=20))
# 表面化していないデータを予測。訓練プロセスが終了すれば、Predictor で予測処理を作成。
predictor = estimator.train(training_data=training_data)
test_data = ListDataset([{"start": test.index[0], "target": test}],freq = "d")
for test_entry, forecast in zip(test_data, predictor.predict(test_data)):
to_pandas(test_entry)[-150:].plot(figsize=(12, 5), linewidth=2)
forecast.plot(color='r')
plt.grid(which='both')
plt.legend(["observations", "median prediction", "90% confidence interval", "50% confidence interval"])
以上です。
pythonでプログラミングがしたい!!
pythonを学びたい!という方には、
下記のオンラインプログラミング教室『Aidemy アイデミー』がお勧めです。
ご自身でプログラム環境を用意する必要は無く、サイトへアクセスするだけです。
創業者は東京大学卒の石川聡彦さん。
著書に『人工知能プログラミングのための数学がわかる本』(KADOKAWA/2018年)など。
無料で、お試しもできますので安心です。ご参考までに。