數據樣本 Date RSV K D J 2020/1/14 100 56.78 49.08 72.18… · The Chat Archive
Explore 數據樣本 Date RSV K D J 2020/1/14 100 56.78 49.08 72.18 2020/1/15 71.42857143 61.66285714… Save Share Download ▾ Report數據樣本
Date RSV K D J
2020/1/14 100 56.78 49.08 72.18
2020/1/15 71.42857143 61.66285714 53.27428571 78.44
2020/1/16 45.23809524 56.18793651 54.24550265 60.07280423
2020/1/17 38.0952381 50.15703704 52.88268078 44.70574956
2020/1/20 38.0952381 46.13643739 50.63393298 37.14144621
2020/1/30 0 30.75762493 44.00849696 4.255880854
2020/1/31 11.86440678 24.45988554 37.49229316 -1.60492968
2020/2/3 8.823529412 19.24776683 31.41078438 -5.078268264
2020/2/4 38.23529412 25.57694259 29.46617045 17.79848688
2020/2/5 46.96969697 32.70786072 30.54673388 37.03011441
============================= Complete LSTM Stock Price Prediction Script =============================
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_absolute_percentage_error
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.callbacks import EarlyStopping
import tensorflow as tf
import warnings
from datetime import timedelta
Suppress warnings for cleaner output
warnings.filterwarnings("ignore")
tf.get_logger().setLevel('ERROR')
1. Load and Preprocess Data
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\stock_price_with_kdj.csv"
data = pd.read_csv(file_path, parse_dates=['Date'])
Display first few rows and check for missing values
print("Sample Data:")
print(data.head())
print("\nMissing Values:")
print(data.isnull().sum())
2. Select Features and Target Variable
Set 'Date' as the DataFrame index if it exists
if 'Date' in data.columns:
data.set_index('Date', inplace=True)
numeric_features = ['RSV', 'K', 'D','J'] # Include 'Closing Price'
target = 'J'
data = data[numeric_features]
Ensure data is sorted by date
data.sort_index(inplace=True)
Handle missing values (e.g., forward fill)
data.fillna(method='ffill', inplace=True)
3. Feature Scaling
scaler_features = MinMaxScaler(feature_range=(0, 1))
scaled_features = scaler_features.fit_transform(data[numeric_features[:-1]]) # Exclude 'Closing Price'
scaler_target = MinMaxScaler(feature_range=(0, 1))
scaled_target = scaler_target.fit_transform(data[[target]]) # Only 'Closing Price'
Combine scaled features and target
scaled_data = np.hstack((scaled_features, scaled_target))
4. Create Sequences for LSTM
def create_sequences(data, sequence_length, target_column):
X = []
y = []
for i in range(sequence_length, len(data)):
X.append(data[i-sequence_length:i, :-1]) # All features except the target
y.append(data[i, -1]) # Target column
return np.array(X), np.array(y)
sequence_length = 70 # You can adjust this value
X, y = create_sequences(scaled_data, sequence_length, target_column=numeric_features.index('J'))
Assistant2024-11-14 13:47 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Nov 14, 2024
Added to archive Nov 17, 2026
ID 01m7h428gz5qzx20phfk2n28y2Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 31158bdd7c872e3340d8314712080b0a
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
5. Manual Train-Test Split to Ensure Alignment 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:]
6. Build the LSTM Model model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(LSTM(units=50))
model.add(Dense(1))
Compile the model model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_absolute_percentage_error'])
7. Implement Early Stopping early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
8. Train the Model history = model.fit(
X_train, y_train,
epochs=100,
batch_size=16,
validation_split=0.1,
callbacks=[early_stop],
verbose=1
)
9. Make Predictions on Test Set predictions = model.predict(X_test)
Inverse Transform to Get Actual Prices y_test_inverse = scaler_target.inverse_transform(y_test.reshape(-1, 1))
predictions_inverse = scaler_target.inverse_transform(predictions)
10. Calculate MAPE mape = mean_absolute_percentage_error(y_test_inverse, predictions_inverse)
print(f"\nMean Absolute Percentage Error (MAPE): {mape * 100:.2f}%")
11. Plot Actual vs Predicted Closing Prices plt.figure(figsize=(14, 7))
plt.plot(y_test_inverse, color='blue', label='Actual Closing Price')
plt.plot(predictions_inverse, color='red', label='Predicted Closing Price')
plt.title('Actual vs Predicted Closing Prices')
plt.xlabel('Time')
plt.ylabel('Closing Price')
plt.legend()
plt.show()
=================== 12. Predict Future 2 Weeks of Stock Prices ===================
12.1 Prepare the Latest Data Sequence last_sequence = scaled_data[-sequence_length:, :-1] # Exclude the target from the last sequence
Initialize a list to store future predictions future_predictions_scaled = []
Define the number of future days to predict (2 weeks ≈ 10 trading days) future_days = 10 # Adjusted to represent two weeks of trading days
Copy the last_sequence to avoid modifying the original scaled_data current_sequence = last_sequence.copy()
for day in range(future_days):
# Reshape to match the input shape of the model: (1, sequence_length, num_features)
input_seq = current_sequence.reshape((1, sequence_length, current_sequence.shape[1]))
# Predict the next day's closing price
predicted_scaled = model.predict(input_seq)
# Append the predicted closing price to future_predictions_scaled
future_predictions_scaled.append(predicted_scaled[0][0])
# Create a new row for the next input sequence
# Reuse the last known values for 'Buy', 'Sell', 'Net Buy/Sell (Lots)'
new_row = current_sequence[-1].copy()
new_row[-1] = predicted_scaled # Update 'Closing Price'
# Append the updated row to current_sequence and remove the first row
current_sequence = np.vstack([current_sequence[1:], new_row])
12.2 Inverse Transform the Predicted Values future_predictions_scaled = np.array(future_predictions_scaled).reshape(-1, 1)
future_predictions_inverse = scaler_target.inverse_transform(future_predictions_scaled)
12.3 Prepare Dates for Future Predictions
Get the last date from the original dataset if isinstance(data.index, pd.DatetimeIndex):
last_date = data.index[-1]
else:
last_date = pd.to_datetime(data['Date'].iloc[-1])
Generate future trading dates (excluding weekends) future_dates = []
current_date = last_date
while len(future_dates) < future_days:
current_date += timedelta(days=1)
if current_date.weekday() < 5: # Monday=0, Sunday=6
future_dates.append(current_date)
future_dates = pd.to_datetime(future_dates)
12.4 Create DataFrames for Historical and Future Data
Historical Closing Prices history_df = pd.DataFrame({
'Date': data.index[-len(y_test_inverse):],
'Actual Closing Price': y_test_inverse.flatten()
})
Future Predicted Closing Prices future_df = pd.DataFrame({
'Date': future_dates,
'Predicted Closing Price': future_predictions_inverse.flatten()
})
12.5 Plot Predicted Closing Prices Only import matplotlib.dates as mdates
plt.figure(figsize=(14, 7))
plt.plot(future_df['Date'], future_df['Predicted Closing Price'], color='red', marker='o', label='Predicted Closing Price')
plt.title('Predicted Closing Prices for the Next 2 Weeks')
plt.xlabel('Date')
plt.ylabel('Closing Price')
plt.legend()
Format the x-axis to show dates in YYYY-MM-DD format plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=1)) # Set major ticks to daily intervals
Rotate date labels for better readability
Ensure layout fits well plt.tight_layout()
plt.show()
12.6 Print Future Predictions print("\nPredicted Closing Prices for the Next 2 Weeks:")
print(future_df)
============================= Script End ============================= 當前您的 LSTM 模型在股票價格預測中達到的 MAPE 為 50%,這表明模型的預測誤差相對較大。為了改進模型並降低 MAPE,可以考慮以下幾個方面:
數據預處理 :
確保數據足夠且具有代表性。
考慮使用更多的特徵,增加模型的預測能力。
優化數據縮放方法,確保特徵之間的比例合理。
模型架構 :
增加模型的複雜度,如添加更多的 LSTM 層或神經元。
添加正則化技術,如 Dropout,防止過擬合。
嘗試不同的激活函數和優化器。
超參數調整 :
調整序列長度(sequence_length)以捕捉更多的時間序列依賴性。
調整批量大小(batch_size)和訓練輪數(epochs)以找到最佳的訓練效果。
增強數據 :
如果數據量不足,考慮進行數據增強或收集更多的歷史數據。
以下是針對您的原始腳本進行改進後的版本,涵蓋上述建議:
# ============================= 改進版 LSTM 股票價格預測腳本 =============================
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_absolute_percentage_error
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
import tensorflow as tf
import warnings
from datetime import timedelta
# 禁用警告以保持輸出整潔
warnings.filterwarnings("ignore")
tf.get_logger().setLevel('ERROR')
# 1. 載入和預處理數據
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\stock_price_with_kdj.csv"
data = pd.read_csv(file_path, parse_dates=['Date'])
# 顯示前幾行數據並檢查缺失值
print("樣本數據:")
print(data.head())
print("\n缺失值:")
print(data.isnull().sum())
# 2. 選擇特徵和目標變量
# 如果存在 'Date' 列,將其設為DataFrame的索引
if 'Date' in data.columns:
data.set_index('Date', inplace=True)
# 增加更多的特徵(如果有的話)
# 假設 'Close' 是收盤價,您可以根據需要添加更多的技術指標
numeric_features = ['RSV', 'K', 'D', 'J'] # 包含所有相關特徵
target = 'J' # 目標變量(假設為 'J')
data = data[numeric_features]
# 確保數據按日期排序
data.sort_index(inplace=True)
# 處理缺失值(例如,前向填充)
data.fillna(method='ffill', inplace=True)
# 3. 特徵縮放
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# 將特徵和目標分開
features = scaled_data[:, :-1] # RSV, K, D
target_scaled = scaled_data[:, -1] # J
# 4. 創建 LSTM 序列
def create_sequences(features, target, sequence_length):
X = []
y = []
for i in range(sequence_length, len(features)):
X.append(features[i-sequence_length:i, :])
y.append(target[i])
return np.array(X), np.array(y)
sequence_length = 30 # 調整序列長度,根據數據集大小進行優化
X, y = create_sequences(features, target_scaled, sequence_length)
# 5. 分割訓練集和測試集
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:]
# 6. 構建 LSTM 模型
model = Sequential()
model.add(LSTM(units=100, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(0.2)) # 添加 Dropout 層防止過擬合
model.add(LSTM(units=100, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(units=1)) # 預測一個值
# 編譯模型
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_absolute_percentage_error'])
# 7. 實現早停
early_stop = EarlyStopping(monitor='val_loss', patience=20, restore_best_weights=True)
# 8. 訓練模型
history = model.fit(
X_train, y_train,
epochs=200, # 增加訓練輪數,視過擬合情況調整
batch_size=32, # 調整批量大小
validation_split=0.1,
callbacks=[early_stop],
verbose=1
)
# 9. 在測試集上進行預測
predictions = model.predict(X_test)
# 反轉縮放以獲取實際值
scaler_target = MinMaxScaler()
scaler_target.min_, scaler_target.scale_ = scaler.min_[-1], scaler.scale_[-1]
y_test_inverse = scaler_target.inverse_transform(y_test.reshape(-1, 1))
predictions_inverse = scaler_target.inverse_transform(predictions)
# 10. 計算 MAPE
mape = mean_absolute_percentage_error(y_test_inverse, predictions_inverse)
print(f"\n均方絕對百分比誤差 (MAPE): {mape * 100:.2f}%")
# 11. 繪製實際值與預測值對比圖
plt.figure(figsize=(14, 7))
plt.plot(y_test_inverse, color='blue', label='實際收盤價')
plt.plot(predictions_inverse, color='red', label='預測收盤價')
plt.title('實際值 vs 預測值 - 收盤價')
plt.xlabel('時間')
plt.ylabel('收盤價')
plt.legend()
plt.show()
# =================== 12. 預測未來兩週的股票價格 ===================
# 12.1 準備最新的數據序列
last_sequence = features[-sequence_length:, :]
# 初始化列表以存儲未來的預測
future_predictions_scaled = []
# 定義預測未來的天數(兩週約10個交易日)
future_days = 10
# 複製最近的序列
current_sequence = last_sequence.copy()
for day in range(future_days):
# 重塑為模型的輸入形狀: (1, 序列長度, 特徵數)
input_seq = current_sequence.reshape((1, sequence_length, current_sequence.shape[1]))
# 預測下一天的收盤價
predicted_scaled = model.predict(input_seq)
# 將預測結果添加到未來預測列表中
future_predictions_scaled.append(predicted_scaled[0][0])
# 更新當前序列
# 假設未來的 RSV, K, D 與前一天相同,僅更新 J 值
new_row = current_sequence[-1].copy()
new_row[-1] = predicted_scaled # 更新 J 值
current_sequence = np.vstack([current_sequence[1:], new_row])
# 12.2 反轉縮放以獲取實際預測值
future_predictions_scaled = np.array(future_predictions_scaled).reshape(-1, 1)
future_predictions_inverse = scaler_target.inverse_transform(future_predictions_scaled)
# 12.3 準備未來預測的日期
if isinstance(data.index, pd.DatetimeIndex):
last_date = data.index[-1]
else:
last_date = pd.to_datetime(data['Date'].iloc[-1])
future_dates = []
current_date = last_date
while len(future_dates) < future_days:
current_date += timedelta(days=1)
if current_date.weekday() < 5: # 排除週末
future_dates.append(current_date)
future_dates = pd.to_datetime(future_dates)
# 12.4 創建未來預測的 DataFrame
future_df = pd.DataFrame({
'Date': future_dates,
'預測收盤價': future_predictions_inverse.flatten()
})
# 12.5 繪製未來預測的收盤價
plt.figure(figsize=(14, 7))
plt.plot(future_df['Date'], future_df['預測收盤價'], color='green', marker='o', label='預測收盤價')
plt.title('未來兩週的預測收盤價')
plt.xlabel('日期')
plt.ylabel('收盤價')
plt.legend()
# 格式化 x 軸以顯示日期
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=1))
# 旋轉日期標籤以提高可讀性
plt.xticks(rotation=45)
# 確保佈局良好
plt.tight_layout()
plt.show()
# 12.6 打印未來的預測結果
print("\n未來兩週的預測收盤價:")
print(future_df)
# ============================= 腳本結束 =============================
改進點詳解:
增加模型複雜度與正則化 :
將 LSTM 層的單元數增加到 100,提升模型的表達能力。
添加了 Dropout 層(比例設為 0.2),以防止模型過擬合。
調整序列長度與批量大小 :
將 sequence_length 調整為 30,這是一個常見的選擇,可以根據實際數據進行調整。
增加 batch_size 至 32,加速訓練並可能提升穩定性。
增加訓練輪數 :
將 epochs 增加到 200,以便模型有足夠的時間學習數據中的模式。早停機制(EarlyStopping)將在模型性能不再提升時提前停止訓練。
優化特徵縮放 :
將所有特徵一起進行縮放,確保特徵之間的比例一致,這對於 LSTM 模型尤為重要。
改進序列生成方法 :
確保特徵和目標正確分離,並且在創建序列時不混淆特徵與目標。
增強訓練集與測試集的分割 :
使用 train_size 將數據分為 80% 的訓練集和 20% 的測試集,這是比較常見的比例。
反轉縮放時的處理 :
確保在反轉縮放時,僅對目標變量進行操作,避免數據變形。
預測未來價格時的假設改進 :
在更新序列時,假設未來的 RSV、K、D 與前一天相同,僅更新 J 值。這可以根據實際情況進一步優化,例如使用相關的模型預測其他指標。
進一步建議:
增加更多特徵 :
如果有更多的技術指標或基本面數據,可以將其納入特徵範疇,提升模型的預測能力。
使用交叉驗證 :
進一步提高模型的穩健性,可以使用時間序列的交叉驗證方法,而非單一的訓練/測試分割。
嘗試其他模型 :
除了 LSTM,還可以嘗試 GRU 或 Transformer 等模型,看看是否能提升預測效果。
超參數調整 :
使用網格搜索(Grid Search)或隨機搜索(Random Search)等方法,系統性地調整模型的超參數,以找到最佳的配置。
數據平滑與去噪 :
如果數據噪聲過大,可以考慮使用移動平均等方法對數據進行平滑處理,提高模型的預測精度。
監控其他指標 :
除了 MAPE,還可以監控 MAE、RMSE 等指標,全面評估模型性能。
通過上述改進,相信您的模型在預測準確性上會有所提升。如果在實施過程中遇到任何問題,歡迎隨時詢問!
Copy first response
Not yet included in a published release.