[英]How do I calculate a percent change of a zoo object using sapply?
I have a list of zoo objects. 我有一个动物园物品清单。 The core data is the adjusted close of several stock symbols, monthly data. 核心数据是多个股票代码(月度数据)的调整后收盘价。 Each list object is a separate time series for each ticker. 每个清单对象是每个股票行情的单独时间序列。 I'd like to calculate the monthly change for each month, in each object. 我想计算每个对象中每个月的每月变化。 If it helps, here's what gets me up to my desired calculation: 如果有帮助,请按照以下步骤进行所需的计算:
path = 'C:/SectorRotationSymbList072013.csv'
symbs = read.csv(path, header = FALSE, stringsAsFactors = FALSE)
symbs = symbs[, 1]
importData = vector('list', length(symbs))
#Get monthly pricing data.
for (sIdx in 1:length(symbs)){
#Import the data for each symbol into the list.
importData[[sIdx]] = get.hist.quote(instrument= symbs[sIdx],
start="2000-01-01", end="2013-07-15", quote="AdjClose",
provider="yahoo", origin="1970-01-01",
compression="m", retclass="zoo")
}
names(importData) = symbs
I can get the month over month change for each object using sapply as follows: 我可以使用sapply获取每个对象的逐月变化,如下所示:
monthlyGainsLosses = sapply(importData, diff)
I want relative change, though (%). 我想要相对变化,但是(%)。 I've tried every variation I can think of on the simple calculation, including: 我已经尝试过在简单的计算中可以想到的所有变化,包括:
monthlyGainsLosses = sapply(importData, diff / importData)
monthlyGainsLosses = sapply(importData, diff / coreData(importData))
None of which work. 都不起作用。 For the latter (which seems most logical to me) I get the error: 对于后者(在我看来,这最合逻辑)我得到了错误:
non- numeric argument to binary operator. 二进制运算符的非数字参数。 Can anyone help? 有人可以帮忙吗?
sapply
expects a function as second argument and diff / coreDate(importData)
is not a function in R but an expression. sapply
期望函数作为第二个参数,并且diff / coreDate(importData)
在R中不是函数,而是表达式。
You can supply lambda to correct it. 您可以提供lambda进行更正。
monthlyGainsLosses = sapply(importData, function(x) diff(x) / (x))
Or if you want to avoid lambda, then do it in two steps. 或者,如果要避免使用lambda,则分两步执行。
perc <- function(x) diff(x) / x
monthlyGainsLosses = sapply(importData, perc)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.