Figure 3-5. Historical levels of the S&P 500 index
The trend strategy we want to implement is based on both a two-month (i.e., 42 trading
days) and a one-year (i.e., 252 trading days) trend (i.e., the moving average of the index
level for the respective period). Again, pandas makes it efficient to generate the respective
time series and to plot the three relevant time series in a single figure. First, the generation
of the trend data:
In [ 36 ]: sp500[‘42d’] = np.round(pd.rolling_mean(sp500[‘Close’], window= 42 ), 2 )
sp500[‘252d’] = np.round(pd.rolling_mean(sp500[‘Close’], window= 252 ), 2 )
In this example, the first line simultaneously adds a new column to the pandas DataFrame
object and puts in the values for the 42-day trend. The second line does the same with
respect to the 252-day trend. Consequently, we now have two new columns. These have
fewer entries due to the very nature of the data we have generated for these columns —
i.e., they start only at those dates when 42 and 252 observation points, respectively, are
available for the first time to calculate the desired statistics:
In [ 37 ]: sp500[[‘Close’, ‘42d’, ‘252d’]].tail()
Out[37]: Close 42d 252d
Date
2014-04-08 1851.96 1853.88 1728.66
2014-04-09 1872.18 1855.66 1729.79
2014-04-10 1833.08 1856.46 1730.74
2014-04-11 1815.69 1856.36 1731.64
2014-04-14 1830.61 1856.63 1732.74
Second, the plotting of the new data. The resulting plot in Figure 3-6 already provides
some insights into what was going on in the past with respect to upward and downward
trends:
In [ 38 ]: sp500[[‘Close’, ‘42d’, ‘252d’]].plot(grid=True, figsize=( 8 , 5 ))