In this screencast, I demonstrate how to use R to download historical price data from Yahoo! Finance.  I also demonstrate how to convert the price data series into a return data series, and I show how to write the output to a file which can be read into a spreadsheet program such as Excel or Google Docs Spreadsheet.

I use the return data that this script generates to run CAPM and Fama-French regressions and to compute performance metrics such as Sharpe Ratios.  However, I note in the presentation that I have found that Yahoo! Finance frequently has errors in the historical price series, so users should use caution when using the return data generated from these historical prices to make financial decisions.

The code used in this screencast is pasted below, and the slides used in the screencase are available here.

# Goal: download adjusted price data for selected security, convert to returns, and write to output file


# Load security data from Yahoo! Finance
prices1 <- get.hist.quote("SPY", quote="Adj", start="2005-12-25", retclass="zoo")

prices1 <- na.locf(prices1)               # Copy last traded price when NA

# To make week end prices:
nextfri.Date <- function(x) 7 * ceiling(as.numeric(x - 1)/7) + as.Date(1)
weekly.prices <- aggregate(prices, nextfri.Date,tail,1)

# To convert month end prices:
monthly.prices <- aggregate(prices1, as.yearmon, tail, 1)

# Convert weekly prices into weekly returns
r.weekly <- diff(log(weekly.prices)) # convert prices to log returns
r1.weekly <- exp(r.weekly)-1          # back to simple returns

# Convert monthly prices into monthly returns
r.monthly <- diff(log(monthly.prices))  # convert prices to log returns
r1.monthly <- exp(r.monthly)-1          # back to simple returns

# Write output data to csv file
write.zoo(r1.weekly, file="weekly.csv",sep=",",col.names=c("Dates","Percent Return"))
write.zoo(r1.monthly, file="monthly.csv",sep=",",col.names=c("Dates","Percent Return"))