In [ 53 ]: %time DAX[‘Return’] = np.log(DAX[‘Close’] / DAX[‘Close’].shift( 1 ))
Out[53]: CPU times: user 4 ms, sys: 0 ns, total: 4 ms
Wall time: 1.52 ms
In [ 54 ]: DAX[[‘Close’, ‘Ret_Loop’, ‘Return’]].tail()
Out[54]: Close Ret_Loop Return
Date
2014-09-22 9749.54 -0.005087 -0.005087
2014-09-23 9595.03 -0.015975 -0.015975
2014-09-24 9661.97 0.006952 0.006952
2014-09-25 9510.01 -0.015853 -0.015853
2014-09-26 9490.55 -0.002048 -0.002048
This not only provides the same results with more compact and readable code, but also is
the much faster alternative.
VECTORIZATION WITH DATAFRAMES
In general, you can use the same vectorization approaches with pandas DataFrame objects as you would whenever
you could do such an operation with two NumPy ndarray objects containing the same data.
One column with the log return data is enough for our purposes, so we can delete the other
one:
In [ 55 ]: del DAX[‘Ret_Loop’]
Now let us have a look at the newly generated return data. Figure 6-4 illustrates two
stylized facts of equity returns:
Volatility clustering
Volatility is not constant over time; there are periods of high volatility (both highly
positive and negative returns) as well as periods of low volatility.
Leverage effect
Generally, volatility and stock market returns are negatively correlated; when
markets come down volatility rises, and vice versa.
Here is the code that generates this plot:
In [ 56 ]: DAX[[‘Close’, ‘Return’]].plot(subplots=True, style=‘b’,
figsize=( 8 , 5 ))
Figure 6-4. The DAX index and daily log returns
While volatility is something of particular importance for options traders, (technical) stock