简体   繁体   中英

How to stop quantmod from removing missing values from an xts

I'm trying to retrieve monthly returns for many tickers, however, not all monthly return time series go fully up to today's date and so my monthly returns don't match up across tickers. For example, after doing

getSymbols("III.L")
monthlyReturn(III.L, from = '2000-01-01', to = '2017-09-26')

in particular, this will give me the time series of monthly returns for 3i, however, this series is missing data from around '2016-10-21' up to the "to" date. Is it possible to get the time series to return as it is, except with the missing data filled in as just NAs without quantmod removing the missing (recent) values?

Ie I'd like the returns to come back as the normal series of returns, except with a string of NAs (or equivalent placeholders) filling up to the "to" date.

This will get you the data with missing values removed:

na.omit(monthlyReturn(III.L, from = '2000-01-01', to = '2017-09-26’))

( with your default warnings setting you get a warning message that the missing values are removed, which you can ignore)

Try this (optionally replace 0 returns by NAs as commented out):

getSymbols("SPY")
III.L <- merge(III.L, xts(, index(SPY)))
III.L[, 4] <- na.locf(III.L[, 4])
r <- monthlyReturn(Cl(III.L), from = '2000-01-01', to = '2017-09-26')

# Optional, replace 0 return months to NA:
#r[r[, 1] == 0, ] <- NA

tail(r, 20)

#            monthly.returns
# 2016-04-29    -0.017723488
# 2016-05-31     0.252478748
# 2016-06-30    -0.070347284
# 2016-07-29     0.181992337
# 2016-08-31    -0.004051864
# 2016-09-30     0.058584215
# 2016-10-31     0.016141430
# 2016-11-30     0.000000000
# 2016-12-30     0.000000000
# 2017-01-31     0.000000000
# 2017-02-28     0.000000000
# 2017-03-31     0.000000000
# 2017-04-28     0.000000000
# 2017-05-31     0.000000000
# 2017-06-30     0.000000000
# 2017-07-31     0.000000000
# 2017-08-31     0.466717095
# 2017-09-29    -0.058277463
# 2017-10-31     0.052573932
# 2017-11-08    -0.009885536

Use SPY to get a set of trading dates for which you "think" you should have price data but don't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM