============================= Complete LSTM Foreign… · The Chat Archive
Explore / Programming ============================= Complete LSTM Foreign Buy/Sell Prediction Script… Save Share Download ▾ Report============================= Complete LSTM Foreign Buy/Sell Prediction Script =============================
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
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\Foreign.csv"
data = pd.read_csv(file_path)
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
Assuming columns are ['Date', 'Buy', 'Sell', 'Net Buy/Sell (Lots)']
Convert 'Date' to datetime and set as index
data['Date'] = pd.to_datetime(data['Date'], format='%Y/%m/%d')
data.set_index('Date', inplace=True)
Selecting features - You can choose to predict 'Buy', 'Sell', or 'Net Buy/Sell (Lots)'
Here, we'll predict 'Net Buy/Sell (Lots)' based on previous 'Buy' and 'Sell'
features = ['Buy', 'Sell','Net Buy/Sell (Lots)']
target = 'Closing Price'
data = data[features + [target]]
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))
scaler_target = MinMaxScaler(feature_range=(0, 1))
Fit scaler_features on 'Buy' and 'Sell'
scaled_features = scaler_features.fit_transform(data[features])
Fit scaler_target on 'Net Buy/Sell (Lots)'
scaled_target = scaler_target.fit_transform(data[[target]])
Combine scaled features and target
scaled_data = np.hstack((scaled_features, scaled_target))
4. Create Sequences for LSTM
def create_sequences(data, sequence_length):
X = []
y = []
for i in range(sequence_length, len(data)):
X.append(data[i-sequence_length:i, :-1]) # All features except target
y.append(data[i, -1]) # Target variable
return np.array(X), np.array(y)
sequence_length = 30 # You can adjust this value based on your data size
X, y = create_sequences(scaled_data, sequence_length)
print(f"\nTotal sequences created: {len(X)}")
5. Manual Train-Test Split to Ensure Alignment
Assistant2024-11-13 13:57 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 13, 2024
Added to archive Nov 16, 2026
ID 01m7h428gz1s0z0110j35ddvtvSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 60cee27223795bfc4203dc422206ea3d
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
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:]
print(f"Training sequences: {len(X_train)}")
print(f"Testing sequences: {len(X_test)}")
6. Build the LSTM Model model = Sequential()
model.add(LSTM(units=64, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(LSTM(units=64))
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 Values 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 Net Buy/Sell (Lots) plt.figure(figsize=(14, 7))
plt.plot(y_test_inverse, color='blue', label='Actual Net Buy/Sell (Lots)')
plt.plot(predictions_inverse, color='red', label='Predicted Net Buy/Sell (Lots)')
plt.title('Actual vs Predicted Net Buy/Sell (Lots)')
plt.xlabel('Time')
plt.ylabel('Net Buy/Sell (Lots)')
plt.legend()
plt.show()
=================== 12. Predict Future 2 Weeks of Buy/Sell (10 Trading Days) ===================
12.1 Prepare the Latest Data Sequence last_sequence = scaled_data[-sequence_length:, :-1] # Last 'sequence_length' days of features
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, X_train.shape[2]))
# Predict the next day's Net Buy/Sell (Lots)
predicted_scaled = model.predict(input_seq)
# Append the predicted value to future_predictions_scaled
future_predictions_scaled.append(predicted_scaled[0][0])
# Create a new row for the next input sequence
# Here, we assume that the 'Buy' and 'Sell' for the next day remain the same as the last day
# except for the 'Net Buy/Sell' which is updated based on prediction
# You may enhance this by incorporating more sophisticated logic
new_row = current_sequence[-1].copy()
new_row[-1] = predicted_scaled # Update 'Net Buy/Sell (Lots)'
# Append the new 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 last_date = data.index[-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 DataFrame for Future Predictions future_df = pd.DataFrame({
'Date': future_dates,
'Predicted Net Buy/Sell (Lots)': future_predictions_inverse.flatten()
})
12.5 Plot Predicted Net Buy/Sell (Lots) Only plt.figure(figsize=(14, 7))
plt.plot(future_df['Date'], future_df['Predicted Net Buy/Sell (Lots)'], color='red', marker='o', label='Predicted Net Buy/Sell (Lots)')
plt.title('Predicted Net Buy/Sell (Lots) for the Next 2 Weeks')
plt.xlabel('Date')
plt.ylabel('Predicted Net Buy/Sell (Lots)')
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 Net Buy/Sell (Lots) for the Next 2 Weeks:")
print(future_df)
============================= Script End ============================= ###我增加了Closing Price這個欄位在CSV,把Closing Price'當為預測值
您好!感谢您分享完整的LSTM外资买卖预测脚本,并告知您已经在CSV中添加了Closing Price列,并将其设为预测目标变量。整体来看,您的脚本已经很好地处理了数据加载、预处理、模型构建和训练的各个步骤。然而,考虑到您现在的目标是预测Closing Price,在脚本的第12步(即未来2周的预测部分)需要进行一些调整,以确保预测的是Closing Price而不是Net Buy/Sell (Lots)。
以下是针对第12步的详细调整建议和修改后的代码:
12. 预测未来2周的Closing Price
12.1 准备最新的数据序列
原脚本中,您将Closing Price设为目标变量,因此我们需要确保在未来预测中,模型使用的是Buy、Sell和Net Buy/Sell (Lots)作为输入特征,以预测Closing Price。
修改后的代码:
# =================== 12. 预测未来2周的Closing Price(10个交易日) ===================
# 12.1 准备最新的数据序列
last_sequence = scaled_data[-sequence_length:, :-1] # 最近的 'sequence_length' 天的特征
# 初始化一个列表以存储未来的预测值
future_predictions_scaled = []
# 定义要预测的未来天数(2周约10个交易日)
future_days = 10 # 调整为表示两周的交易日
# 复制 last_sequence 以避免修改原始的 scaled_data
current_sequence = last_sequence.copy()
for day in range(future_days):
# 将输入序列调整为模型需要的形状:(1, sequence_length, num_features)
input_seq = current_sequence.reshape((1, sequence_length, X_train.shape[2]))
# 预测下一天的 Closing Price
predicted_scaled = model.predict(input_seq)
# 将预测值添加到 future_predictions_scaled 中
future_predictions_scaled.append(predicted_scaled[0][0])
# 创建新的特征行用于下一个预测
# 假设 'Buy' 和 'Sell' 保持与最后一天相同,可以根据实际情况调整
new_row = current_sequence[-1].copy()
# 这里我们无法预测未来的 'Buy' 和 'Sell',所以保持不变
# 仅更新 'Net Buy/Sell (Lots)' 或根据需要进行其他处理
# 如果 'Closing Price' 是唯一的预测目标,可以不更新其他特征
# 这里只需将新的 'Closing Price' 添加到序列中
# 但由于 'Closing Price' 是目标变量,不应作为输入特征,因此我们不需要更新它
# 因此,我们只需使用现有的特征序列进行预测,而不修改输入特征
# 如果需要,可以将 'Closing Price' 作为新的特征添加,但这需要模型架构的调整
# 这里保持特征不变
current_sequence = np.vstack([current_sequence[1:], current_sequence[-1]])
# 12.2 反向缩放以获取实际的 Closing Price 值
future_predictions_scaled = np.array(future_predictions_scaled).reshape(-1, 1)
future_predictions_inverse = scaler_target.inverse_transform(future_predictions_scaled)
# 12.3 为未来预测准备日期
# 获取原始数据的最后日期
last_date = data.index[-1]
# 生成未来的交易日期(不包含周末)
future_dates = []
current_date = last_date
while len(future_dates) < future_days:
current_date += timedelta(days=1)
if current_date.weekday() < 5: # 星期一=0, 星期日=6
future_dates.append(current_date)
future_dates = pd.to_datetime(future_dates)
# 12.4 创建未来预测的 DataFrame
future_df = pd.DataFrame({
'Date': future_dates,
'Predicted Closing Price': future_predictions_inverse.flatten()
})
# 12.5 绘制预测的 Closing Price
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('未来2周的预测 Closing Price')
plt.xlabel('日期')
plt.ylabel('预测 Closing Price')
plt.legend()
# 格式化x轴以显示日期(格式:YYYY-MM-DD)
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未来2周的预测 Closing Price:")
print(future_df)
解释与调整说明:
预测目标调整 :
将预测目标从Net Buy/Sell (Lots)更改为Closing Price。
在创建序列时,X为过去30天的Buy、Sell和Net Buy/Sell (Lots),y为下一天的Closing Price。
未来预测部分的调整 :
在预测未来的Closing Price时,由于我们无法获得未来的Buy和Sell数据,假设它们保持与最后一天相同。这是一种简化的假设,实际应用中可以根据更复杂的逻辑进行调整。
由于Closing Price是目标变量,不需要将其加入输入特征,因此在更新current_sequence时,仅保留原有的特征序列,不添加新的Closing Price预测值。
反向缩放 :
利用scaler_target对预测值进行反向缩放,以获取实际的Closing Price值。
日期处理 :
可视化与输出 :
绘制未来2周的预测Closing Price图表。
打印未来预测的具体数值。
完整调整后的脚本
为了方便,以下是整个脚本中相关部分的调整总结:
选择特征与目标变量 :
features = ['Buy', 'Sell','Net Buy/Sell (Lots)']
target = 'Closing Price'
data = data[features + [target]]
创建序列 :
不需要更改,仍然使用过去30天的Buy、Sell和Net Buy/Sell (Lots)作为输入,预测下一天的Closing Price。
未来预测部分(第12步) :
如上所述,确保预测的是Closing Price,并相应调整代码和注释。
其他建议
模型性能优化 :
考虑调整模型的层数、单元数或添加正则化层以防止过拟合。
尝试不同的优化器和学习率,以找到最佳的训练效果。
特征工程 :
根据业务理解,增加更多相关特征,如技术指标(移动平均线、相对强弱指数等)以提升模型性能。
考虑使用时间序列特有的特征,如季节性、趋势性等。
评估指标 :
除了MAPE,可以考虑其他评估指标如均方误差(MSE)、均方根误差(RMSE)等,以全面评估模型性能。
未来预测的特征处理 :
当前假设未来的Buy和Sell与最后一天相同,您可以根据业务逻辑,制定更合理的预测机制,例如:
使用移动平均值或其他统计方法预测未来的Buy和Sell。
引入外部数据源来获取未来的Buy和Sell信息。
希望这些调整和建议能帮助您更好地预测Closing Price。如果您有任何进一步的问题或需要更详细的帮助,请随时告知!
Copy first response
Not yet included in a published release.