R,无交易/位置需要图表

时间:2018-06-26 01:09:38

标签: r quantstrat blotter

我正在研究吸墨纸和Quantstrat。我想知道为什么会有错误信息,该错误信息始终不显示图表的交易/位置。您能给我一些帮助吗?

#### Set up packages we need to use below   ##########
library(blotter)
library(FinancialInstrument)
library(quantstrat)
p = 0

## This is your universe of investable assets    #####
## To remove an asset from the list, just delete #####
symbols <- c( "UGAZ", "EWQ", "EWH",
               "VIXM", "SPY", "QQQ",
               "EWG", "INDA", "MCHI"  )

plot(VIXM$Adjusted)
##### ignore code until you see "Pay Attention" ########################
currency('USD')
stock(symbols, 
      currency = "USD", 
      multiplier = 1)

## Set up investment strategy params
init_date <- "2015-12-31"
start_date <- "2016-01-01"
end_date <- "2018-06-01"
init_equity <- 10000000 # $10,000,000
adjustment <- TRUE

getSymbols(Symbols = symbols, 
           src = "yahoo", 
           index.class = "POSIXct",
           from = start_date, 
           to = end_date, 
           adjust = adjustment)

stock(symbols, 
      currency = "USD", 
      multiplier = 1)

portfolio.st <- "Port.Luxor"
account.st <- "Acct.Luxor"
strategy.st <- "Strat.Luxor"
#########^^^^^^^^Ignore ^^^^^^^^^########################
#########################################################



############################################################
### Once you run above, to rerun after makning changes   ###
### to your strategy below, just run from here to end    ###

rm.strat(portfolio.st)
rm.strat(account.st)
rm.strat(strategy.st)

initPortf(name = portfolio.st,
          symbols = symbols,
          initDate = init_date)


initAcct(name = account.st,
         portfolios = portfolio.st,
         initDate = init_date,
         initEq = init_equity)


initOrders(portfolio = portfolio.st,
           symbols = symbols,
           initDate = init_date)

strategy(strategy.st, store = TRUE)





#######################################################
#### Pay attention! Change indicators here  ###########

# SMA speed can be modified here
fastSMA=20
slowSMA=60

add.indicator(strategy = strategy.st,
              name = "SMA",
              arguments = list(x = quote(Cl(mktdata)), 
                               n = fastSMA),
              label = "nFast")

add.indicator(strategy = strategy.st, 
              name = "SMA", 
              arguments = list(x = quote(Cl(mktdata)), 
                               n = slowSMA), 
              label = "nSlow")



#### Pay attention! Change signals here  ##########
add.signal(strategy = strategy.st,
           name="sigCrossover",
           arguments = list(columns = c("nFast", "nSlow"),
                            relationship = "gte"),
           label = "long")

add.signal(strategy = strategy.st,
           name="sigCrossover",
           arguments = list(columns = c("nFast", "nSlow"),
                            relationship = "lt"),
           label = "short")



#### Pay attention! Change trade rules here  ###########

# Trade sizes for long/short
longSize=100
shortSize=10000
fast=slow=sr1=sr2=sr3=sr4 =sr5=sr6=longs=shorts=c()
z = seq(10, 1000, by = 100)
for (i in z) {
  longSize=i
  j = seq(10,100,by = 10)
   for(n in z){
     shortSize = n

     add.signal(strategy = strategy.st,
                name="sigCrossover",
                arguments = list(columns = c("nFast", "nSlow"),
                                 relationship = "gte"),
                label = "long")

     add.signal(strategy = strategy.st,
                name="sigCrossover",
                arguments = list(columns = c("nFast", "nSlow"),
                                 relationship = "lt"),
                label = "short")
### LONG Rules
# Enter Long
add.rule(strategy = strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol = "long",
                          sigval = TRUE,
                          orderqty = longSize,
                          ordertype = "market",
                          orderside = "long", 
                          prefer = "High", 
                          TxnFees = 0, 
                          replace = FALSE),
         type = "enter",
         label = "EnterLONG")
# Exit Long
add.rule(strategy.st, 
         name = "ruleSignal", 
         arguments = list(sigcol = "long", 
                          sigval = TRUE, 
                          orderside = "short", 
                          ordertype = "market", 
                          orderqty = "all", 
                          TxnFees = 0, 
                          replace = TRUE), 
         type = "exit", 
         label = "Exit2LONG")

#### SHORT rules
# Enter Short
add.rule(strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol = "short",
                          sigval = TRUE,
                          orderqty = -shortSize,
                          ordertype = "market",
                          orderside = "short", 
                          replace = FALSE, 
                          TxnFees = 0, 
                          prefer = "Low"),
         type = "enter",
         label = "EnterSHORT")

# Exit Short
add.rule(strategy.st, 
         name = "ruleSignal", 
         arguments = list(sigcol = "short", 
                          sigval = TRUE, 
                          orderside = "long", 
                          ordertype = "market", 
                          orderqty = "all", 
                          TxnFees = 0, 
                          replace = TRUE), 
         type = "exit", 
         label = "Exit2SHORT")

### Add stop loss rule  #####
.stoploss <- .04 # <<<< Modify stop loss as % of entry price here


## Stop loss long
add.rule(strategy.st, 
         name = "ruleSignal",
         arguments = list(sigcol = "long" , 
                          sigval = TRUE,
                          replace = FALSE,
                          orderside = "long",
                          ordertype = "stoplimit",
                          tmult = TRUE,
                          threshold = quote(.stoploss),
                          TxnFees = 0,
                          orderqty = "all",
                          orderset = "ocolong"),
         type = "chain", 
         parent = "EnterLONG",
         label = "StopLossLONG",
         enabled = T)


## Stop loss short
add.rule(strategy.st, 
         name = "ruleSignal",
         arguments = list(sigcol = "short", 
                          sigval = TRUE,
                          replace = FALSE,
                          orderside = "short",
                          ordertype = "stoplimit",
                          tmult = TRUE,
                          threshold = quote(.stoploss),
                          TxnFees = 0,
                          orderqty = "all",
                          orderset = "ocoshort"),
         type = "chain", 
         parent = "EnterSHORT",
         label = "StopLossSHORT",
         enabled =T)

#### End of Stop Loss code  ################

## Now get results for signal/rules/strategies
results_file <- paste("results", strategy.st, "RData", sep = ".")
if( file.exists(results_file) ) {
  file.remove(results_file)}

  results <- applyStrategy(strategy.st, portfolios = portfolio.st)
  updatePortf(portfolio.st)
  updateAcct(account.st)
  updateEndEq(account.st)

for(symbol in symbols) {
  print(symbol)
  chart.Posn(portfolio.st, Symbol = symbol, 
             TA = "add_SMA(n = fastSMA, col = 4); add_SMA(n = slowSMA, col = 2)")
}

### Tabulate Result Stats by Individual Asset
tstats <- tradeStats(portfolio.st)
knitr::kable(t(tstats))

### Now get Total Portfolio Results   ####
final_acct <- getAccount(account.st)
end_eq <- final_acct$summary$End.Eq
returns <- Return.calculate(end_eq, method="log")
charts.PerformanceSummary(returns, colorset = bluefocus, main = "Strategy Performance")


########### Our sharpe ratio and return #########
sr1 = c(SharpeRatio.annualized(returns),sr1)
sr2 = c(table.AnnualizedReturns(returns),sr2)
sr3 = SharpeRatio(returns,add.sharpe = "SPY$Adjusted")
longs=c(longSize,longs)
shorts=c(shortSize,shorts)
p = p+1

print(sr3[3])
sr4[p] = sr3[3]
sr5[p] = SharpeRatio.annualized(returns)
sr6[p] = returns
rm.strat(portfolio.st)
rm.strat(account.st)
rm.strat(strategy.st)

initPortf(name = portfolio.st,
          symbols = symbols,
          initDate = init_date)


initAcct(name = account.st,
         portfolios = portfolio.st,
         initDate = init_date,
         initEq = init_equity)


initOrders(portfolio = portfolio.st,
           symbols = symbols,
           initDate = init_date)

strategy(strategy.st, store = TRUE)
print(sr4)
print(sr5)
print(sr6)
  }
}

我想使用循环尝试尽可能多的长短组合。因此,我将此添加为功能。但是,当我一一测试时,效果很好。当我切换到循环时,它显示此错误。

1 个答案:

答案 0 :(得分:0)

有时,Quantstrat中的错误是由列名的错误指定引起的。 试试这个:

add.signal(strategy = strategy.st,
                name="X1.sigCrossover",
                arguments = list(columns = c("nFast", "nSlow"),
                                 relationship = "gte"),
                label = "long")

     add.signal(strategy = strategy.st,
                name="X1.sigCrossover",
                arguments = list(columns = c("nFast", "nSlow"),
                                 relationship = "lt"),
                label = "short")