均值回归策略

Python 中的金融交易

Chelsea Yang

Data Science Instructor

基于 RSI 的均值回归策略

"恐慌时买入,贪婪时卖出"

 

  • 基于 RSI 的均值回归策略:
    • 做空信号:RSI > 70
      • 表明可能超买,价格或将回落
    • 做多信号:RSI < 30
      • 表明可能超卖,价格或将反弹
Python 中的金融交易

计算指标

import talib
# Calculate the RSI
stock_rsi = talib.RSI(price_data['Close']).to_frame()
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
Python 中的金融交易

绘制信号

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

RSI plot

# 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-based Signal plot

Python 中的金融交易

用信号定义策略

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

RSI mean-reversion backtest result

Python 中的金融交易

¡Vamos a practicar!

Python 中的金融交易

Preparing Video For Download...