Ok I've read through the documentation, the updated slides from Guy Yollin and all my past posts, but I cannot find an answer to this problem. After my for loop I still get an error that the object 'USDCHF' cannot be found.
Here's my code:
################
# 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)
}
}
And here's the error:
Error in get(Symbol, pos = env) : object 'USDCHF' not found
However this line of code gives the following output:
> ls(envir=FinancialInstrument:::.instrument)
[1] "CHF" "SPY" "USD" "USDCHF"
So the object is there but it cannot be found..why? If I execute the sample code from GuyYollins Website quantstrat-I.R it works completely fine...
Ok solved it after looking at the code for hours. The mistake was in the assignment. I stored the time series data for the exchange rate in the MergedXTS variable. However the symbol in the portfolio is called USDCHF. They need to have the same name, since blotter accesses the price data for all symbols by using the symbol name, which is USDCHF. Since so far I didn't have an USDCHF variable, it crashed.
Here are the lines of code that solved it:
Now I have another problem though..but for that I'll open a new thread.