Monday, February 22, 2016

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

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.

Use the following code:

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

####Using quantmod####
####Single Stock data####

suppressPackageStartupMessages(library(quantmod))

getSymbols("WIPRO.Ns", from="2015-01-01", to="2015-02-22")

#### multiple Stocks data Method-1 (each as seperate dataset) ####

getSymbols(c("WIPRO.NS","TCS.NS","INFY.NS"), from="2015-01-01", to="2015-02-22")

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

####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", 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####
library(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.

0 comments:

Post a Comment

Top Ad unit 728 × 90

Food

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

Contact Us
A.Sulthan
@sulthankhan
India