我正在研究用于 quanstrat 吸墨纸等的 Guy Yollin 幻灯片。这是我要执行的代码:
#According to quantstrat lectures 1-3 von Guy Yollin
library(blotter)
library(FinancialInstrument)
source("chart_Posn.R")
currency("USD")
stock("SPY",currency="USD",multiplier=1)
getSymbols('SPY', from='1998-01-01', to='2011-07-31', adjust=T)
SPY=to.monthly(SPY, indexAt='endof')
SPY$SMA10m <- SMA(Cl(SPY), 10)
####################################
# Initialize portfolio and account #
####################################
#Initialize portfolio and account
b.strategy <- "bFaber" #Is only the name for the portfolio strategy
initPortf(b.strategy,'SPY', initDate='1997-12-31')
initAcct(b.strategy,portfolios=b.strategy, initDate='1997-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(SPY,theme=theme,name="SPY")
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 1:nrow(SPY) ) {
CurrentDate <- time(SPY)[i]
ClosePrice <- as.numeric(Cl(SPY[i,]))
Posn <- getPosQty(b.strategy, Symbol='SPY', Date=CurrentDate)
if( !is.na(as.numeric(SPY[i,'SMA10m'])) ) {
if( Posn == 0 ) { # No position, test to go Long
if( ClosePrice > as.numeric(SPY[i,'SMA10m']) ) {
# enter long position
addTxn(b.strategy, Symbol='SPY', TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = 1000 , TxnFees=0) }
} else { # Have a position, so check exit
if( ClosePrice < as.numeric(SPY[i,'SMA10m']) ) {
# exit position
addTxn(b.strategy, Symbol='SPY', TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = -Posn , TxnFees=0) }
}
}
# Calculate P&L and resulting equity with blotter
updatePortf(b.strategy, Dates = CurrentDate)
updateAcct(b.strategy, Dates = CurrentDate)
updateEndEq(b.strategy, Dates = CurrentDate)
} # End dates loop
chart.Posn(b.strategy, Symbol='SPY', Dates='1998::')
plot(add_SMA(n=10,col=4,on=1,lwd=2))
但是我无法让它工作..for循环之后总是出现这个错误:
Error in periodicity(table) :
can not calculate periodicity of 1 Observation
这两行会产生以下错误:
chart.Posn(b.strategy, Symbol='SPY', Dates='1998::')
plot(add_SMA(n=10,col=4,on=1,lwd=2)
> chart.Posn(b.strategy, Symbol='SPY', Dates='1998::')
Error in as.POSIXct.numeric(first(index(Position))) :
'origin' must be supplied
> plot(add_SMA(n=10,col=4,on=1,lwd=2))
Warning message:
In mapply(function(name, value) { :
longer argument not a multiple of length of shorter
我在看什么?