While using quantmod and scraping GOOGLE stock prices I want the dates and it is showing the dates but unable to subset the dates.
library(quantmod)
start <- as.Date("2017-01-01")
end <- as.Date("2017-11-01")
getSymbols("GOOGL", src = "yahoo", from = start, to = end)
Snapshot:
What should I do?
The xts class (a superset of the zoo class which stores the time data as rownames rather than in numeric columns) has a method for "[" that can be used. It parses dates as characters and uses "/" to separate the ends of intervals:
G.subset <- GOOGL["2017-01-01/2017-11-01"]
Read more at:
?`[.xts`
?xts
The time values are accessible with the index function.
Related
I need to generate a list to attach as a time dimension for a NetCDF file. This file was stacked from many files that were generated as monthly means from 6-hourly data. As a result, each t observation is simply the chronological value of the file in the stack.
First, I generated a date sequence, converted it to characters and then created a date object stating the origin to be the origin of interest. My objective was to receive an integer list of "days since 1850-01-01", however, converting to an integer, I see the origin used is still the R default "1970-01-01".
I am new to working with this "Julian" approach and I would appreciate any advice as to what methods I should use.
The code is as follows
dates <- seq(as.Date("1901-01-01"), by = "month", length.out = 12)
dates <- as.character(dates)
o <- as.Date("1850-01-01")
dates <- as.Date(dates, origin = o)
dates
dates <- as.numeric(dates)
Convert dates to Date class, subtract o and convert that to numeric:
as.numeric(as.Date(dates) - o)
## [1] 18627 18658 18686 18717 18747 18778 18808 18839 18870 18900 18931 18961
Alternately convert both to numeric:
as.numeric(as.Date(dates)) - as.numeric(o)
or use difftime
as.numeric(difftime(as.Date(dates), o, unit = "day"))
I imported some time series data via quantmod and the respective xts object contains several different columns not only one with different prices over time (open close ect). How do I properly call/subset a specific column in a xts object as I need only to work with one of them of further analysis?
getSymbols gets me several price infos per day I dont all need/want.
library(quantmod)
data <- getSymbols("GOOGL",src = "yahoo", from = "2000-01-01", to = "2015-01-01")
data <- data[ ,"GOOGL.Open"] #trying to subset like this
data <- data[ , 3] #or this
Nothin worked yet. There must be some easy solution.
Of course I want to preserve the xts structure. Thank you a lot!
After you run getSymbols, the data is present in GOOGL and not data. Try
GOOGL[, "GOOGL.Open"]
GOOGL[, 3]
The object is created in the environment. We can check ls()
ls()
#[1] "data" "GOOGL"
If we check data, it would be just the character string
data
#[1] "GOOGL"
and that is the reason it is not working
The object name would be the same symbol name used in getSymbols. So, use
GOOGL[, "GOOGL.Open"]
Or we can get the value with
get(data)[, "GOOGL.Open"]
Or if we need to directly assign and wants more control, use the. option auto.assign = FALSE as it is by default TRUE. On a fresh R session,
data <- getSymbols("GOOGL",src = "yahoo", from = "2000-01-01",
to = "2015-01-01", auto.assign = FALSE)
ls()
#[1] "data"
as the auto.assign is FALSE, it is not creating the GOOGL object.
head(data[, "GOOGL.Open"])
# GOOGL.Open
#2004-08-19 50.05005
#2004-08-20 50.55556
#2004-08-23 55.43043
#2004-08-24 55.67567
#2004-08-25 52.53253
#2004-08-26 52.52753
Im trying to create a column using the RBLPAPI BDH
StockMove <- function(ticker){
StockMove <- bdh("MSFT Equity", "Chg_Pct_1D", x$Date, x$Date)
colnames(ernmove) <- NULL
ernmove <- ernmove[,2]
}
but I keep getting the error
Error in eval(substitute(expr), envir, enclos) : expecting a single value
Called from: bdh_Impl(con, securities, fields, start.date, end.datee, options, overrides, verbose, identity)
x$Date is a column of historic dates, and I am trying to create a new column and pull BDH data for each row corresponding to the x$Date column in that row.
. As a sanity check, I used Sys.Date() in place of the x$Date input and it works correctly.
Thanks for any advice, this is my first question so apologies for any errors.
You say x$Date is a column of dates. BDH wants a start date and end date. I think that's what the error is telling you. You're giving it a column where it wants a single value.
I haven't written any R in forever so forgive me is this is buggy:
startDate <- min(x$Date)
endDate <-max(x$Date)
bdh("MSFT Equity", "Chg_Pct_1D", startDate, endDate)
BDH is not well suited to retrieving data from a predetermined list of dates. And not even one date at a time, because holidays have empty data unless you use an override to fill them in.
Instead, I always retrieve the full range of dates from start to end with BDH. If I have a column of specific dates that I need, I look them up in that result.
Data: DOWNLOAD .TXT
Code:
data = read.table("DistrBdaily1yrs.txt", header = TRUE, sep = "", dec = ",")
data$DATE = as.Date(as.character(data$DATE),format="%Y%m%d")
dataXts = xts(data$QUANTITY,data$DATE, frequency = 6)
tseries = ts(dataXts, start = start(dataXts), end = end(dataXts), frequency = 6)
What I'm trying to do is to convert the xts dataXts object to a ts object with correct starting and ending date in order to use the decompose function. In this case start = start(dataXts) and end = end(dataXts) give me the right starting and ending date but tseries doesn't recognize the data column in dataXts and then think that all is data.
How can I fix this?
I am not sure I was able to "FORCE" xts to ts but i got the decompose part to function:
library("data.table")
# I was unable to read-in using read.table() for some reason.... used fread() as it is much faster
data <- fread("DistrBdaily1yrs.txt", header = TRUE, sep="\t")
# Set column names to the ones I saw on dropbox, as i was unable to read-in header for some reason!
colnames(data) <- c("DATE", "QUANTITY")
# Keep as-is
data$DATE = as.Date(as.character(data$DATE),format="%Y%m%d")
dataXts = xts(data$QUANTITY,data$DATE, frequency = 6)
# Not sure what the "QUANTITY" Column means but it must be turned into "numeric"
# You can see this post on how to do it if the following is unsatisfactory:
# http://stackoverflow.com/questions/3605807/how-to-convert-numbers-with-comma-inside-from-character-to-numeric-in-r
a<-as.numeric(gsub(",",".",dataXts))
dataXts <- reclass(a, match.to=dataXts); colnames(dataXts)<- "QUANTITY"
# Now convert it to timeSeries
timeseries <- ts(dataXts,frequency=6)
# decompose
decompose(timeseries)
Also, when I convert xts to ts I assume that it will use the first and last dates in order to construct the ts which is why i left out start = start(dataXts), end = end(dataXts) in the ts() function. Also see ?ts since you cannot pass Dates in the start or end criteria, rather:
Either a single number or a vector of two integers, which specify a natural time unit and a (1-based) number of samples into the time unit.
You can always convert back to xts using reclass:
# for example: Say you only want the trend
reclass(decompose(timeseries)$trend,match.to=dataXts)
I'm learning R this semester and this is my first assignment. I want to retrieve monthly Adjusted stock quotes within a set date range using a for loop. And once I am able to do that I want to merge all the data into a data frame.
My code so far retrieves daily stock quotes for 5 stock symbols within a set date range, it assigns the object to the environment specified, and places only the .Adjusted column in the list.
Could someone point me in a better direction in obtaining the monthly quotes and am I on the right track with my code.
Thanks.
#Packages
library(quantmod)
#Data structure that contains stock quote objects
ETF_Data <- new.env()
#Assign dates to set range for stock quotes
sDate <- as.Date("2007-08-31")
eDate <- as.Date("2014-09-04")
#Assign a vector of ticker symbols.
ticker_symbol <- c("IVW","JKE","QQQ","SPYG","VUG")
#Assign number of ticker symbols.
total_ticker_symbols <- length(ticker_symbol)
#Assign empty list to for each object contained in my environment.
Temp_ETF_Data <- list()
#Assign integer value to counter.
counter <- 1L
#Loop and retrieve each ticker symbols quotes from Yahoo's API
for(i in ticker_symbol)
{
getSymbols(
i,
env = ETF_Data,
reload.Symbols = FALSE,
from = sDate,
to = eDate,
verbose = FALSE,
warnings = TRUE,
src = "yahoo",
symbol.lookup = TRUE)
#Add only Adjusted Closing Prices for each stock or object into list.
Temp_ETF_Data[[i]] <- Ad(ETF_Data[[i]])
if (counter == length(ticker_symbol))
{
#Merge all the objects of the list into one object.
ETF_Adj_Daily_Quotes <- do.call(merge, Temp_ETF_Data)
ETF_Adj_Monthly_Quotes <- ETF_Adj_Daily_Quotes[endpoints(ETF_Adj_Daily_Quotes,'months')]
}
else
{
counter <- counter + 1
}
}
There's no need for the for loop. You can loop over all the objects in the environment with eapply:
getSymbols(ticker_symbol, env=ETF_Data, from=sDate, to=eDate)
# Extract the Adjusted column from all objects,
# then merge all columns into one object
ETF_Adj_Data <- do.call(merge, eapply(ETF_Data, Ad))
# then extract the monthly endpoints
Monthly_ETF_Adj_Data <- ETF_Adj_Data[endpoints(ETF_Adj_Data,'months')]
I know that this is an old question but this answer might help potential future users seeking a better answer.
quantmod has now introduced an additional parameter to the getSymbols function called periodicity which can take the values of daily, weekly, monthly.
I tested out the following and it seems to work as desired:
getSymbols("EURGBP=X", from = starting, src = 'yahoo', periodicity = 'monthly')
just use
to.monthly(your_ticker)