均值回歸策略

Financial Trading in Python

Chelsea Yang

Data Science Instructor

基於 RSI 的均值回歸策略

逢低買進,逢高賣出

 

  • 基於 RSI 的均值回歸策略:
    • 做空訊號:RSI > 70
      • 表示資產可能超買,價格或將反轉下跌
    • 做多訊號:RSI < 30
      • 表示資產可能超賣,價格或將反彈上漲
Financial Trading in Python

計算指標

import talib
# Calculate the RSI
stock_rsi = talib.RSI(price_data['Close']).to_frame()
Financial Trading in Python

建構訊號

# Create the same DataFrame structure as RSI
signal = stock_rsi.copy()
signal[stock_rsi.isnull()] = 0

# Construct the signal signal[stock_rsi < 30] = 1
signal[stock_rsi > 70] = -1
signal[(stock_rsi <= 70) & (stock_rsi >= 30)] = 0
Financial Trading in Python

繪製訊號

# Plot the RSI
stock_rsi.plot()
plt.title('RSI')

RSI 圖

# Merge data into one DataFrame
combined_df = bt.merge(signal, stock_data)
combined_df.columns = ['Signal', 'Price']
# Plot the signal with price

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

基於 RSI 的訊號圖

Financial Trading in Python

用訊號定義策略

# Define the strategy
bt_strategy = bt.Strategy('RSI_MeanReversion', 
                          [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')

RSI 均值回歸回測結果

Financial Trading in Python

一起來練習吧!

Financial Trading in Python

Preparing Video For Download...