This tutorial walks through the development of a true 6-factor strategy model for Bitcoin using Python. We use technical indicators like EMA, MACD, RSI, KDJ, CCI, and OBV to build a signal classification model that outputs Buy, Sell, or Hold. 本教程将带你从头开始构建一个真正的六因子比特币交易模型,利用多个经典技术指标生成买卖信号。
Step 1 步骤一:加载数据
btc_data = pd.read_csv("btc_data.csv", parse_dates=['Open time'])
btc_data.set_index('Open time', inplace=True)
btc_data.rename(columns=lambda x: x.lower(), inplace=True)
我们加载 15 分钟级别的 BTC 数据,并将时间设为索引。
Step 2 步骤二:添加技术指标(Technical Indicators)
我们使用 pandas_ta 添加如下指标:
- EMA 6, EMA 18, EMA 60
- MACD, MACD Signal
- RSI(14日)
- CCI(14日)
- KDJ(三线指标)
- OBV(On-Balance Volume)
import pandas_ta as ta
df['EMA_6'] = ta.ema(df['close'], length=6)
df['EMA_18'] = ta.ema(df['close'], length=18)
...
df['OBV'] = ta.obv(df['close'], df['volume'])
df.dropna(inplace=True)
每一个因子代表了市场情绪、动量或资金流的某个维度。
Step 3 步骤三:价格预测模型(Price Regression Model)
我们用这些因子预测下一个周期的价格:
X = df[["EMA_6", "EMA_18", ..., "OBV"]]
y = df['close'].shift(-1)
训练一个线性模型进行价格拟合:
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
模型输出也可以作为后续决策模型的一部分特征:Predicted_Close
Step 4 步骤四:决策信号分类模型(Buy/Sell/Hold)
目标变量由以下六个条件生成:
y = np.where(
(EMA_6 > EMA_18) & (MACD > MACD_signal) & (RSI > 30) &
(K > D) & (CCI > 100) & (OBV > OBV.shift(1)), 1, # 买入
np.where(
(EMA_6 < EMA_18) & (MACD < MACD_signal) & (RSI < 70) &
(K < D) & (CCI < -100) & (OBV < OBV.shift(1)), -1, 0 # 卖出 / 持有
)
)
用 RandomForestClassifier 训练预测这些三分类信号:
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(max_depth=5)
model.fit(X_train, y_train)
模型预测出 Buy/Sell/Hold 信号,可用于策略执行。
Step 5 步骤五:图表展示(Interactive Plot)
我们用 Plotly 画出:
- 实际 vs 预测价格
- 买入(绿色三角)
- 卖出(红色倒三角)
- 持有(黄色圆点)
fig.add_trace(go.Scatter(... name='Buy'))
fig.add_trace(go.Scatter(... name='Sell'))
fig.add_trace(go.Scatter(... name='Hold'))
Summary 总结
- 🔍 因子基于传统技术指标:MACD、KDJ、OBV 等
- 🔄 通过组合条件构建标签(Buy/Sell/Hold)
- 🤖 使用机器学习进行分类预测
- 📈 图形展示策略效果,适合量化交易实践
This model demonstrates how to combine multiple technical indicators into a rule-based signal system, and then enhance it with machine learning for decision-making.
📎 Download & Connect
📥 完整代码与数据将上传至 GitHub,欢迎参考。 📬 如需合作或交流,请通过 LinkedIn 联系我。
Leave a Reply