I try am trying to use the "to.minutes3" function in the xts package to segment my data.
This function does correctly put the time column into the desired intervals. But data columns becomes "open" , "close", "high" and "low". Is there are way tell the function to average the data points that fall into the same interval?
Thanks,
Derek
You want period.apply. Assuming your data are in object x and are more frequent than 3-minutes, the code below will give you a mean for each distinct, non-overlapping, 3-minute interval.
> period.apply(x, endpoints(x,k=3,"minutes"), mean)
It looks to me like the answer is no, without completely changing that function, based on help("to.period"). to.minutes uses to.period, which says the following w.r.t. the OHLC parameter:
OHLC should an OHLC object be
returned? (only OHLC=TRUE currently
supported)
So other return values aren't supported.
Related
I'm using quantmod to work on multiple symbols in R. My instinct is to combine the symbols into a list of xts objects, then use lapply do do what I need to do. However, some of the things that make quantmod convenient seem (to this neophyte) not to play nicely with lists. An example:
> symbols <- c("SPY","GLD")
> getSymbols(symbols)
> prices.list <- mget(symbols)
> names(prices.list) <- symbols
> returns.list <- lapply(prices.list, monthlyReturn, leading = FALSE)
This works. But it's unclear to me which column of prices it is using. If I try to specify adjusted close, it throws an error:
> returns.list <- lapply(Ad(prices.list), monthlyReturn, leading = FALSE)
Error in Ad(prices.list) :
subscript out of bounds: no column name containing "Adjusted"
The help for Ad() confirms that it works on "a suitable OHLC object," not on a list of OHLC objects. In this particular case, how can I specify that lapply should apply the monthlyReturn function to the Adjusted column?
More generally, what is the best practice for working with multiple symbols in quantmod? Is it to use lists, or is another approach better suited?
Answer monthlyReturn:
All the **Return functions are based on periodReturn. The default check of periodReturn is to make sure it is an xts objects and then takes the open price as the start value and the close price as the last value and calculates the return. If these are available at least. If these are not available it will calculate the return based on the first value of the timeseries and the last value of the timeseries, taking into account the needed time interval (month, day, year, etc).
Answer for lapply:
You want do 2 operations on a list object, so using an function inside the lapply should be used:
lapply(prices.list, function(x) monthlyReturn(Ad(x), leading = FALSE))
This will get what you want.
Answer for multiple symbols:
Do what you are doing.
run and lapply when getting the symbols:
stock_prices <- lapply(symbols, getSymbols, auto.assign = FALSE)
use packages tidyquant or BatchGetSymbols to get all the data in a big tibble.
... probably forgot a few. There are multiple SO answers about this.
I wanted to use rollapply in order to build a rolling window for Value at Risk function. I use the following code:
var<-rollapply(phelix, width=1000, FUN=function(x) VaR(R=phelix, p=0.95, method="historical"),by=1, by.column=TRUE )
phelix is the name of the data vector with returns. It is 3995 observations. I wanted to use a rolling window with 1000 observations. Starting from 1001 and executing the VaR function for every single observation onwards.
After executing the rollapply function I get a vector with 2996 one and the same values. It seems that my window has stuck and doesn't roll :)
Can you please help me with that? Many thanks in advance!
Rollapply repeated calls the function you supply to it with a vector that contains data within the rolling window. In your case you supply FUN=function(x), so x will contain the data within the window. However the function you define has no reference to x so so it always returns the same thing. Assuming that the first argument to VaR is the one that should receive the rolling data, you should use: var<-rollapply(phelix, width=1000, FUN=function(x) VaR(R=x, p=0.95, method="historical"),by=1, by.column=TRUE )
I am able to get the following code to work:
world_dat <- get_ensemble_temp(world,"annualavg",2080,2100)
but I would like to change it to historical and start in 1920,1939 (or even earlier). Unfortunately it keeps saying unused arguments
world_dat2 <- get_historical_temp(world,"annualavg",1920,1939)
I basically want to create a world map showing historical temperatures. Any help will be greatly appreciated. Thx!
The reason why you get the "unused argument" error is because the arguments for these two functions are different:
get_ensemble_temp(locator, type, start, end)
get_historical_temp(locator, time_scale)
For the "get_historical_temp" function, you would set time_scale="year", and then subset to the years that you want. E.g.:
USA_dat <- get_historical_temp("USA", "year")
USA_dat_small <- subset(USA_dat, year >= 1920 & year <= 1939,
select=c(1:length(USA_dat)))
The outputs of these functions are quite different, too. You will have to average and summarize the data from "get_historical_temp" to make them comparable to the output of "get_ensemble_temp"
Also, I couldn't get your first line to work with the argument "world."
According to the docs (http://cran.r-project.org/web/packages/rWBclimate/rWBclimate.pdf)
you have to use a vector of all country codes in order to get the whole world's data all at once.
I am having a problem with the window function in R.
newdata1 <-window(mergedall,start=c(as.Date(as.character("2014-06-16"))),end=c(as.Date(as.character("2015-01-31"))))
I got this error. I am trying to understand how I can fix this issue. Thank you!
Error in window.default(mergedall, start = c(as.Date(as.character("2014-06-16"))), :
'start' cannot be after 'end'
In addition: Warning message:
In window.default(mergedall, start = c(as.Date(as.character("2014-06-16"))), :
'end' value not changed`
I know it's an old post. But, please make sure that "mergedall" is a time series object which was created using the ts command.
While creating the time series object from any vector or series,
some_result_ts <- ts(vector,frequency=xx,start=c(yyyy,m))
This kind of error comes when yyyy is lesser than the start you are specifying in window command.
For example if you take a data frame column or a vector or series , and during the ts formation with ts command, give yyyy=2010,m=1 with a frequency of 12 and assuming it's a 36 month data, the implicit end will be 2013,12.
some_result_ts <- ts(vector,frequency=12,start=c(2010,1))
Then, while using a window function, if you are specifying let's say, start = c(2014,1) , then R will give a message that => 'start' cannot be after 'end' and end value not changed.
Again it's an old post. But since I stumbled upon it by searching the same error. I want to still provide something useful for future Googlers.
I could not replicate your issue because you did not provide your own mergedall dataset. So I am starting with a toy example to show a few places where the problem might be. It's really not that difficult at all.
Potential problem #1:
You did not create a ts object to begin with. Window function operates on a ts object, and it cannot just be a vector took directly from a df. Use ts function to make a vector a ts object first. And then assign it with proper start, end, frequency.
all <-seq(1:8) #eight observations in sequence
Assign these eight values as monthly observations, starting from 201406 to 201501. Frequency 12 means monthly.
all.ts <- ts(all, start = c(2014,6), end = c(2015,1), frequency = 12)
Potential problem #2:
You perhaps already assigned your mergedall series as a ts object, but with different start/end/frequency. My example above was based on monthly observations. So even though they are correct examples, they will not match with your daily-based window function. Window function and the ts object needs to be consistent.
Following my example, the window function would look like:
newdata1 <-window(all.ts,start=c(2014,6),end=c(2015,1) )
Hi here is what you can try, perhaps this would be the solution as I also faced the same problem.
You might not be referring to proper index value in the timeseries object.
In below code I have added the index (i) you can put 1 in case the object has only one series or any number or pass different values using a simple loop.
Hope it helps.!
newdata1 <-window(mergedall[i],start=c(as.Date(as.character("2014-06-16"))),end=c(as.Date(as.character("2015-01-31"))))
I am also a future googler and none of the answers helped me. This was my problem and solution:
MWE issue:
set.seed(50)
data <- ts(rnorm(100), start(1850))
data.train <- window(data, start = 1850, end = 1949)
MWE solution:
set.seed(50)
data <- ts(rnorm(100), start = (1850))
data.train <- window(data, start = 1850, end = 1949)
Issue was the missing equals sign when setting the start date.
The resulting variable data was still a time series; but the give-away was: "Time-Series from 1 to 100" rather than "Time-Series from 1850 to 1949", which told me that something was awry with creating the time series.
The ts function doesn't raise this as an error, presumably because it accepts the start() function from the {stats} package, according to the ?ts doc.
This is probably an issue arising from the format of your 'mergedall' object.
Make sure that you have a ts, xts or a zoo object.
Try f.ex. the following first, in order to ensure the format of your object:
str(mergedall)
First a reproducible example:
library(quantstrat)
getSymbols("AAPL")
Test<-period.apply(AAPL,endpoints(AAPL,on="weeks",k=10),ROC)
TestDF<-as.data.frame(Test)
I want to get the ROC for a certain stock or whatever for x weeks. Or in other words, I want to compare several stocks and rank them with their 10-week ROC, 20 week ROC etc.
Obviously the period apply works, however when I want to convert it to a data Frame and look at my data I always get this error:
Error in coredata.xts(x) : currently unsupported data type
Any idea whats wrong?
period.apply requires a function that returns a single row. ROC does not return a single row. So define your own function to do that.
Test <- period.apply(AAPL, endpoints(AAPL,on="weeks",k=10),
function(x) log(last(x)/coredata(first(x))))