使用optim查找最长的日期范围

时间:2014-07-07 20:45:32

标签: r

我试图学会使用优化,但在这里失败了。我似乎无法理解如何正确地调用优化。在此先感谢您的帮助。

以下代码查看SPY并使用函数FindRange确定涵盖第一个&的日期。 TestLevel的最后交叉== 100。由于我想优化,我创建了一个包装函数OptimFindRange,它返回从开始到结束的天数作为我想要最大化的标量。有一些简单的循环来测试事情或多或少正常工作。 (我认为他们确实......)

但是,我完全迷失了如何使用optim来做到这一点。我显然不明白如何设置通话,最明显的是输入输入与我的数据&等级值。救命啊!

library(quantmod)

FindRange = function(d1, level){
  if (level == 0){ #To bypass search)
    DS = first(index(d1))
    DE = last(index(d1))
  }else{
    DS = index(first(d1[(Cl(d1)>level) & lag(Cl(d1)<level)]))
    DE = index( last(d1[(Cl(d1)>level) & lag(Cl(d1)<level)]))
  }
  return(c(DS,DE))
}

#Optimizable call to FindRange that
#returns a scalar
OptimFindRange = function(data, level){
  RetVal = FindRange(data, level)
  Result1 = as.integer(RetVal[2]-RetVal[1])
  return(Result1)
}

TestSym = "SPY"
Source = "yahoo"
StartDate = "1990-01-01"
Adjust = TRUE
TestLevel = 100

getSymbols(TestSym,src=Source,from=StartDate,adjust=Adjust)

data = get(TestSym)
#Plot all data and TestLevel
plot(Cl(data),main=TestSym)
abline(h=TestLevel, col="black", lty=1)

#Simple test to get start & end dates for TestLevel
R1 = FindRange(data, TestLevel)

InitDate  = R1[1]
FinalDate = R1[2]
NumDays = as.integer(R1[2] - R1[2])

TestData = data[ (index(data)>=InitDate) & (index(data)<=FinalDate) ]
#Plot only range of data with TestValue
plot(Cl(TestData),main=TestSym)
abline(h=TestLevel, col="black", lty=1)


#Test only
#Call OptimFindRange function in loop
xl = ceiling(min(Cl(data)))
xu = floor(max(Cl(data)))
Vec1 = vector()
for (i in xl:xu){
  tmp1 = OptimFindRange(data, i)
  print(paste("TestLevel:",i," - Num days: ",as.integer(tmp1)))
  Vec1[i] = as.integer(tmp1)
  rm(tmp1)
}
LongestLevel = order(Vec1, decreasing=TRUE)[1]
#Get date range
FindRange(data, LongestLevel)
#End test


#Limits for optimization?
MaxLevel = max(Cl(TestData))
MinLevel = min(Cl(TestData))

#Trying to optimze but I don't understand
optim(fn=OptimFindRange, data = TestData, 
      level = ave(MaxLevel,MinLevel),
      method="Brent", 
      lower=MinLevel, upper=MaxLevel,
      control=list(fnscale=-1)
)

0 个答案:

没有答案