一、核心概念對(duì)比表
二、5步遷移法(以MACD為例)步驟1:數(shù)據(jù)準(zhǔn)備# 通達(dá)信 DIF:EMA(CLOSE,12)-EMA(CLOSE,26); DEA:EMA(DIF,9); # PTrade def calculate_macd(df): # 計(jì)算EMA ema12 = df['close'].ewm(span=12, adjust=False).mean() ema26 = df['close'].ewm(span=26, adjust=False).mean() dif = ema12 - ema26 dea = dif.ewm(span=9, adjust=False).mean() return dif, dea 步驟2:信號(hào)檢測(cè)# 通達(dá)信 CROSS(DIF,DEA),BPK; // 金叉做多 CROSS(DEA,DIF),SPK; // 死叉平倉 # PTrade # 獲取最近兩天的DIF和DEA值 dif_current = dif.iloc[-1] dif_prev = dif.iloc[-2] dea_current = dea.iloc[-1] dea_prev = dea.iloc[-2] # 金叉判斷 golden_cross = (dif_prev < dea_prev) & (dif_current > dea_current) # 死叉判斷 death_cross = (dif_prev > dea_prev) & (dif_current < dea_current) 步驟3:交易執(zhí)行if golden_cross and g.position == 0: # 計(jì)算可買數(shù)量(按整手) cash = context.portfolio.cash price = data[g.security].close shares = int(cash * 0.95 // (price * 100)) * 100 # 95%資金,整手交易 order(g.security, shares) g.position = 1 elif death_cross and g.position == 1: order_target(g.security, 0) g.position = 0 步驟4:避免未來函數(shù)# 重要:使用前日收盤價(jià)計(jì)算信號(hào),當(dāng)日開盤執(zhí)行 def handle_data(context, data): # 獲取截止昨日的數(shù)據(jù)(避免使用當(dāng)日數(shù)據(jù)計(jì)算指標(biāo)) hist = get_history(30, '1d', ['close'], g.security) # 計(jì)算指標(biāo) dif, dea = calculate_macd(hist) # 獲取當(dāng)前倉位 current_position = context.portfolio.positions[g.security].amount 步驟5:可視化驗(yàn)證# 在回測(cè)結(jié)束后添加: def after_trading_end(context): # 記錄指標(biāo)值 record(dif=dif.iloc[-1], dea=dea.iloc[-1]) # 記錄倉位 record(position=g.position*100) # 放大顯示比例 三、常用函數(shù)速查表
四、調(diào)試技巧
# 打印最近5根K線 log.info('最新5日收盤價(jià):\n', hist.tail(5))
if golden_cross: log.info(f'金叉信號(hào):時(shí)間 {context.current_dt}, DIF={dif.iloc[-1]:.2f}, DEA={dea.iloc[-1]:.2f}')
try: order(g.security, 100) except Exception as e: log.error('下單失敗:', str(e)) 五、進(jìn)階優(yōu)化方向
# 獲取1小時(shí)線數(shù)據(jù) hourly_data = get_history(20, '60m', ['close'], g.security)
# 在initialize中設(shè)置股票池 g.stock_pool = ['600519.SH', '000001.SZ'] set_universe(g.stock_pool)
# 使用參數(shù)網(wǎng)格 params = { 'fast_period': range(10, 20, 2), 'slow_period': range(20, 30, 2) } 建議從簡(jiǎn)單的均線策略開始,逐步增加復(fù)雜度。PTrade的實(shí)時(shí)模擬交易功能可以幫助驗(yàn)證策略有效性,建議先用模擬盤運(yùn)行1-2周再實(shí)盤。 |
|