Instantly share code, notes, and snippets.

# StuartGordonReid/Volatility.py

Created June 12, 2015 11:33
Star You must be signed in to star a gist
Volatility Risk Metrics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 import numpy import numpy.random as nrand def vol(returns): # Return the standard deviation of returns return numpy.std(returns) def beta(returns, market): # Create a matrix of [returns, market] m = numpy.matrix([returns, market]) # Return the covariance of m divided by the standard deviation of the market returns return numpy.cov(m) / numpy.std(market) # Example usage r = nrand.uniform(-1, 1, 50) m = nrand.uniform(-1, 1, 50) print("vol =", vol(r)) print("beta =", beta(r, m))

### WilliamJosephKlubinski commented Dec 16, 2019

Hi Stuart,

In line 14: `return numpy.cov(m) / numpy.std(market)` you should replace the `.std` with `.var`. The division in Beta is done with the variance of the market and not standard deviation. Thus, `return numpy.cov(m) / numpy.var(market)`

In the current form, Beta is significantly affecting the results of the Treynor ratio.

PS. It can also be easily tested in Excel e.g. `=COVARIANCE.P(range_of_the_fund,range_of_the_market)/VAR.P(range_of_the_market)`

Hope it helps. Thanks
William Klubinski