2015-11-26 41 views
1

我需要向后填充知道收益的历史价格(在实际情况下它们是模拟的)。 到目前为止,我有这样的代码:R中的折返时间序列

library(quantmod) 
getSymbols("AAPL") 
df = AAPL["2014-01-01/2015-01-01", "AAPL.Close"] 
df_ret = diff(log(df),1) 
# imagine the half of the past prices are missing 
df["2014-01-01/2014-07-01"] = NA 
df_tot = cbind(df, df_ret) 

fillBackwards = function(data, range_to_fill){ 
    index_array = index(data[range_to_fill,]) 
    data_out = data 
    for (i in (length(index_array)-1):1){ 
    inx = index_array[i] 
    inx_0 = index_array[i+1] 
    data_out[inx,1] = exp(-(data_out[inx_0,2]))*(data_out[inx_0,1]) 
    } 
    return (data_out) 
} 

df_filled = fillBackwards(df_tot,"2014-01-01/2014-07-02") 

sum(AAPL["2014-01-01/2015-01-01", "AAPL.Close"] - df_filled[,1]) # zero up to computation error, i.e. identical 

此作品完美,但有点慢。能否请您使用内置的rollapply()提出好的建议

# i want something like this 
df_filled = rollapply(df_tot["2014-07-02/2014-01-01",], by=-1, function(x) {....}) 
+0

你可以用'动物园::: rollapply.zoo' rollapply研究源代码。它很长,但它可能只是'mapply'的一个包装?但是他们在哪里使用'seq_along(...)'你想'rev(seq_along(...))' (这是一条评论,而不是答案,因为我没有时间去确认这个猜测。) –

回答

1

你不需要rollapply,或循环。您可以在退货上使用cumprod。下面是一个使用cumprodfillBackwards版本:

fillBackwards <- function(data, range_to_fill) { 
    data_range <- data[range_to_fill,] 

    returns <- rev(coredata(data_range[-1L, 2L])) 
    last_price <- drop(coredata(last(data_range[, 1L]))) 

    new_prices <- rev(last_price * cumprod(exp(-returns))) 
    data[range_to_fill, 1L] <- c(last_price, new_prices) 

    return(data) 
} 
+0

谢谢,约书亚! – stkubr