Perform the following steps to analyze stock returns:
diff
function that returns an array built up of the difference between two consecutive array elements. This is sort of like differentiation in calculus. To get the returns, we also have to divide by the value of the previous day. We must be careful though. The array returned by diff
is one element shorter than the close prices array. After careful deliberation, we get the following code:returns = np.diff( arr ) / arr[ : -1]
Notice that we don't use the last value in the divisor. Let's compute the standard deviation using the std
function:
print "Standard deviation =", np.std(returns)
This results in the following output:
Standard deviation = 0.0129221344368
log
function to get the log of the close price and then unleash the diff
function on the result.logreturns = np.diff( np.log(c) )
Normally, we would have to check that the input array doesn't have zeroes or negative numbers. If it did, we would have got an error. Stock prices are, however, always positive, so we didn't have to check.
where
function, which returns the indices of an array that satisfies a condition. Just type the following code:posretindices = np.where(returns > 0) print "Indices with positive returns", posretindices
This gives us a number of indices for the array elements that are positive.
Indices with positive returns (array([ 0, 1, 4, 5, 6, 7, 9, 10, 11, 12, 16, 17, 18, 19, 21, 22, 23, 25, 28]),)
std
and mean
functions. See the following code:annual_volatility = np.std(logreturns)/np.mean(logreturns) annual_volatility = annual_volatility / np.sqrt(1./252.) print annual_volatility
sqrt
function. Since, in Python, integer division works differently than float division, we needed to use floats to make sure that we get the proper results. Similarly, the monthly volatility is given by:print "Monthly volatility", annual_volatility * np.sqrt(1./12.)
We calculated the simple stock returns with the diff
function, which calculates differences between sequential elements. The log
function computes the natural logarithms of array elements. We used it to calculate the logarithmic returns. At the end of the tutorial we calculated the annual and monthly volatility (see returns.py
).
import numpy as np c=np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True) returns = np.diff( c ) / c[ : -1] print "Standard deviation =", np.std(returns) logreturns = np.diff( np.log(c) ) posretindices = np.where(returns > 0) print "Indices with positive returns", posretindices annual_volatility = np.std(logreturns)/np.mean(logreturns) annual_volatility = annual_volatility / np.sqrt(1./252.) print "Annual volatility", annual_volatility print "Monthly volatility", annual_volatility * np.sqrt(1./12.)