23 February 2016

Simple way to download and export stock data using R - Method 3

you can read the method 1 here: http://www.iamsulthan.in/2016/04/step-by-step-tutorial-to-download.html If you have missed it.

In Security analysis and Portfolio management , the historical prices of a stock or indices is the base data for analysis in that case any researcher want to download and organize the data. Mostly they prefer to save the data in .csv file which is universally imported in any software. A difficulty or time consuming task for such researchers is to organize the data. for example: to check for any missing prices or to organize the closing prices in single worksheet for all companies in case of a multivariate analysis.

Using the following code you can download and export the data to .csv format which can be later used in any other data analysis softwares if you wish whereas R can do almost what other softwares do . It just need proper command to execute your research objectives.



Github link for the code can be located here: download-historical-stock-data-in-R

Use the following code:

========================================================================

####Using quantmod####
####Single Stock data####
if(!require(quantmod)){install.packages("quantmod")}
getSymbols("WIPRO.NS", from="2015-01-01", to= Sys.Date())

#### multiple Stocks data Method-1 (each as seperate dataset) ####
getSymbols("WIPRO.NS;TCS.NS;INFY.NS", from="2015-01-01", to= Sys.Date())

#### multiple Stocks Method-2 (using list)####
stocklist <- c("WIPRO.NS","TCS.NS","INFY.NS","AAPL" )
getSymbols(stocklist, from="2015-01-01", to= Sys.Date())

####multiple Stocks Method-3####
stocklist <- c("WIPRO.NS","TCS.NS","INFY.NS","AAPL") # create list of stock tickers
Adjclose <- NULL
for (Ticker in stocklist)
  Adjclose <- cbind(Adjclose,getSymbols.yahoo(Ticker, from="2015-01-01", to= Sys.Date(), verbose=FALSE, auto.assign=FALSE)[,6]) #get data for companies in list, [,6] = keep the adjusted prices
FinalAdjclose <- na.locf(Adjclose) #copy last traded price in empty cell
FinalAdjclose1 <- Adjclose[apply(Adjclose,1,function(x) all(!is.na(x))),] #keep only dates having closing price
####Export the data to excel####
if(!require(timeSeries)){install.packages("timeSeries")}
data <- as.timeSeries(FinalAdjclose1)
write.csv(data, "data.csv")
========================================================================

I'm a Polymath my learning activities spans over different subject areas and I blog somthing about everthing.

For Consulting about Data Analysis, LaTeX, Word formatting Hire me

Contact Us
A.Sulthan
sulthankhan90
India