Importing Historical Data from Yahoo Finance following the API Crash — R code

It has been almost three weeks now that Yahoo Finance API is down. Unfortunately, this makes life harder when trying to process stock data for example and calculate daily returns. If you’re using R or Python to download data directly through the API here’s what you’ll get :

In Python (Using the pandas data web reader package) :

In R — using getsymbols(‘AAPL’) for instance:

Here’s a code in R that allow you, after downloading the csv files, to process the stock data and get daily returns for the SP500 :

1/ Download the csv file and put it in a directory and put the directory address in the string dir :

dir = “C:/Users/lenovo/Desktop/Cours/T3 2016/Financial Econometrics/Homeworks/Homework2/”

2/ Then read the csv file through the following command :

GSPC <- na.omit(read_csv(paste(dir,”^GSPC.csv”,sep=””) ,
col_types = cols(Close = col_skip(),
High = col_skip(), Low = col_skip(),
Open = col_skip(), Volume = col_skip()),
na = “null”))
#here the file name is ^GSPC.csv and I choose to skip all the High,Open, Low, Volume colums to keep only Close and Adj Close.

Now the object GSPC is an object containing the colums of your csv file, let’s calculate the daily returns :

3/ Calculate daily returns

# transform the date colum into recognizable date for R :
GSPC$Date <- as.Date(GSPC$Date, format=”%d/%m/%Y”)
GSPC$GSPC.logp = log(GSPC$`Adj Close`)
GSPC_rtn <- diff(GSPC$GSPC.logp)*100
GSPC$GSPC.rtn = c(0,GSPC_rtn)
GSPC$GSPC.rtn <- xts(GSPC$GSPC.rtn, =GSPC$Date)

There you go, the GSPC object now contains a column called rtn where your daily returns are stored, let’s plot them :