Python for Finance: Analyze Big Financial Data

(Elle) #1

traders might be more interested in moving averages, or so-called trends. A moving


average is easily calculated with the rolling_mean function of pandas (there are other


“rolling” functions as well, like rolling_max, rolling_min, and rolling_corr):


In  [ 57 ]: DAX[‘42d’]  =   pd.rolling_mean(DAX[‘Close’],   window= 42 )
DAX[‘252d’] = pd.rolling_mean(DAX[‘Close’], window= 252 )
In [ 58 ]: DAX[[‘Close’, ‘42d’, ‘252d’]].tail()
Out[58]: Close 42d 252d
Date
2014-09-22 9749.54 9464.947143 9429.476468
2014-09-23 9595.03 9463.780952 9433.168651
2014-09-24 9661.97 9465.300000 9437.122381
2014-09-25 9510.01 9461.880476 9440.479167
2014-09-26 9490.55 9459.425000 9443.769008

A typical stock price chart with the two trends included then looks like Figure 6-5:


In  [ 59 ]: DAX[[‘Close’,   ‘42d’,  ‘252d’]].plot(figsize=( 8 ,  5 ))

Figure 6-5. The DAX index and moving averages

Returning to the more options trader-like perspective, the moving historical standard


deviation of the log returns — i.e. the moving historical volatility — might be more of


interest:


In  [ 60 ]: import math
DAX[‘Mov_Vol’] = pd.rolling_std(DAX[‘Return’],
window= 252 ) * math.sqrt( 252 )
# moving annual volatility

Figure 6-6 further supports the hypothesis of the leverage effect by clearly showing that


the historical moving volatility tends to increase when markets come down, and to


decrease when they rise:


In  [ 61 ]: DAX[[‘Close’,   ‘Mov_Vol’,  ‘Return’]].plot(subplots=True,  style=‘b’,
figsize=( 8 , 7 ))
Free download pdf