<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Lstm on Xainome Blog</title>
    <link>https://xainome-blog.pages.dev/tags/lstm/</link>
    <description>Recent content in Lstm on Xainome Blog</description>
    <generator>Hugo</generator>
    <language>ja-JP</language>
    <lastBuildDate>Wed, 24 Jul 2024 00:00:00 +0000</lastBuildDate>
    <atom:link href="https://xainome-blog.pages.dev/tags/lstm/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>短期売買と分析力が向上しそうな株価予測をだらだらとやる part9</title>
      <link>https://xainome-blog.pages.dev/posts/2024/07/stock-price-prediction-part-9/</link>
      <pubDate>Wed, 24 Jul 2024 00:00:00 +0000</pubDate>
      <guid>https://xainome-blog.pages.dev/posts/2024/07/stock-price-prediction-part-9/</guid>
      <description>&lt;h2 id=&#34;前回のあらすじ&#34;&gt;前回のあらすじ&lt;/h2&gt;
&lt;p&gt;確率的勾配降下法を使って予測をしてみました。&lt;/p&gt;
&lt;p&gt;うまくいかなかったので、別の方法を試すことにしました。&lt;/p&gt;
&lt;h2 id=&#34;lstm&#34;&gt;LSTM&lt;/h2&gt;
&lt;p&gt;時系列分析の代表モデルと言えばLSTMだと思います。&lt;/p&gt;
&lt;p&gt;というわけで前回とはプログラムを分けて実装しました。&lt;/p&gt;
&lt;pre tabindex=&#34;0&#34;&gt;&lt;code&gt;import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Input
import matplotlib.pyplot as plt

import glob
dm_fol = &amp;#39;./datamart/&amp;#39;
stock_list = glob.glob(dm_fol + &amp;#34;*.parquet&amp;#34;)

# データの読み込みと前処理
def preprocess_data(df, time_step=60):
    df[&amp;#39;Close&amp;#39;] = df[&amp;#39;Close&amp;#39;].astype(float)
    data = df[[&amp;#39;Close&amp;#39;]].values

    # データのスケーリング
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(data)
    
    # LSTM用のデータセット作成
    X, Y = [], []
    for i in range(time_step, len(scaled_data)):
        X.append(scaled_data[i-time_step:i, 0])
        Y.append(scaled_data[i, 0])
    
    X, Y = np.array(X), np.array(Y)
    X = X.reshape(X.shape[0], X.shape[1], 1)
    
    return X, Y, scaler

# LSTMモデルの構築
def create_lstm_model(input_shape):
    model = Sequential()
    model.add(Input(shape=input_shape))  # Inputオブジェクトを使用して入力形状を指定
    model.add(LSTM(50, return_sequences=True))
    # model.add(LSTM(50, return_sequences=True, input_shape=input_shape))
    model.add(LSTM(50, return_sequences=False))
    model.add(Dense(25))
    model.add(Dense(1))
    model.compile(optimizer=&amp;#39;adam&amp;#39;, loss=&amp;#39;mean_squared_error&amp;#39;)
    return model

# モデルの評価とプロット
def evaluate_model(df, model, scaler, X_train, y_train, X_test, y_test, time_step, sticker_name):
    y_train_pred = model.predict(X_train)
    y_test_pred = model.predict(X_test)
    
    y_train_pred = scaler.inverse_transform(y_train_pred)
    y_test_pred = scaler.inverse_transform(y_test_pred)
    
    y_train = scaler.inverse_transform([y_train])
    y_test = scaler.inverse_transform([y_test])
    
    train_mse = np.mean((y_train_pred - y_train[0]) ** 2)
    test_mse = np.mean((y_test_pred - y_test[0]) ** 2)
    print(f&amp;#34;Train Mean Squared Error: {train_mse}&amp;#34;)
    print(f&amp;#34;Test Mean Squared Error: {test_mse}&amp;#34;)
    
    # プロット
    df.set_index(&amp;#39;Date&amp;#39;, inplace=True)
    train_dates = df.iloc[time_step:len(y_train[0])+time_step].index
    test_dates = df.iloc[len(y_train[0])+time_step-1:-1].index
    
    plt.figure(figsize=(14, 7))
    # plt.plot(train_dates, y_train[0], label=&amp;#39;Train Actual&amp;#39;, color=&amp;#39;black&amp;#39;)
    plt.plot(test_dates, y_test[0], label=&amp;#39;Test Actual&amp;#39;, color=&amp;#39;red&amp;#39;)
    plt.plot(test_dates, y_test_pred, label=&amp;#39;Test Predicted&amp;#39;, color=&amp;#39;blue&amp;#39;)
    plt.title(sticker_name+&amp;#39;: Actual vs Predicted Stock Prices&amp;#39;)
    plt.xlabel(&amp;#39;Date&amp;#39;)
    plt.ylabel(&amp;#39;Close&amp;#39;)
    plt.legend()
    plt.show()

# 次の日の予測
def predict_next_day(model, scaler, df, time_step=60):
    data = df[[&amp;#39;Close&amp;#39;]].values
    last_data = data[-time_step:]
    last_data_scaled = scaler.transform(last_data)
    X_input = last_data_scaled.reshape(1, time_step, 1)
    next_day_prediction = model.predict(X_input)
    next_day_prediction = scaler.inverse_transform(next_day_prediction)
    print(f&amp;#34;Next Day Prediction: {next_day_prediction[0][0]}&amp;#34;)

# データの読み込み
for count, stock_data in enumerate(stock_list):
  df = pd.read_parquet(stock_data)
  sticker_name = stock_data.split(&amp;#39;\\&amp;#39;)[1].replace(&amp;#39;.parquet&amp;#39;, &amp;#39;&amp;#39;)

  # データの前処理
  time_step = 60
  X, Y, scaler = preprocess_data(df, time_step)

  # データの分割
  train_size = int(len(X) * 0.8)
  X_train, X_test = X[:train_size], X[train_size:]
  y_train, y_test = Y[:train_size], Y[train_size:]

  # モデルの構築と訓練
  model = create_lstm_model((X_train.shape[1], 1))
  model.fit(X_train, y_train, batch_size=1, epochs=1)

  # モデルの評価
  evaluate_model(df, model, scaler, X_train, y_train, X_test, y_test, time_step, sticker_name)

  # 次の日の予測
  predict_next_day(model, scaler, df, time_step)
&lt;/code&gt;&lt;/pre&gt;&lt;h2 id=&#34;コード確認&#34;&gt;コード確認&lt;/h2&gt;
&lt;pre tabindex=&#34;0&#34;&gt;&lt;code&gt;    # LSTM用のデータセット作成
    X, Y = [], []
    for i in range(time_step, len(scaled_data)):
        X.append(scaled_data[i-time_step:i, 0])
        Y.append(scaled_data[i, 0])
    
    X, Y = np.array(X), np.array(Y)
    X = X.reshape(X.shape[0], X.shape[1], 1)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;LSTM用のデータセットは60日分のデータを学習として使い、次の日を出力として使用するという特徴があります。&lt;/p&gt;</description>
    </item>
  </channel>
</rss>
