順勢策略

Financial Trading in Python

Chelsea Yang

Data Science Instructor

兩類交易策略

順勢交易

  • 押注價格趨勢會延續原方向
  • 用移動平均、ADX 等趨勢指標產生交易訊號

均值回歸

  • 押注價格會回到均值附近
  • 用 RSI、布林通道等指標產生交易訊號
Financial Trading in Python

MA 交叉策略

趨勢是你的朋友。

 

  • 雙 EMA 黃金交叉:
    • 做多訊號:短期 EMA 向上穿越長期 EMA
    • 做空訊號:短期 EMA 向下跌破長期 EMA
Financial Trading in 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()
Financial Trading in 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
Financial Trading in 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 交叉訊號圖

Financial Trading in Python

用訊號定義策略

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

[bt.algos.WeighTarget(signal), bt.algos.Rebalance()])
Financial Trading in Python

回測以訊號為基礎的策略

# Create the backtest and run it
bt_backtest = bt.Backtest(bt_strategy, price_data)
bt_result = bt.run(bt_backtest)
Financial Trading in Python

繪製回測結果

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

MA 交叉回測結果

Financial Trading in Python

一起來練習吧!

Financial Trading in Python

Preparing Video For Download...