ホンダ株価予測(LSTM + 特徴量強化)

✅ 今回の目標

✅ 特徴量強化版コード(Colab向け)

# ========================= # ホンダ株価予測 完成版 # LSTM + MA + RSI + MACD # 日本語対応版 # ========================= !pip install yfinance --quiet # 日本語フォント !apt-get update -qq !apt-get install -y fonts-noto-cjk import yfinance as yf import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.font_manager as fm from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import ( LSTM, Dense, Dropout ) from tensorflow.keras import Input # ========================= # 日本語フォント設定 # ========================= fonts = [f.name for f in fm.fontManager.ttflist] if "Noto Sans CJK JP" in fonts: plt.rcParams['font.family'] = 'Noto Sans CJK JP' elif "IPAexGothic" in fonts: plt.rcParams['font.family'] = 'IPAexGothic' elif "IPAGothic" in fonts: plt.rcParams['font.family'] = 'IPAGothic' # ========================= # データ取得 # ========================= ticker = "7267.T" from datetime import datetime today = datetime.today().strftime('%Y-%m-%d') df = yf.download( ticker, start="2018-01-01", auto_adjust=True ) # MultiIndex対策 if isinstance(df.columns, pd.MultiIndex): df.columns = df.columns.get_level_values(0) # ========================= # テクニカル指標 # ========================= # 移動平均 df['MA7'] = df['Close'].rolling(window=7).mean() df['MA14'] = df['Close'].rolling(window=14).mean() # RSI delta = df['Close'].diff() gain = delta.where(delta > 0, 0) loss = -delta.where(delta < 0, 0) avg_gain = gain.rolling(14).mean() avg_loss = loss.rolling(14).mean() rs = avg_gain / avg_loss df['RSI'] = 100 - (100 / (1 + rs)) # MACD ema12 = df['Close'].ewm(span=12).mean() ema26 = df['Close'].ewm(span=26).mean() df['MACD'] = ema12 - ema26 # 不要データ削除 df = df[ [ 'Close', 'Volume', 'MA7', 'MA14', 'RSI', 'MACD' ] ].dropna() # ========================= # 正規化 # ========================= scaler = MinMaxScaler() scaled = scaler.fit_transform(df) # ========================= # 時系列データ作成 # ========================= seq_len = 90 X = [] y = [] for i in range(seq_len, len(scaled)): X.append(scaled[i-seq_len:i]) y.append(scaled[i, 0]) X = np.array(X) y = np.array(y) # ========================= # 学習データ / テストデータ # ========================= split = int(len(X) * 0.8) X_train = X[:split] y_train = y[:split] X_test = X[split:] y_test = y[split:] # ========================= # モデル構築 # ========================= model = Sequential([ Input(shape=(seq_len, X.shape[2])), LSTM(128, return_sequences=True), Dropout(0.2), LSTM(64), Dropout(0.2), Dense(32, activation='relu'), Dense(1) ]) model.compile( optimizer='adam', loss='mean_squared_error' ) # ========================= # 学習 # ========================= history = model.fit( X_train, y_train, validation_data=(X_test, y_test), epochs=20, batch_size=32, verbose=1 ) # ========================= # テスト予測 # ========================= pred_test = model.predict(X_test, verbose=0) # Close列だけ逆変換 dummy_test = np.zeros((len(pred_test), scaled.shape[1])) dummy_test[:,0] = pred_test[:,0] pred_prices = scaler.inverse_transform(dummy_test)[:,0] # 実株価 real_dummy = np.zeros((len(y_test), scaled.shape[1])) real_dummy[:,0] = y_test real_prices = scaler.inverse_transform(real_dummy)[:,0] # ========================= # 未来10日予測 # ========================= last_seq = scaled[-seq_len:] future_predictions = [] for _ in range(10): input_seq = last_seq.reshape( 1, seq_len, X.shape[2] ) pred = model.predict( input_seq, verbose=0 )[0][0] future_predictions.append(pred) next_row = last_seq[-1].copy() next_row[0] = pred last_seq = np.vstack([ last_seq[1:], next_row ]) # 逆変換 future_dummy = np.zeros((10, scaled.shape[1])) future_dummy[:,0] = future_predictions future_prices = scaler.inverse_transform( future_dummy )[:,0] future_dates = pd.date_range( df.index[-1] + pd.Timedelta(days=1), periods=10 ) # ========================= # グラフ表示 # ========================= plt.figure(figsize=(14,6)) # 過去実株価 plt.plot( df.index[-len(real_prices):], real_prices, label='実株価' ) # テスト予測 plt.plot( df.index[-len(pred_prices):], pred_prices, label='テスト予測' ) # 未来予測 plt.plot( future_dates, future_prices, marker='o', linewidth=3, label='未来10日予測' ) plt.title("ホンダ株価予測 完成版(LSTM + RSI + MACD)") plt.xlabel("日付") plt.ylabel("株価(円)") plt.grid(True) plt.legend() plt.xticks(rotation=45) plt.tight_layout() plt.show() # ========================= # 未来予測表示 # ========================= future_df = pd.DataFrame({ '日付': future_dates, '予測株価': future_prices }) print("\n未来10日予測") print(future_df)

✅ 改善ポイントまとめ

項目 従来モデル 強化モデル(今回)
入力データ 終値(Close)のみ Close + 出来高 + MA7 + MA14
入力次元 (90, 1) (90, 4)
予測精度 不安定 長期的傾向に強く安定しやすい
解釈可能性 低い 高い(移動平均がトレンド補助)

✅ 次のステップも可能です!

ホンダ未来10日株価予測3モデル比較グラフ

# ========================================== # ホンダ株 AI予測システム Ultimate 完全版 # MultiIndex完全対応 # MACD / RSI / MA / Volume 対応 # LSTM Deep Learning # ========================================== # ========================= # 必要ライブラリ # ========================= !pip install yfinance scikit-learn tensorflow ta japanize-matplotlib --quiet # ========================= # インポート # ========================= import warnings warnings.filterwarnings("ignore") import yfinance as yf import numpy as np import pandas as pd import matplotlib.pyplot as plt import japanize_matplotlib from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import ( Dense, LSTM, Dropout ) from tensorflow.keras.callbacks import ( EarlyStopping ) from ta.trend import MACD from ta.momentum import RSIIndicator # ========================= # 株価データ取得 # ========================= ticker = "7267.T" print("株価データ取得中...") df = yf.download( ticker, start="2018-01-01", auto_adjust=True, progress=False ) # ========================= # MultiIndex対策 # ========================= if isinstance(df.columns, pd.MultiIndex): df.columns = df.columns.get_level_values(0) # ========================= # 必要列確認 # ========================= required_cols = ["Close", "Volume"] for col in required_cols: if col not in df.columns: raise ValueError(f"{col} 列が存在しません") # ========================= # 1次元Series化 # ========================= close_series = df["Close"].squeeze() # ========================= # テクニカル指標 # ========================= # 移動平均 df["MA5"] = close_series.rolling(5).mean() df["MA25"] = close_series.rolling(25).mean() # MACD macd = MACD(close=close_series) df["MACD"] = macd.macd().values df["MACD_SIGNAL"] = macd.macd_signal().values # RSI rsi = RSIIndicator( close=close_series, window=14 ) df["RSI"] = rsi.rsi().values # 欠損除去 df.dropna(inplace=True) # ========================= # 特徴量 # ========================= features = [ "Close", "Volume", "MA5", "MA25", "MACD", "MACD_SIGNAL", "RSI" ] data = df[features] print("\nデータ確認") print(data.tail()) # ========================= # スケーリング # ========================= scaler = MinMaxScaler() scaled_data = scaler.fit_transform(data) # ========================= # シーケンス作成 # ========================= SEQ_LEN = 90 X = [] y = [] for i in range(SEQ_LEN, len(scaled_data)): X.append( scaled_data[i-SEQ_LEN:i] ) # Close価格予測 y.append( scaled_data[i, 0] ) X = np.array(X) y = np.array(y) print("\n学習データ shape") print(X.shape) # ========================= # モデル構築 # ========================= model = Sequential() model.add( LSTM( 128, return_sequences=True, input_shape=( X.shape[1], X.shape[2] ) ) ) model.add(Dropout(0.3)) model.add( LSTM( 128, return_sequences=True ) ) model.add(Dropout(0.3)) model.add(LSTM(64)) model.add(Dropout(0.2)) model.add(Dense(32, activation="relu")) model.add(Dense(1)) # ========================= # コンパイル # ========================= model.compile( optimizer="adam", loss="mean_squared_error" ) # ========================= # EarlyStopping # ========================= early_stop = EarlyStopping( monitor="loss", patience=5, restore_best_weights=True ) # ========================= # AI学習 # ========================= print("\nAI学習中...") history = model.fit( X, y, epochs=10, batch_size=32, verbose=1, callbacks=[early_stop] ) print("\n学習完了") # ========================= # 未来予測 # ========================= future_days = 10 last_sequence = scaled_data[-SEQ_LEN:] future_predictions = [] current_seq = last_sequence.copy() print("\n未来予測計算中...") for _ in range(future_days): pred = model.predict( current_seq.reshape( 1, SEQ_LEN, len(features) ), verbose=0 ) predicted_close = pred[0][0] future_predictions.append(predicted_close) # 次行データ生成 next_row = current_seq[-1].copy() # Close更新 next_row[0] = predicted_close # シーケンス更新 current_seq = np.vstack([ current_seq[1:], next_row ]) print("未来予測完了") # ========================= # Closeのみ逆変換 # ========================= dummy = np.zeros( ( len(future_predictions), len(features) ) ) dummy[:, 0] = future_predictions future_prices = scaler.inverse_transform(dummy)[:, 0] # ========================= # 営業日生成 # ========================= future_dates = pd.bdate_range( start=df.index[-1] + pd.Timedelta(days=1), periods=future_days ) # ========================= # グラフ表示 # ========================= plt.figure(figsize=(16, 8)) # 実株価 plt.plot( df.index[-180:], df["Close"].tail(180), linewidth=2, label="実際の株価" ) # AI予測 plt.plot( future_dates, future_prices, marker="o", linewidth=3, label="AI未来予測" ) plt.title( "ホンダ(7267.T)AI株価予測 Ultimate 完全版", fontsize=20 ) plt.xlabel("日付") plt.ylabel("株価(円)") plt.grid(True) plt.legend() plt.xticks(rotation=45) plt.tight_layout() plt.show() # ========================= # AI売買判定 # ========================= start_price = future_prices[0] end_price = future_prices[-1] diff = end_price - start_price rate = (diff / start_price) * 100 print("\n==============================") print("🧠 AI 売買判定") print("==============================") print(f"開始予測価格 : {start_price:.2f} 円") print(f"終了予測価格 : {end_price:.2f} 円") print(f"予測変化率 : {rate:.2f} %") if rate >= 5: print("🚀 強い上昇予測 → 強気買い") elif rate >= 2: print("✅ 上昇予測 → 買い優勢") elif rate >= 0: print("🟢 やや上昇 → 中立〜買い") elif rate >= -2: print("🟡 横ばい〜弱含み") else: print("⚠️ 下落警戒 → 注意") # ========================= # 未来予測一覧 # ========================= result_df = pd.DataFrame({ "Date": future_dates, "Predicted_Close": future_prices }) print("\n==============================") print("未来予測一覧") print("==============================") print(result_df.round(2)) # ========================= # CSV保存 # ========================= csv_name = "honda_ai_prediction.csv" result_df.to_csv( csv_name, index=False ) print(f"\nCSV保存完了 : {csv_name}")