R - Blotter Запись трех транзакций за сделку

Я пытаюсь создать очень простую торговую стратегию, используя R с Blotter. Идея состоит в том, чтобы покупать выше SMA и продавать, как только акция падает ниже. Когда я запускаю код, Num.Txns иногда показывает 3 транзакции на сделку, когда я запускаю этот блок:

tstats <- tradeStats(Portfolio=portfolioname)
names(tstats) # what trade stats are available
t(tstats) # t() is transpose - just presents them better
trades.tab <- cbind(
    c("Trades", "Win Percent", "Loss Percent","W/L Ratio"),
    c(tstats[,"Num.Trades"],tstats[,"Percent.Positive"],tstats[,"Percent.Negative"],tstats[,"Percent.Positive"]/tstats[,"Percent.Negative"]))
trades.tab
ptstats <- perTradeStats(Portfolio=portfolioname,Symbol='CBA.csv') # notice the difference between trade stats and per-trade stats

Код выглядит следующим образом:

suppressMessages(library(quantmod))
suppressMessages(library(blotter))
for (symbol in symbollist)
{
    #Set the symbolname variable to be the name of the symbol(eg Anz.csv)
    symbolname <- symbol
    #Load in the data as an xts file
    stock1 = as.xts(read.zoo(symbol, header=T, sep=',')) #Read the stock as a zoo file to later convert to xts
    #Rename the variable to be its filename(eg CBA.csv)
    assign(symbolname,stock1)
    #Remove the stock1 variable to clean the workspace
    rm(stock1)

      #Set x to be the stock that is currently being looped
      x = get(symbol)
      #Set the symbol variable to be the symbol that is currently being looped
      symbol = get(symbol)

    #Define the symbol as a stock in that trades in AUD
    stock(symbolname,currency="AUD")

    #For each row(day) of data
    for (i in 3000:nrow(symbol)-1)
    {


      #Get the date that is being worked with
      currentDate <- time(symbol)[i]
      #Define our current equity
      equity <- getEndEq(accountname,currentDate)
      #Close price today
      closePrice <- as.numeric(Cl(symbol[i,]))
      #Size of our current position
      Posn <- getPosQty(portfolioname,Symbol=symbolname,Date=currentDate)
      #Max amount we could buy today(truncated)
      unitSize <- as.numeric(trunc(equity/closePrice))

      #Moving average
      ma = SMA(x$Close,n=100)[i]

      #Print which day is currently being worked on
      print(sprintf('Symbol: %s, Date: %s, Closing Price: %s, Posn: %s',symbolname, currentDate, closePrice, Posn))

      #Make sure there is enough data for the analysis
      if (nrow(x)>400){
        #If the price is above the moving average and we have no position then purchase the instrument
        if (closePrice > ma && Posn == 0){
          #Make the transaction
          addTxn(portfolioname,Symbol=symbolname,TxnDate = currentDate, TxnPrice=closePrice, TxnQty = unitSize, TxnFees = buyprice)
          #Which row the transaction occured on
          buybar <- i

          #If the price is below the moving average then sell the instrument
        } else
          {
            if (closePrice <= ma && Posn != 0){
          addTxn(portfolioname,Symbol=symbolname,TxnDate = currentDate, TxnPrice=closePrice, TxnQty = -Posn, TxnFees = sellprice)
            }
            else {
              #If it is the last row of data
              if (i==nrow(x))
                addTxn(portfolioname,Symbol=symbolname,TxnDate = currentDate, TxnPrice=closePrice, TxnQty = -Posn, TxnFees = sellprice)
            }
          }

      }

      updatePortf(portfolioname,Symbols=symbolname,Dates=currentDate) # do this first
      updateAcct(accountname,Dates=currentDate)    # then this
      updateEndEq(accountname,currentDate)         # then this last
    }
}

Я все еще изучаю R как часть моего курса, так что это может быть что-то чрезвычайно простое, что я просто пропустил. Я пытался переписать код несколько раз, но у меня все еще остается та же проблема. Заранее спасибо!

0 ответов

Другие вопросы по тегам