Creating arraylist using for loop - r

I want to create an arraylist of the price data of certain stocks.
First, I selected my basket of stocks using:
tickers <- c("^GSPC","MSFT","INTC","NVDA","AAPL")
Next, I downloaded the price data using a for loop function:
for (i in 1:length(tickers)) {
getSymbols(tickers[i],
from = as.Date("2006-01-01"), to = as.Date("2009-12-31"))
}
Now, I want to add each stock data into an arraylist, so I tried something like this:
s <- list()
for (i in 1:length(tickers)) {
getSymbols(tickers[i],
from = as.Date("2006-01-01"), to = as.Date("2009-12-31")) %>%
{. ->> s[[i]]}
}
But the output seems to only give me an arraylist of the name of the stocks:
[[1]] [1] "GSPC"
[[2]] [1] "MSFT"
[[3]] [1] "INTC"
[[4]] [1] "NVDA"
[[5]] [1] "AAPL"
Is there something wrong with the code I gave after the pipe function?

Just use lapply to create your list object and make sure to set the option auto.assign to FALSE.
library(quantmod)
tickers <- c("^GSPC","MSFT","INTC","NVDA","AAPL")
# Get the ticker data
s <- lapply(tickers, getSymbols, from = as.Date("2006-01-01"), to = as.Date("2009-12-31"), auto.assign = FALSE)
# name the list objects
names(s) <- tickers
str(s)
List of 5
$ ^GSPC:An ‘xts’ object on 2006-01-03/2009-12-30 containing:
Data: num [1:1006, 1:6] 1248 1269 1273 1273 1285 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:6] "GSPC.Open" "GSPC.High" "GSPC.Low" "GSPC.Close" ...
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 2
..$ src : chr "yahoo"
..$ updated: POSIXct[1:1], format: "2018-12-07 15:01:48"
$ MSFT :An ‘xts’ object on 2006-01-03/2009-12-30 containing:
.....

Related

Adding name to the first column in r

my dataset is missing name for the first column (there are dates in it)
I tried colnames(managers)[1] <- "date" but it renamed the second column
> #load data
> data(managers)
> colnames(managers)[1] <- "date"
> View(head(managers,10))
> str(managers)
An ‘xts’ object on 1996-01-31/2006-12-31 containing:
Data: num [1:132, 1:10] 0.0074 0.0193 0.0155 -0.0091 0.0076 -0.0039 -0.0231 0.0395 0.0147 0.0288 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:10] "date" "HAM2" "HAM3" "HAM4" ...
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
NULL
dataset headers
The 'managers' is an xts object and the dates are the index
library(PerformanceAnalytics)
index(managers)
#[1] "1996-01-31" "1996-02-29" "1996-03-31" "1996-04-30" "1996-05-31" "1996-06-30" ...
The columns of the dataset are
colnames(managers)
#[1] "HAM1" "HAM2" "HAM3" "HAM4" "HAM5" "HAM6" "EDHEC LS EQ" "SP500 TR" "US 10Y TR" "US 3m TR"
If we want to convert it to data.frame, then use fortify.zoo
library(zoo)
managers1 <- fortify.zoo(managers)
colnames(managers)[1] <- 'date'
Or specify the names in fortify.zoo
managers1 <- fortify.zoo(managers, names = "date")

Converting xts objects from FRED to data.table

I have an xts object from FRED, and would like to convert it to a data.table (or a dataframe) object instead. The relevant code is:
library(data.table)
library(quantmod)
library(Quandl)
library(zoo)
library(knitr)
library(ggplot2)
dataTableTemp <- getSymbols('DJIA', src='FRED')
dataTableTemp <- as.data.table(dataTableTemp)
And this is the content of the xts object it gets:
DJIA
2007-08-08 13657.86
2007-08-09 13270.68
2007-08-10 13239.54
... ...
str(DJIA), which is the name it is given when it downloads, gives
> str(DJIA)
An ‘xts’ object on 2007-08-08/2017-08-08 containing:
Data: num [1:2610, 1] 13658 13271 13240 13237 13029 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr "DJIA"
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 2
$ src : chr "FRED"
$ updated: POSIXct[1:1], format: "2017-08-09 09:41:49"
It goes on like that for a few thousand rows. When I convert it to a data.table with the second line of code, however, this is all that there is (in a table format):
dataTableTemp
1 DJIA
I've tried using fortify(dataTableTemp) from ggplot2, in addition to
dataTableTemp <- data.frame(date=index(dataTableTemp), coredata(dataTableTemp)), and even the tribble() method, but none of them seem to work. What should I do to convert it to a dataframe/data.table?
Any help would be appreciated. Thank you.
So that others know how this issue was solved:
getSymbols('DJIA', src='FRED')
dataTableTemp <- as.data.table(DJIA)
You can get the result you expect, if you adjust the auto.assign parameter in getSymbols:
# Note the auto.assign = FALSE parameter specification (this will avoid assigning the data to JDIA in the global environment.:
dataTableTemp <- getSymbols('DJIA', src='FRED', auto.assign = FALSE)
x = data.table("date" = index(dataTableTemp), coredata(dataTableTemp))

Merge output from quantmod::getSymbols

I looked many entries on merging R data frames, however they are not clear to me, they talk about merging/joining using a common column, but in my case its missed or may I don't know how to extract. Here is what I am doing.
library(quantmod)
library(xts)
start = '2001-01-01'
end = '2015-08-14'
ticker = 'AAPL'
f = getSymbols(ticker, src = 'yahoo', from = start, to = end, auto.assign=F)
rsi14 <- RSI(f$AAPL.Adjusted,14)
The output I am expecting is all the columns of f and rsi14 match by date, however 'date' is not available as column, so not sure how do I join. I have to join few Moving Average columns as well.
The premise of your question is wrong. getSymbols returns an xts object, not a data.frame:
R> library(quantmod)
R> f <- getSymbols("AAPL", auto.assign=FALSE)
R> str(f)
An ‘xts’ object on 2007-01-03/2015-08-14 containing:
Data: num [1:2170, 1:6] 86.3 84 85.8 86 86.5 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:6] "AAPL.Open" "AAPL.High" "AAPL.Low" "AAPL.Close" ...
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 2
$ src : chr "yahoo"
$ updated: POSIXct[1:1], format: "2015-08-15 00:46:49"
xts objects do not have a "Date" column. They have an index attribute that holds the datetime. xts extends zoo, so please see the zoo vignettes as well as the xts vignette and FAQ for information about how to use the classes.
Merging xts objects is as simple as:
R> f <- merge(f, rsi14=RSI(Ad(f), 14))
Or you could just use $<- to add/merge a column to an existing xts object:
R> f$rsi14 <- RSI(Ad(f), 14)

R - quantmod, how to reference getsymbol data later in script

very new to programming in R - but I am stumped on this one:
I'd like to only have to enter stock symbol data once in the script, but can't figure out how to reference ie adjusted close later on using Ad(x) without having to type the stock name again. I've tried passing a variable in like below but get error messages:
#get stock series data
stockPair <- c("SPY","DIA")
look_per <- "2015-01-01"
stckA <- suppressWarnings(getSymbols(stockPair[1], from = look_per))
stckB <- suppressWarnings(getSymbols(stockPair[2], from = look_per))
#get Adjusted close data
adA <- Ad(stckA )
adB <- Ad(stckB )
Error in Ad(stckA) :
subscript out of bounds: no column name containing "Adjusted"
The first thing you should do when you get an error is to look at your data. In this case, stckA and stckB are not what you think they are.
R> stckA <- suppressWarnings(getSymbols(stockPair[1], from = look_per))
R> stckB <- suppressWarnings(getSymbols(stockPair[2], from = look_per))
R> str(stckA)
chr "SPY"
R> str(stckB)
chr "DIA"
As you can see, those two objects are only character strings of the symbols returned by getSymbols, not the data. You need to set auto.assign=FALSE if you want to assign the output of getSymbols to an object.
R> stckA <- getSymbols(stockPair[1], from = look_per, auto.assign = FALSE)
R> str(Ad(stckA)) # now stckA contains data
An ‘xts’ object on 2015-01-02/2015-08-05 containing:
Data: num [1:149, 1] 204 200 198 200 204 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr "SPY.Adjusted"
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 2
$ src : chr "yahoo"
$ updated: POSIXct[1:1], format: "2015-08-05 20:02:30"

R dataframe define column names at creation

I get monthly price value for the two assets below from Yahoo:
if(!require("tseries") | !require(its) ) { install.packages(c("tseries", 'its')); require("tseries"); require(its) }
startDate <- as.Date("2000-01-01", format="%Y-%m-%d")
MSFT.prices = get.hist.quote(instrument="msft", start= startDate,
quote="AdjClose", provider="yahoo", origin="1970-01-01",
compression="m", retclass="its")
SP500.prices = get.hist.quote(instrument="^gspc", start=startDate,
quote="AdjClose", provider="yahoo", origin="1970-01-01",
compression="m", retclass="its")
I want to put these two into a single data frame with specified columnames (Pandas allows this now - a bit ironic since they take the data.frame concept from R). As below, I assign the two time series with names:
MSFTSP500.prices <- data.frame(msft = MSFT.prices, sp500= SP500.prices )
However, this does not preserve the column names [msft, snp500] I have appointed. I need to define column names in a separate line of code:
colnames(MSFTSP500.prices) <- c("msft", "sp500")
I tried to put colnames and col.names inside the data.frame() call but it doesn't work. How can I define column names while creating the data frame?
I found ?data.frame very unhelpful...
The code fails with an error message indicating no availability of as.its. So I added the missing code (which appears to have been successful after two failed attempts.) Once you issue the missing require() call you can use str to see what sort of object get.hist.quote actually returns. It is neither a dataframe nor a zoo object, although it resembles a zoo-object in many ways:
> str(SP500.prices)
Formal class 'its' [package "its"] with 2 slots
..# .Data: num [1:180, 1] 1394 1366 1499 1452 1421 ...
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:180] "2000-01-02" "2000-01-31" "2000-02-29" "2000-04-02" ...
.. .. ..$ : chr "AdjClose"
..# dates: POSIXct[1:180], format: "2000-01-02 16:00:00" "2000-01-31 16:00:00" ...
If you run cbind on those two objects you get a regular matrix with dimnames:
> str(cbind(SP500.prices, MSFT.prices) )
num [1:180, 1:2] 1394 1366 1499 1452 1421 ...
- attr(*, "dimnames")=List of 2
..$ : chr [1:180] "2000-01-02" "2000-01-31" "2000-02-29" "2000-04-02" ...
..$ : chr [1:2] "AdjClose" "AdjClose"
You will still need to change the column names since there does not seem to be a cbind.its that lets you assign column-names. I would caution about using the data.frame method, since the object is might get confusing in its behavior:
> str( MSFTSP500.prices )
'data.frame': 180 obs. of 2 variables:
$ AdjClose :Formal class 'AsIs', 'its' [package ""] with 1 slot
.. ..# .S3Class: chr "AsIs" "its"
$ AdjClose.1:Formal class 'AsIs', 'its' [package ""] with 1 slot
.. ..# .S3Class: chr "AsIs" "its"
The columns are still S4 objects. I suppose that might be useful if you were going to pass them to other its-methods but could be confusing otherwise. This might be what you were shooting for:
> MSFTSP500.prices <- data.frame(msft = as.vector(MSFT.prices),
sp500= as.vector(SP500.prices) ,
row.names= as.character(MSFT.prices#dates) )
> str( MSFTSP500.prices )
'data.frame': 180 obs. of 2 variables:
$ msft : num 35.1 32 38.1 25 22.4 ...
$ sp500: num 1394 1366 1499 1452 1421 ...
> head(rownames(MSFTSP500.prices))
[1] "2000-01-02 16:00:00" "2000-01-31 16:00:00" "2000-02-29 16:00:00"
[4] "2000-04-02 17:00:00" "2000-04-30 17:00:00" "2000-05-31 17:00:00"
MSFT.prices is a zoo object, which seems to be a data-frame-alike, with its own column name which gets transferred to the object. Confer
tmp <- data.frame(a=1:10)
b <- data.frame(lost=tmp)
which loses the second column name.
If you do
MSFTSP500.prices <- data.frame(msft = as.vector(MSFT.prices),
sp500=as.vector(SP500.prices))
then you will get the colnames you want (though you won't get zoo-specific behaviours). Not sure why you object to renaming columns in a second command, though.

Resources