📈 AI 股票走势预测模型
用 深度学习 + 时间序列分析 来构建一个 股票预测 AI,基于历史数据预测未来走势。
🚀 1. 关键功能
✅ AI 选股(基于财务数据 + 技术指标)
✅ 股票走势预测(LSTM/Transformer)
✅ 智能筛选高增长潜力股
✅ 可视化分析
🛠 2. 关键技术
📊 数据来源:Yahoo Finance / Alpha Vantage
📈 财务分析:PE、EPS、ROE、PB、成交量
🧠 机器学习选股:随机森林 / XGBoost
🔮 深度学习预测:LSTM / Transformer
📉 技术指标:MACD、RSI、布林带
💻 3. 代码实现
1️⃣ 安装依赖
pip install yfinance pandas numpy scikit-learn xgboost tensorflow matplotlib
👉 yfinance
:获取实时股票数据
👉 scikit-learn
:数据预处理 + 机器学习
👉 xgboost
:训练选股模型
👉 tensorflow
:LSTM 预测未来股价
2️⃣ 获取股票数据
import yfinance as yf
import pandas as pd
# 选取多个股票
stocks = ["AAPL", "TSLA", "MSFT", "GOOGL", "AMZN"]
def get_stock_data(ticker):
"""获取股票财务指标 & 历史数据"""
stock = yf.Ticker(ticker)
hist = stock.history(period="2y") # 获取过去 2 年数据
# 计算技术指标(简单示例)
hist["MA50"] = hist["Close"].rolling(window=50).mean() # 50 日均线
hist["MA200"] = hist["Close"].rolling(window=200).mean() # 200 日均线
hist["Volume_Change"] = hist["Volume"].pct_change() # 成交量变化
# 获取财务数据
info = stock.info
pe = info.get("trailingPE", None) # 市盈率
eps = info.get("trailingEps", None) # 每股收益
roe = info.get("returnOnEquity", None) # 股本回报率
pb = info.get("priceToBook", None) # 市净率
return hist, {"PE": pe, "EPS": eps, "ROE": roe, "PB": pb}
# 处理多个股票
data_dict = {}
fundamentals = []
for stock in stocks:
hist, fund = get_stock_data(stock)
data_dict[stock] = hist
fund["Stock"] = stock
fundamentals.append(fund)
# 转换为 DataFrame
fund_df = pd.DataFrame(fundamentals)
print(fund_df)
3️⃣ 机器学习选股
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 处理数据
fund_df.dropna(inplace=True)
X = fund_df[["PE", "EPS", "ROE", "PB"]]
y = (fund_df["ROE"] > 0.15).astype(int) # 例如 ROE > 15% 作为优质股票
# 归一化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 训练选股模型
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
# 预测潜力股
fund_df["AI_Selection"] = model.predict(X_scaled)
print(fund_df[fund_df["AI_Selection"] == 1]) # 选出的优质股票
4️⃣ 预测股价(LSTM)
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
# 选取 AI 选出的优质股
selected_stock = fund_df[fund_df["AI_Selection"] == 1]["Stock"].iloc[0]
stock_data = data_dict[selected_stock][["Close"]]
# 归一化
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(stock_data)
# 构造时间序列
def create_sequences(data, time_steps=60):
X, y = [], []
for i in range(len(data) - time_steps):
X.append(data[i : i + time_steps])
y.append(data[i + time_steps])
return np.array(X), np.array(y)
time_steps = 60
X, y = create_sequences(scaled_data, time_steps)
# 划分训练 & 测试集
split = int(len(X) * 0.8)
X_train, X_test = X[:split], X[split:]
y_train, y_test = y[:split], y[split:]
# LSTM 预测模型
model = Sequential([
LSTM(50, return_sequences=True, input_shape=(time_steps, 1)),
Dropout(0.2),
LSTM(50, return_sequences=False),
Dropout(0.2),
Dense(25),
Dense(1)
])
model.compile(optimizer="adam", loss="mean_squared_error")
model.fit(X_train, y_train, epochs=20, batch_size=32)
# 预测股价
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)
# 可视化
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
plt.plot(stock_data.index[split+time_steps:], scaler.inverse_transform(y_test.reshape(-1,1)), label="真实价格")
plt.plot(stock_data.index[split+time_steps:], predictions, label="预测价格")
plt.legend()
plt.title(f"股票价格预测 - {selected_stock}")
plt.show()
🚀 优化 AI 选股模型,让选股更精准!
我们可以提升 AI 选股模型 的准确性,方法包括:
✅ 财务指标(营收增长、负债率、自由现金流)
✅ 使用 XGBoost 代替随机森林(更强的特征学习能力)
✅ 技术指标(MACD、RSI、布林带)
✅ 结合市场情绪分析(新闻 & 社交媒体情绪)
1️⃣ 安装依赖
pip install yfinance pandas numpy scikit-learn xgboost matplotlib ta
👉 ta
:用于计算技术指标(MACD、RSI)
👉 xgboost
:更强的机器学习选股模型
2️⃣ 获取股票数据(加入更多财务指标)
import yfinance as yf
import pandas as pd
# 选取多个股票
stocks &#