Time for action – analyzing stock returns

Perform the following steps to analyze stock returns:

  1. First, let's calculate simple returns. NumPy has the diff() function that returns an array that is built up of the difference between two consecutive array elements. This is sort of like differentiation in calculus (the derivative of price with respect to time). 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. The standard deviation is equal to the square root of variance. Compute the standard deviation using the std() function:

    print("Standard deviation =", np.std(returns))

    This results in the following output:

    Standard deviation = 0.0129221344368
    
  2. The log return or logarithmic return is even easier to calculate. Use the log() function to get the natural logarithm of the close price and then unleash the diff() function on the result:
    logreturns = np.diff(np.log(c))

    Normally, we have to check that the input array doesn't have zeros or negative numbers. If it does, we will get an error. Stock prices are, however, always positive, so we didn't have to check.

  3. Quite likely, we will be interested in days when the return is positive. In the current setup, we can get the next best thing with the 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 as a tuple, recognizable by the round brackets on both sides of the printout:

    Indices with positive returns (array([ 0,  1,  4,  5,  6,  7,  9, 10, 11, 12, 16, 17, 18, 19, 21, 22, 23, 25, 28]),)
    
  4. In investing, volatility measures price variation of a financial security. Historical volatility is calculated from historical price data. The logarithmic returns are interesting if you want to know the historical volatility—for instance, the annualized or monthly volatility. The annualized volatility is equal to the standard deviation of the log returns as a ratio of its mean, divided by one over the square root of the number of business days in a year, usually one assumes 252. Calculate it with the std() and mean() functions, as in the following code:
    annual_volatility = np.std(logreturns)/np.mean(logreturns)
    annual_volatility = annual_volatility / np.sqrt(1./252.)
    print(annual_volatility)

    Take notice of the division within the 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. The monthly volatility is similarly given by the following code:

    print("Monthly volatility", annual_volatility * np.sqrt(1./12.))

What just happened?

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 this section, we calculated the annual and monthly volatility (see returns.py):

from __future__ import print_function
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.))
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset