3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
指数平均数指标(EXPMA)是一种兼具趋势跟踪与平滑特性的动量指标。在 PTrade 平台中,我们可以通过自定义 Python 函数计算 EXPMA 指标,并结合 handle_data 盘中事件构建量化交易策略。
EXPMA 的计算公式如下:
本策略采用快慢 EXPMA 双线交叉策略:
# 指数平滑计算函数
def calc_expma(price_array, period):
alpha = 2.0 / (period + 1)
expma = price_array[0]
for p in price_array[1:]:
expma = alpha * p + (1 - alpha) * expma
return expma
def initialize(context):
# 设置标的股票(以恒生电子为例)
g.security = '600570.SS'
set_universe(g.security)
# 设置指标参数
g.short_period = 12
g.long_period = 26
def handle_data(context, data):
security = g.security
# 获取足够周期的历史收盘价数据
df = get_history(100, '1d', 'close', security, fq=None, include=False)
if df is None or len(df) < g.long_period:
return
close_prices = df['close'].values
# 计算当前与前一交易日的快慢 EXPMA 值
short_expma = calc_expma(close_prices, g.short_period)
long_expma = calc_expma(close_prices, g.long_period)
prev_short_expma = calc_expma(close_prices[:-1], g.short_period)
prev_long_expma = calc_expma(close_prices[:-1], g.long_period)
# 获取当前持仓与可用资金
pos = get_position(security)
current_amount = pos.amount if pos else 0
cash = context.portfolio.cash
# 金叉买入
if prev_short_expma <= prev_long_expma and short_expma > long_expma:
if cash > 0:
order_value(security, cash)
log.info("EXPMA 金叉,买入 %s" % security)
# 死叉卖出
elif prev_short_expma >= prev_long_expma and short_expma < long_expma:
if current_amount > 0:
order_target(security, 0)
log.info("EXPMA 死叉,卖出 %s" % security)
get_history 时,count 参数需保证大于最大周期数(例如 26),以确保指数平滑递推计算的准确性。get_history 中设置 fq='pre'(前复权),避免因除权除息导致价格跳空进而产生错误的交易信号。