R code to compute beta and the Sharpe ratio for a publicly traded stock

The following R code will calculate beta and the Sharpe ratio using adjusted closing prices from Yahoo finance.

A video describing the output using an earlier version of this routine is available at

http://www.youtube.com/watch?v=U8rNmkFRT1M

# calculate beta and the Sharpe ratio

suppressPackageStartupMessages(require(quantmod))

BRCM.Quote <- getSymbols.yahoo(“BRCM”, from=”1950-01-01″, verbose=FALSE, auto.assign=FALSE)
SPX.Quote <- getSymbols.yahoo(“^GSPC”, from=”1950-01-01″, verbose=FALSE, auto.assign=FALSE)

Prices <- cbind(SPX.Quote, BRCM.Quote)
Prices <- Prices[apply(Prices, 1, function(x) all(!is.na(x))),c(“GSPC.Adjusted”,”BRCM.Adjusted”)]

Returns <- as.xts(tail(data.frame(Prices),-1) / head(data.frame(Prices),-1) – 1)

lm(BRCM.Adjusted ~ GSPC.Adjusted, data.frame(Returns[“2002-08-20/2012-08-20”]))

lreg <- lm(BRCM.Adjusted ~ GSPC.Adjusted, data.frame(Returns[“2002-08-20/2012-08-20”]))

summary(lreg)
anova(lreg)

mean(Returns[“2002-08-20/2012-08-20″,”BRCM.Adjusted”])
sd(as.numeric(Returns[“2002-08-20/2012-08-20″,”BRCM.Adjusted”]))

mret <- mean(Returns[“2002-08-20/2012-08-20″,”BRCM.Adjusted”])
sdret <- sd(as.numeric(Returns[“2002-08-20/2012-08-20″,”BRCM.Adjusted”]))
(mret * 252 – .05) / (sdret * sqrt(252))

Advertisements
Comments
2 Responses to “R code to compute beta and the Sharpe ratio for a publicly traded stock”
  1. lili says:

    Hello! Could you show a code for calculating an appraisal ratio in R? Thank you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: