Last active
April 5, 2017 23:22
-
-
Save dled/138a74ffe7dd00262a64e7d15577c2fc to your computer and use it in GitHub Desktop.
Example stock beta using a modified script from Daniel Khosravi: http://danialk.github.io/blog/2015/12/19/calculating-stocks-beta-using-r/
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
# http://danialk.github.io/blog/2015/12/19/calculating-stocks-beta-using-r/ | |
# https://finance.yahoo.com/quote/NFLX/history?period1=1358668800&period2=1491379200&interval=1d&filter=history&frequency=1d | |
# https://finance.yahoo.com/quote/%5EGSPC/history?period1=1358668800&period2=1491379200&interval=1d&filter=history&frequency=1d | |
nflx <- read.csv('nflx_2013-01-20_2017-04-05.csv' | |
, sep = ',' | |
, header = T | |
, stringsAsFactors = F) | |
spx <- read.csv('gspc_2013-01-20_2017-04-05.csv' | |
, sep = ',' | |
, header = T | |
, stringsAsFactors = F) | |
# Making sure R knows the Date column is Date | |
nflx$Date <- as.Date(nflx$Date) | |
spx$Date <- as.Date(spx$Date) | |
range <- nflx$Date == spx$Date | |
# Extract daily closing prices | |
nflxPrices <- nflx$Close[range] | |
spxPrices <- spx$Close[range] | |
# Calculating the daily return, e.g (x2-x1)/x1 | |
nflxReturns <- ( nflxPrices[1:(length(nflxPrices) - 1)] - nflxPrices[2:length(nflxPrices)] ) / nflxPrices[2:length(nflxPrices)] | |
spxReturns <- ( spxPrices[1:(length(spxPrices) - 1)] - spxPrices[2:length(spxPrices)] ) / spxPrices[2:length(spxPrices)] | |
# y ~ x is our formula | |
fit <- lm(nflxReturns ~ spxReturns) | |
result <- summary(fit) | |
# summary gives us a lot of useful information, but we're mostly in beta value !! | |
beta <- result$coefficients[2,1] | |
print(beta) | |
# Call (from 2013-01-20 to 2017-04-05) | |
# lm(formula = nflxReturns ~ spxReturns) | |
# Residuals: | |
# Min 1Q Median 3Q Max | |
# -0.86066 -0.01247 -0.00150 0.01025 0.42093 | |
# Coefficients: | |
# Estimate Std. Error t value Pr(>|t|) | |
# (Intercept) 0.001292 0.001232 1.048 0.295 | |
# spxReturns 1.308468 0.155087 8.437 <2e-16 *** | |
# --- | |
# Signif. codes: | |
# 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 | |
# Residual standard error: 0.04 on 1056 degrees of freedom | |
# Multiple R-squared: 0.06315, Adjusted R-squared: 0.06226 | |
# F-statistic: 71.18 on 1 and 1056 DF, p-value: < 2.2e-16 | |
# NFLX BETA ~ 1.308468 | |
# Call (from 2012-01-01 to 2017-04-05) | |
# lm(formula = nflxReturns ~ spxReturns) | |
# Residuals: | |
# Min 1Q Median 3Q Max | |
# -0.86050 -0.01334 -0.00160 0.01107 0.42114 | |
# Coefficients: | |
# Estimate Std. Error t value Pr(>|t|) | |
# (Intercept) 0.001085 0.001111 0.977 0.329 | |
# spxReturns 1.245764 0.139271 8.945 <2e-16 *** | |
# NFLX BETA ~ 1.2457 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment