Financial Trading in Python
Chelsea Yang
Data Science Instructor
Trend-following
Mean reversion
The trend is your friend.
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()
# 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
# 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'])
# Define the strategy bt_strategy = bt.Strategy('EMA_crossover',
[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