Quantmod: How do I leave the XTS output variable? - r

I am new to R and quantmod. I am trying to get daily data for a user defined ticker symbol, like this:
check_symbol<-"GOOG"
check_symbol2<-paste0(check_symbol,".Adjusted")
getSymbols(check_symbol)
temp<-as.vector(GOOG[,check_symbol2])
How do I keep GOOG as a variable in the as.vector(GOOG[,check_symbol2]) part of the above code?
Also, any more elegant way of doing this is much appreciated!

It seems like you'd benefit from using auto.assign=FALSE in the call to getSymbols:
check_symbol <- "GOOG"
check_symbol_data <- getSymbols(check_symbol, auto.assign=FALSE)
temp <- as.vector(Ad(check_symbol_data))

Related

using chron package to format data in R

at the moment I'm trying to convert a string into time-format.
e.g. my string looks like following: time <- '12:00'.
I already tried to use the chron-Package. And my code looks like following:
time <- paste(time,':00', sep = '') time <- times(time)
Instead of getting a value like "12:00:00" the function times() always translate the object time into "0.5"
Am I using the wrong approach?
regards
Your code works. If you check the 'class()' it is "times". However, if you want another way, try:
time <- '12:00:00'
newtime<-as.POSIXlt(time, format = "%H:%M:%S") # The whole date with time
t <- strftime(newtime, format="%H:%M:%S") # To extract the time part
t
#[1] "12:00:00"
Cheers !

Using Yahoo! database without quantmod functions

The problem I am trying to solve is looping a string through R with Yahoo! finance api. This would make a bunch of data frame files, but if I could convert it into xts, that would be awesome. However, the xts part is not as important.
library(quantmod)
DB <- quantmod:::DDB_Yahoo()
for (i in length(DB$db)){
symbols <- DB$db[i] #symbols are c('AAIT', 'AAL', 'AAME', ... #Thousands Essentially
URL <- "http://ichart.finance.yahoo.com/table.csv?s=symbols"
dat[i] <- read.csv(URL[i])
dat$Date <- as.Date(dat$Date, "%Y-%m-%d")
I know that we can't have symbols in ("") quotations, but it is for logical purposes.
p.s. For this instance, I am not using quantmod functions on purpose.
x<-c('AAIT', 'AAL', 'AAME')
kk<-lapply(x,function(i) download.file(paste0("http://ichart.finance.yahoo.com/table.csv?s=",i),paste0(i,".csv")))
if you want to directly read the file:
jj<- lapply(x,function(i) read.csv(paste0("http://ichart.finance.yahoo.com/table.csv?s=",i)))

How to convert a zoo object in a ts object in order to use strucchange

Ok. I´ve tried several foruns and threads, but I couldn't find this. I imported my database to R using this:
teste <- read.zoo("bitcoin2.csv", header=TRUE, sep=",", format = "%m/%d/%Y")
Which worked fine. My xyplot gave me the right plot. So I tried to convert it to ts in order to use strucchange and other outlier/breakpoints packages.
aba <- as.ts(zoo(z$Weighted_Price))
When I did it, it seems to have been lost the index time. The plot still has the same shape, but the X-axis doesn't look as a regular time series plot.
Anyway, I´ve tried the strucchange. After loading it, I made this simple test:
test<-breakpoints(teste$Weighted_Price~1)
But R returned me:
Error in my.RSS.table[as.character(i), 3:4] <- c(pot.index[opt], break.RSS[opt]) :
replacement has length zero
I presume my mistake is that the coercion from zoo to ts was not correct. Any help would be great.

Get frequency for TS from and XTS for X12

I'm trying to automate some seasonal adjustment with the x12 package. To do this I need a ts object. However, I do not need a simple ts object, but one whose start date and frequency has been set. For any given series I could type that, but I will be feeding a mix of monthly or weekly data in. I can get the data from a quantmod as an xta object, but can't seem to figure out how to extract the frequency from the xts.
Here is some sample code that works the the whole way through, but I would like to pull the frequency info from the xts, rather than explicitly set it:
getSymbols("WILACR3URN",src="FRED", from="2000-01-01") # get data as an XTS
lax <- WILACR3URN #shorten name
laxts <- ts(lax$WILACR3URN, start=c(2000,1), frequency=12) #explicitly it works
plot.ts(laxts)
x12out <- x12(laxts,x12path="c:\\x12arima\\x12a.exe",transform="auto", automdl=TRUE)
laxadj <- as.ts(x12out$d11) # extract seasonally adjusted series
Any suggestions? Or is it not possible and I should determine/feed the frequency explicitly?
Thanks
This is untested for this specific case, but try using xts::periodicity for the frequency:
freq <- switch(periodicity(lax)$scale,
daily=365,
weekly=52,
monthly=12,
quarterly=4,
yearly=1)
And use the year and mon elements of POSIXlt objects to calculate the start year and month.
pltStart <- as.POSIXlt(start(lax))
Start <- c(pltStart$year+1900,pltStart$mon+1)
laxts <- ts(lax$WILACR3URN, start=Start, frequency=freq)
plot.ts(laxts)
The xts::periodicity suggestion was helpful to me. I've also found the following approach using xts::convertIndex works well for monthly and quarterly data. It is untested for weekly data.
require("quantmod")
require("dplyr")
getSymbols("WILACR3URN",src="FRED", from="2000-01-01") # get data as an XTS
lax <- WILACR3URN #shorten name
laxts <- lax %>%
convertIndex("yearmon") %>% # change index of xts object
as.ts(start = start(.), end = end(.)) # convert to ts
plot.ts(laxts)

Adding a variable to a ts object in R

I have an object that I have created using the as.ts function in R, and now I would like a simple way to transform one of the variables and add it to the same ts object. So, for example
tsMloa <- ts(read.dta("http://www.stata-press.com/data/r12/mloa.dta"), frequency=12, start=1959)
tsMloa[, "meanLog"] <- tsMloa[,"log"] - mean(tsMloa[,"log"])
gives me a subscript out of bounds error. How can I get around this?
Firstly, you ought to consider adding require(foreign) to your example code, as it's necessary to run your code.
I don't know anything about *.dta files or their formatting, but i can tell you that if you'd like to work with time series in R, you'd do well to look into the zoo and xts family of functions.
With that in mind, try the following:
require(xts)
require(foreign)
tsMloa <- ts(read.dta("http://www.stata-press.com/data/r12/mloa.dta"), frequency=12, start=1959)
tt <- seq(as.Date("1959-01-01"), as.Date("1990-12-01"), by='mon')
tsMloa_x <- xts(unclass(tsMloa)[,1:3], order.by=tt)
tsMloa_x$meanLog <- tsMloa_x$log - mean(tsMloa_x$log)
That should do what you are looking for -- and it gives you a reason to look into the very good packages.
Doing it with zoo -- plus i've created a function to turn your integers into months.
require(foreign)
require(zoo)
Mloa <- read.dta("http://www.stata-press.com/data/r12/mloa.dta"), frequency=12, start=1959)
intToMonth <- function(intMonth, origin = "1960-01-01"){
dd <- as.POSIXlt(origin)
ddVec <- rep(dd, length(intMonth))
ddVec$mon <- ddVec$mon + intMonth%%12
ddVec$year <- ddVec$year + intMonth%/%12
ddRet <- as.Date(ddVec)
return(ddRet)
}
dateString <- intToMonth(Mloa[, 'tm'])
zMloa <- zoo(Mloa[, -2], dateString)
zMloa$meanLog <- zMloa$log - mean(zMloa$log)
As i see it, your problem is with converting the timestamps in the source file to something R understands and can work with. I found this part of adapting to R especially tricky.
The above function will take your month-integers, and turn them into a Date object. The resultant output will work with both zoo and xts as the order.by argument.
If you need to change the origin date, just supply the second argument to the function -- i.e. otherDateString <- intToMonth(timeInts, "2011-01-01").

Resources