Blogs

Visualizing Backtest Trades

Here's the code:

import numpy as np
import matplotlib.pyplot as plt
import pandas_datareader.data as pdr

df = pdr.DataReader('QQQ', 'yahoo', start='2020-06-30', end='2022-06-30')

df['sma_short'] = df['Close'].rolling(window = 7).mean()
df['sma_long'] = df['Close'].rolling(window = 21).mean()

# create a new column 'Signal' such that if faster moving average is greater than slower moving average
df['Signal'] = np.where(df['sma_short'] > df['sma_long'], 1.0, 0.0)

# create a new column 'Position' : a day-to-day difference of the 'Signal' column.
df['Position'] = df['Signal'].diff()

df_pos = df[(df['Position'] == 1) | (df['Position'] == -1)]
df_pos['Position'] = df_pos['Position'].apply(lambda x: 'Buy' if x == 1 else 'Sell')

fig, ax = plt.subplots(figsize=(12,6))
ax.set_title('QQQ Backtest Trades', fontsize = 20)
ax.plot(df.index, df['Close'], color = 'k', label= 'Close Price' )
ax.plot(df.index, df['sma_short'],color = 'b',label = 'SMA Long' )
ax.plot(df.index, df['sma_long'], color = 'g', label = 'SMA Short')
ax.plot(df[df['Position'] == 1].index, df['sma_short'][df['Position'] == 1],
        '^', markersize = 10, color = 'g', label = 'buy')
ax.plot(df[df['Position'] == -1].index, df['sma_long'][df['Position'] == -1],
        'v', markersize = 10, color = 'r', label = 'sell')
ax.set_ylabel('Price', fontsize = 15 )
ax.set_xlabel('Date', fontsize = 15 )
ax.legend()
ax.grid()
plt.show()

That's the visualization: