R blotter:get中的错误(符号,pos = env):找不到对象...

时间:2013-08-19 07:01:23

标签: r blotter

好的,我已经阅读了文档,Guy Yollin的更新幻灯片和我过去的所有帖子,但我找不到这个问题的答案。在我的for循环之后,我仍然得到一个错误,即无法找到对象'USDCHF'。

这是我的代码:

################
# HOUSEKEEPING #
################
setwd("O:/R/R Programs/")
rm(list=ls(all=TRUE))
library(blotter)
.blotter <- new.env()
.instrument <- new.env()


Sys.setenv(TZ="UTC")

source("VariableAndDataFunctions.R")


############
# SETTINGS #
############
StrategyName<-"Test"
CurrencyPair<-"USD_CHF"
RiskIndex<-"RiskIndex"

MAPeriod <- 10
ParamUp <- 0.96
ParamDown <- 0.95
InitialInvestment <- 10000

Lag=1 #default 1, in order not to peek into the future

CrossCurrency <- paste(substrLeft(CurrencyPair, 3), substrRight(CurrencyPair,3),sep="")

#############
# DATASETUP #
#############
#Import datasets, both as XTS
RiskIndicator<-readVariableAsXTS(RiskIndex)
FXCrossTable<-read.table(paste("O:/Data/",CurrencyPair, ".asc", sep=""),sep=",",skip=1,header=FALSE)
FXCrossTable[,4]<-as.Date(as.character(FXCrossTable[,4]), format="%Y%m%d")
colnames(FXCrossTable)<-c("V1","V2","V3", "Date","Close")
FXCrossXTS<-xts(FXCrossTable[,5], order.by=FXCrossTable[,4])
MergedXTS<-merge.xts(FXCrossXTS,RiskIndicator,join='inner')
MergedXTS[,'RiskIndicator']<-SMA(MergedXTS[,'RiskIndicator'],MAPeriod)
colnames(MergedXTS)<-c("Close", "RiskIndicatorMA")


currency("USD")
currency("CHF")
exchange_rate(CrossCurrency)

####################################
# Initialize portfolio and account #
####################################
#Initialize portfolio and account
Risk.Strategy <- StrategyName  #Is only the name for the portfolio strategy
initPortf(Risk.Strategy,CrossCurrency, initDate='1970-12-31')
initAcct(Risk.Strategy,portfolios=Risk.Strategy, initDate='1970-12-31', initEq=1e6)

#######################
# Formating the chart #
#######################
theme<-chart_theme()
theme$col$up.col<-'lightgreen'
theme$col$up.border<-'lightgreen'
theme$col$dn.col<-'pink'
theme$col$dn.border<-'pink'
chart_Series(MergedXTS,theme=theme,name=CrossCurrency)
plot(add_SMA(n=10,col=4,lwd=2))

#################
# Trading logic # (buy when monthly price > 10-month SMA, sell when monthly price < 10-month SMA)
#################
for(i in (MAPeriod+1):nrow(MergedXTS) ) {
  CurrentDate <- time(MergedXTS)[i]
  ClosePrice <- as.numeric(MergedXTS[i,'Close'])
  if(!(is.na(as.numeric(MergedXTS[i,'Close']))) && !(is.na(as.numeric(MergedXTS[i-1,'Close'])))){

    RiskClose <- as.numeric(MergedXTS[i,'RiskIndicatorMA'])
    RiskClose.PreviousDay <- as.numeric(MergedXTS[i-1,'RiskIndicatorMA'])
    Posn <- getPosQty(Risk.Strategy, Symbol=CrossCurrency, Date=CurrentDate)


    if(Posn != 0){
      if(Posn>0){
        #Long active, sell long
        if(RiskClose <= ParamUp && RiskClose.PreviousDay > ParamUp){
          addTxn(Risk.Strategy, Symbol=CrossCurrency, TxnDate=CurrentDate, 
                 TxnPrice=ClosePrice, TxnQty = -1000 , TxnFees=0)
        }
      } else {
        #Short active sell short
        if(RiskClose >= ParamDown && RiskClose.PreviousDay < ParamDown){
          addTxn(Risk.Strategy, Symbol=CrossCurrency, TxnDate=CurrentDate, 
                 TxnPrice=ClosePrice, TxnQty = 1000 , TxnFees=0)
        }
      }
    } else {
      if(RiskClose >= ParamUp && RiskClose.PreviousDay < ParamUp){
        #Buy
        addTxn(Risk.Strategy, Symbol=CrossCurrency, TxnDate=CurrentDate, 
               TxnPrice=ClosePrice, TxnQty = 1000 , TxnFees=0)
      }
      if(RiskClose <= ParamDown && RiskClose.PreviousDay > ParamDown){
        #Short
        addTxn(Risk.Strategy, Symbol=CrossCurrency, TxnDate=CurrentDate, 
               TxnPrice=ClosePrice, TxnQty = -1000 , TxnFees=0)
      }
    }

    # Calculate P&L and resulting equity with blotter
    updatePortf(Risk.Strategy)
    updateAcct(Risk.Strategy)
    updateEndEq(Risk.Strategy)
  }
}

这是错误:

Error in get(Symbol, pos = env) : object 'USDCHF' not found

但是这行代码提供了以下输出:

> ls(envir=FinancialInstrument:::.instrument)
[1] "CHF"    "SPY"    "USD"    "USDCHF"

所以对象就在那里但却无法找到..为什么?如果我从GuyYollins网站quantstrat-I.R执行示例代码,它的工作完全正常......

1 个答案:

答案 0 :(得分:1)

好好解决了几个小时的代码问题。错误在于作业。我在MergedXTS变量中存储了汇率的时间序列数据。但是,投资组合中的符号称为USDCHF。它们需要具有相同的名称,因为吸墨纸通过使用符号名称(USDCHF)访问所有符号的价格数据。到目前为止,我没有USDCHF变量,它崩溃了。

以下是解决它的代码行:

CurrencyPair<-"USD_CHF"
CrossCurrency <- paste(substrLeft(CurrencyPair, 3), substrRight(CurrencyPair,3), sep="")
assign(CrossCurrency,MergedXTS)

现在我还有另外一个问题..但是我会打开一个新线程。