📘 03. Building Forecast Models (MA, ARIMA, etc.)

✅ In this section, you'll learn how to build basic FX price prediction models using Python, including Moving Average (MA) and ARIMA. ✅ 本セクションでは、移動平均(MA)やARIMAなどの基本的な為替予測モデルをPythonで構築する方法を学びます。


📊 Overview of Forecasting Models / モデル概要

Model Description (EN) 説明(日本語)
Moving Average (MA) Smooths price data over time 平均化してノイズを減らすシンプルなモデル
ARIMA Statistical model capturing trend + seasonality 傾向・周期性を扱える統計的予測モデル
Linear Regression Predicts future values based on features 特徴量に基づいて未来値を予測
LSTM (Bonus) Deep learning for sequence data 時系列に特化したニューラルネットワークモデル(応用)

🧮 Example 1: Moving Average Forecast

import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt

# データ取得
df = yf.download('USDJPY=X', start='2023-01-01', end='2023-12-31')

# 移動平均を計算
df['SMA_10'] = df['Close'].rolling(window=10).mean()

# 可視化
df[['Close', 'SMA_10']].plot(figsize=(12, 4), title='USD/JPY with 10-day SMA')
plt.grid()
plt.show()

📝 This example adds a simple 10-day moving average. 📝 この例では、10日間の移動平均線をチャートに表示しています。


📈 Example 2: ARIMA Forecast

import yfinance as yf
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
import matplotlib.pyplot as plt

# データ取得
df = yf.download('USDJPY=X', start='2022-01-01', end='2023-01-01')
df = df[['Close']].dropna()

# モデル構築・学習
model = ARIMA(df, order=(5,1,0))
model_fit = model.fit()

# 予測
forecast = model_fit.forecast(steps=30)

# 可視化
df['Close'].plot(label='Historical', figsize=(10,4))
forecast.plot(label='Forecast', linestyle='--')
plt.title('ARIMA Forecast: USD/JPY')
plt.legend()
plt.grid()
plt.show()

📌 order=(5,1,0) はAR, I, MAの各項を表します。変更して調整可能です。


🧠 Bonus: Linear Regression (Optional)

from sklearn.linear_model import LinearRegression
import numpy as np

df['SMA_5'] = df['Close'].rolling(window=5).mean()
df.dropna(inplace=True)

# 特徴量とターゲット
X = np.arange(len(df)).reshape(-1, 1)
y = df['SMA_5'].values

model = LinearRegression()
model.fit(X, y)

future_X = np.arange(len(df), len(df) + 10).reshape(-1, 1)
future_y = model.predict(future_X)

# 可視化
plt.plot(X, y, label='Historical')
plt.plot(future_X, future_y, label='Forecast', linestyle='--')
plt.title('Linear Regression Forecast')
plt.legend()
plt.grid()
plt.show()


🔍 Notes & Tips / 補足とヒント