メインコンテンツへスキップ
見出し画像

プログラミング初心者です。株価の予想をしてみました

    自己紹介ときっかけ
    ちまたでAIAIとよく聞くようになり、プログラミング含めていったいどういうものかと興味を持ち始めてみました。
    途中転職もし、多忙ななかで何とか形にできそうでうれしいです。


    実行環境
    Google Colaboratory

    日経平均株価について、2020年1月からのデータを用い、2024年12月末の株価を予想します。
    データはYahoo!financeから引用しています。

    分析の流れ


    yfinanceのライブラリをインストールして、株価データを取得するための準備をします。
    バージョン情報は以下の通りです。
    yfinance 0.2.43
    statsmodels 0.14.3

    今回使用するデータとティッカーシンボル

    mufg_ticker = '8306.T'
    nikkei_ticker = '^N225'

    8306.T: MUFG株価^N225: 日経平均株価
    
    import yfinance as yf
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import statsmodels.api as sm
    
    # MUFGと日経平均のティッカーシンボル
    mufg_ticker = '8306.T'
    nikkei_ticker = '^N225'
    
    # データの取得期間を設定
    start_date = '2020-01-01'
    end_date = '2024-08-31'
    # MUFGの株価データを取得
    mufg_data = yf.download(mufg_ticker, start=start_date, end=end_date)
    
    # 日経平均株価データを取得
    nikkei_data = yf.download(nikkei_ticker, start=start_date, end=end_date)
    
    # データの表示
    print(mufg_data.head())
    print(nikkei_data.head())
    
    # 株価の終値を時間系列データとして使用
    mufg_series = mufg_data['Close']
    nikkei_series = nikkei_data['Close']
    
    # データのプロット
    plt.figure(figsize=(10, 6))
    plt.plot(mufg_series, label='MUFG Stock Price')
    plt.plot(nikkei_series, label='Nikkei 225 Index')
    plt.title('MUFG Stock Price and Nikkei 225 Index')
    plt.xlabel('Date')
    plt.ylabel('Value')
    plt.legend()
    plt.show()
    

    画像
    日経平均とMUFG株価の推移比較

    縦軸について、日経平均と三菱UFJフィナンシャルグループは株価の桁が違うのでMUFGのグラフ(ブルー)は平坦になってしまいました・・・

    定常性の確認

    データが定常でない場合、差分を取ってデータを定常にします。差分を取る前後のプロットを確認します。

    # @title デフォルトのタイトル テキスト
    # 定常性の確認: 差分を取る前と後のプロット
    diff_mufg_series = mufg_series.diff().dropna()
    diff_nikkei_series = nikkei_series.diff().dropna()
    
    plt.figure(figsize=(10, 6))
    plt.subplot(211)
    plt.plot(mufg_series, label='Original MUFG Series')
    plt.legend()
    
    plt.subplot(212)
    plt.plot(diff_mufg_series, label='Differenced MUFG Series')
    plt.legend()
    plt.show()
    

    モデルの設定

    SARIMAXモデルのパラメータを設定し、日経平均株価データを外因変数(exog)として指定します。

    # SARIMAXモデルのパラメータ設定
    order = (1, 1, 1)
    seasonal_order = (1, 1, 1, 12)
    
    # 日経平均株価データを外因変数としてSARIMAXモデルを構築
    sarimax_model = sm.tsa.SARIMAX(mufg_series, order=order, seasonal_order=seasonal_order, exog=nikkei_series)
    
    # モデルの訓練
    sarimax_result = sarimax_model.fit()
    
    # モデルの要約
    print(sarimax_result.summary())

    予測期間の設定

    12か月先まで設定します。

    # 予測期間の設定
    forecast_steps = 12  # 12ヶ月先まで予測
    
    # 新しい日経平均株価データ(予測期間分)
    
    new_nikkei_data = nikkei_series[-forecast_steps:].values 
    new_nikkei_series = pd.Series(new_nikkei_data, index=pd.date_range(start=mufg_series.index[-1], periods=forecast_steps + 1, freq='M')[1:])
    
    print(new_nikkei_data)
    print(new_nikkei_series)

    予測の実行

    予測を実行し、プロットします。

    # 予測の実行
    forecast = sarimax_result.get_forecast(steps=forecast_steps, exog=new_nikkei_series)
    forecast_index = pd.date_range(start=mufg_series.index[-1], periods=forecast_steps + 1, freq='M')[1:]
    
    # 予測結果の取得
    forecast_series = pd.Series(forecast.predicted_mean.values, index=forecast_index)
    conf_int = forecast.conf_int()
    lower_series = pd.Series(conf_int.iloc[:, 0].values, index=forecast_index)
    upper_series = pd.Series(conf_int.iloc[:, 1].values, index=forecast_index)
    
    # 予測結果のプロット
    plt.figure(figsize=(10, 6))
    plt.plot(mufg_series, label='Observed')
    plt.plot(forecast_series, label='Forecast', color='red')
    plt.fill_between(forecast_index, lower_series, upper_series, color='pink', alpha=0.3)
    plt.title('MItsubishi UFJ (8306.T) Stock Price Forecast with Nikkei 225 Data')
    plt.xlabel('Date')
    plt.ylabel('Stock Price (JPY)')
    plt.legend()
    plt.grid(True)
    plt.show()

    結果
    青線が実データ、赤線が予測値、ピンクは予測範囲となります。
    上昇傾向ではあるものの、最近のボラティリティの大きさの反映は難しく、予測範囲が広いように見受けられます。

    画像
    日経平均株価を考慮した三菱UFJフィナンシャルグループの株価予測

    最後に

    業務で使うこともなく、なんとなく興味を持って初めてみて半年が過ぎました。
    無償でさまざまなライブラリが利用できたり、日々それぞれに進化していっているのを見て、AIに無限の可能性を感じました。
    あまり時間がなく十分に学習できませんでしたが、なんとなく入口部分が分かった感じがして自分なりに満足しています。
    また時間が取れたらチャレンジしてみたいと思います。


    ※ カリキュラムの一環で、受講修了条件を満たすために公開しています。


    あなたへのおすすめ