Financial Trading in Python
Chelsea Yang
Data Science Instructor
Buy the fear and sell the greed
import talib
# Calculate the RSI
stock_rsi = talib.RSI(price_data['Close']).to_frame()
# 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
# Plot the RSI
stock_rsi.plot()
plt.title('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'])
# Define the strategy
bt_strategy = bt.Strategy('RSI_MeanReversion',
[bt.algos.WeighTarget(signal),
bt.algos.Rebalance()])
# Create the backtest and run it
bt_backtest = bt.Backtest(bt_strategy, price_data)
bt_result = bt.run(bt_backtest)
# Plot the backtest result
bt_result.plot(title='Backtest result')
Financial Trading in Python