
等级: 新手上路
- 注册:
- 2025-3-12
- 曾用名:
|
# 导入必要库
import pandas as pd
import talib
from pylab import *
# 策略参数
FAST_LEN = 20
SLOW_LEN = 60
ATR_LEN = 14
RISK_RATIO = 0.02
# 初始化函数
def initialize(context):
# 设置合约
context.symbol = 'AU88' # 沪金主力合约
context.bar_interval = '1d' # 日线
subscribe(context.symbol, context.bar_interval)
# 策略变量
context.position = 0 # 持仓方向
context.stop_loss = 0 # 动态止损价
context.trail_high = 0 # 波段高点跟踪
# K线处理函数
def handle_bar(context):
# 获取数据
hist = history_bars(context.symbol, max(FAST_LEN, SLOW_LEN, ATR_LEN)*3,
context.bar_interval, ['close','high','low','volume'])
close = hist['close']
high = hist['high']
low = hist['low']
vol = hist['volume']
# 指标计算
ma20 = talib.EMA(close, FAST_LEN) + 0.5*(high[-1] - low[-1])
ma60 = talib.WMA(close, SLOW_LEN)
atr = talib.ATR(high, low, close, ATR_LEN)[-1]
# 交易信号
cross_up = (ma20[-2] < ma60[-2]) and (ma20[-1] > ma60[-1]) # 金叉
cross_down = (ma20[-2] > ma60[-2]) and (ma20[-1] < ma60[-1]) # 死叉
# 辅助条件
vol_cond = vol[-1] > talib.MA(vol, 20)[-1]
cci = talib.CCI(high, low, close, 30)[-1]
hhv_10 = talib.MAX(high[-10:], 10)[-1]
llv_10 = talib.MIN(low[-10:], 10)[-1]
# 构建交易条件
long_cond = cross_up and vol_cond and (cci > -100) and (close[-1] > hhv_10)
short_cond = cross_down and vol_cond and (cci < 100) and (close[-1] < llv_10)
# 仓位管理
if context.current_pos() == 0 and atr > 0:
contract_size = get_contract(context.symbol).multiplier
capital = context.current_capital()
lot = int(capital * RISK_RATIO / (atr * contract_size))
else:
lot = 0
# 交易执行
if context.position == 0:
if long_cond:
order_target(context.symbol, lot)
context.position = 1
context.stop_loss = close[-1] - 3*atr
context.trail_high = high[-1]
elif short_cond:
order_target(context.symbol, -lot)
context.position = -1
context.stop_loss = close[-1] + 3*atr
context.trail_low = low[-1]
# 持仓管理
elif context.position > 0:
context.trail_high = max(context.trail_high, high[-1])
if close[-1] < context.stop_loss or close[-1] < context.trail_high*0.985:
order_target(context.symbol, 0)
context.position = 0
elif context.position < 0:
context.trail_low = min(context.trail_low, low[-1])
if close[-1] > context.stop_loss or close[-1] > context.trail_low*1.015:
order_target(context.symbol, 0)
context.position = 0
# 风险控制
def on_strategy_end(context):
order_target(context.symbol, 0) # 平掉所有持仓
|
|