
等级: 新手上路
- 注册:
- 2025-3-6
- 曾用名:
|
```python
from PythonApi import *
import time
import numpy as np
from sklearn.linear_model import LinearRegression
def init(context):
context.symbol = "ZQZC05"
context.trade_interval = 15 # 信号刷新间隔缩短至15秒
context.base_price = 0
context.position = 0
context.layer = 0
context.max_layers = 6 # 扩展最大层级
context.risk_ratio = 0.18 # 动态风险系数
context.volatility = 0 # 波动率指标
# 增强参数组
context.adaptive_params = {
"open_threshold": 0.002,
"stop_loss": 0.004,
"take_profit": 0.0055,
"momentum_window": 5 # 动量观测窗口(分钟)
}
# 加载机器学习模型
context.trend_model = LinearRegression()
settimer(market_analysis, 60) # 每分钟执行趋势分析
print(f"{context.symbol} 智能策略启动")
def market_analysis(context):
# 获取分钟级特征数据
bars = get_bars(context.symbol, 60, context.adaptive_params["momentum_window"])
prices = np.array([bar.close for bar in bars]).reshape(-1,1)
volumes = np.array([bar.volume for bar in bars])
# 计算动态波动率
context.volatility = np.std(prices[-10:]) / np.mean(prices[-10:])
# 训练趋势预测模型
X = np.arange(len(prices)).reshape(-1,1)
context.trend_model.fit(X, prices)
# 动态参数调整
adjust_parameters(context)
def adjust_parameters(context):
"""根据波动率自适应调整参数"""
vol_coeff = 1 + (context.volatility - 0.005) * 50
context.adaptive_params.update({
"open_threshold": max(0.0015, 0.002 * vol_coeff),
"stop_loss": min(0.006, 0.004 * vol_coeff),
"take_profit": 0.0055 * (1 + context.volatility*20)
})
def check_market(context):
if not istradertime(context.symbol):
return
current_price = get_dynainf(context.symbol, 7)
pred_trend = context.trend_model.predict([[context.adaptive_params["momentum_window"]]])[0][0]
# 多因子决策逻辑
entry_signal = 0
if context.position == 0:
if current_price > pred_trend * 1.0015:
entry_signal = 1
elif current_price < pred_trend * 0.9985:
entry_signal = -1
else:
if (context.position == 1 and current_price < pred_trend) or \
(context.position == -1 and current_price > pred_trend):
close_position(context)
return
# 执行交易逻辑
execute_trading(context, current_price, pred_trend, entry_signal)
def execute_trading(context, price, pred, signal):
equity = get_account(19)
position_size = int((equity * context.risk_ratio) / (context.max_layers * price))
# 开仓逻辑
if signal != 0 and context.layer == 0:
open_position(context, signal, position_size*2) # 首仓加倍
return
# 加仓逻辑
if context.layer < context.max_layers and context.position == signal:
price_diff = abs(price - context.base_price)/context.base_price
if price_diff > context.adaptive_params["open_threshold"]*(context.layer**0.5):
add_position(context, position_size)
# 止盈止损
current_profit = (price - context.base_price)/context.base_price * context.position
if current_profit > context.adaptive_params["take_profit"]*(context.layer**0.7):
close_position(context)
elif current_profit < -context.adaptive_params["stop_loss"]*(context.layer**0.5):
close_position(context)
|
|