趋势跟随策略

Python 中的金融交易

Chelsea Yang

Data Science Instructor

两类交易策略

趋势跟随

  • 押注价格趋势将延续同向
  • 用移动平均、ADX 等趋势指标构建交易信号

均值回归

  • 押注价格会回到均值附近
  • 用 RSI、布林带等指标构建交易信号
Python 中的金融交易

均线交叉策略

趋势是你的朋友。

 

  • 双 EMA 交叉:
    • 做多信号:短期 EMA 上穿长期 EMA
    • 做空信号:短期 EMA 下穿长期 EMA
Python 中的金融交易

计算指标

import talib
# Calculate the indicators
EMA_short = talib.EMA(price_data['Close'],
                      timeperiod=10).to_frame()
EMA_long = talib.EMA(price_data['Close'], 
                     timeperiod=40).to_frame()
Python 中的金融交易

构建信号

# Create the signal DataFrame
signal = EMA_long.copy()
signal[EMA_long.isnull()] = 0

# Construct the signal signal[EMA_short > EMA_long] = 1
signal[EMA_short < EMA_long] = -1
Python 中的金融交易

绘制信号

# Plot the signal, price and MAs
combined_df = bt.merge(signal, price_data, EMA_short, EMA_long)
combined_df.columns = ['Signal', 'Price', 'EMA_short', 'EMA_long']

combined_df.plot(secondary_y=['Signal'])

EMA交叉信号图

Python 中的金融交易

用信号定义策略

# Define the strategy
bt_strategy = bt.Strategy('EMA_crossover',

[bt.algos.WeighTarget(signal), bt.algos.Rebalance()])
Python 中的金融交易

回测基于信号的策略

# Create the backtest and run it
bt_backtest = bt.Backtest(bt_strategy, price_data)
bt_result = bt.run(bt_backtest)
Python 中的金融交易

绘制回测结果

# Plot the backtest result
bt_result.plot(title='Backtest result')

均线交叉回测结果

Python 中的金融交易

Passons à la pratique !

Python 中的金融交易

Preparing Video For Download...