According to Investopedia, Beta is a measure of the volatility, or systematic risk, of a security or a portfolio in comparison to the market as a whole. In this post, we’re going to learn how to calculate beta coefficient of our desired stocks using historical price data that is publicly available.
Below we will be covering
- R script to calculate beta for Goldman Sachs
- Maths behind the beta coefficient
In this tutorial we are using S&P500 as our market and we’re calculating beta of Goldman Sachs in relation to S&P500. It’s essentially the correlation of price movements of stocks within the market/index, to individual stocks within the market/index.
In order to calculate beta, we need to obtain historical data for both S&P500 and Goldman Sachs. I’m using Yahoo Finance’s public API in order to get historical quotes.
Follow the code and make sure you read the comments !
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
Mathematically, beta is the covariance of stocks percentage daily/weekly change and index/markets daily/weekly change divided by the variance of market’s percentage daily/weekly changes:
Beta = Covariance(Stock's % Change, Index's % Change)/Variance(Index % Change)
You can replace the
stockUrl with some other company’s data that is in S&P500. Make sure you read the Yahoo Finance API before doing so.
The main purpose of this tutorial is to see how regression can and
lm() can be used in R, but it is also helpful to be able to calculate beta coefficient if you’re running your own portfolio. The value obtained using this script (1.453472) at the time of writing was a little bit off from the values provided by Google Finance(1.67) and Yahoo Finance(1.38) which can be due to using different time spans for their beta calculations. But since those two numbers don’t match, I’d say you should trust the value that you’ve calculated yourself !!
If you made to here, I hope you found it useful !
Please leave a comment if there are any questions, tips or other concerns.