Git Product home page Git Product logo

backtesting-strategies's Introduction

Screenshot

The Hugo Academic Resumé Template empowers you to easily create your job-winning online resumé, showcase your academic publications, and create online courses or knowledge bases to grow your audience.

Get Started Discord
Twitter Follow

Trusted by 250,000+ researchers, educators, and students. Highly customizable via the integrated no-code, widget-based Wowchemy page builder, making every site truly personalized ⭐⭐⭐⭐⭐

Easily write technical content with plain text Markdown, LaTeX math, diagrams, RMarkdown, or Jupyter, and import publications from BibTeX.

Check out the latest demo of what you'll get in less than 10 minutes, or get inspired by our academics and research groups.

The integrated Wowchemy website builder and CMS makes it easy to create a beautiful website for free. Edit your site in the CMS (or your favorite editor), generate it with Hugo, and deploy with GitHub or Netlify. Customize anything on your site with widgets, light/dark themes, and language packs.

We ask you, humbly, to support this open source movement

Today we ask you to defend the open source independence of the Wowchemy website builder and themes 🐧

We're an open source movement that depends on your support to stay online and thriving, but 99.9% of our creators don't give; they simply look the other way.

Hugo Academic Theme for Wowchemy Website Builder

Demo image credits

Latest news

backtesting-strategies's People

Contributors

timtrice avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

backtesting-strategies's Issues

Error when call apply.paramset in chapter 7.4 Apply Paramset of tutorial

Hi, i'm following your book to learn how to use quantstrat and i'm facing an error when run the code below:

results <- apply.paramset(strategy.st,

  •                         paramset.label = "SMA",
    
  •                         portfolio.st = portfolio.st,
    
  •                         account.st = account.st, 
    
  •                         nsamples = .nsamples)
    

Error:
error calling combine function:
<simpleError in fun(result.1, result.2, result.3, result.4, result.5, result.6, result.7, result.8, result.9, result.10, result.11, result.12, result.13, result.14, result.15): attempt to select less than one element in OneIndex>

Can you help me to fix or go on on the book? (i don't know if this issue is on some dependency package or something i have to do) All the prior code was successfull executed until now.

Thanks a lot.

Section 5.5: Error in getAccount(account.st) : promise already under evaluation: recursive default argument reference or earlier problems?

I am kind of a noob but i pretty much copy pasted the code (after i typed it incorrecly) from the website and spend hours looking at it and googleing because i couldnt make it run
The problem was the checkBlotterUpdate() it told me: Error in getAccount(account.st) : promise already under evaluation: recursive default argument reference or earlier problems?

from what i read it is a problem of the form x=x.
When I changed account.st=account.st to acct.st=account.st
and
a <- getAccount(account.st) into a <- getAccount(acct.st) it worked
my question is did I made a mistake somewhere else which caused this to be a problem which it actually is not, or am I correct?
the code on the website: (https://timtrice.github.io/backtesting-strategies/using-quantstrat.html#checkBlotterUpdate)

checkBlotterUpdate <- function(port.st = portfolio.st, 
                               account.st = account.st,
                               verbose = TRUE) {
    
    ok <- TRUE
    p <- getPortfolio(port.st)
    a <- getAccount(account.st)
    syms <- names(p$symbols)
    port.tot <- sum(
        sapply(
            syms, 
            FUN = function(x) eval(
                parse(
                    text = paste("sum(p$symbols", 
                                 x, 
                                 "posPL.USD$Net.Trading.PL)", 
                                 sep = "$")))))
    
    port.sum.tot <- sum(p$summary$Net.Trading.PL)
    
    if(!isTRUE(all.equal(port.tot, port.sum.tot))) {
        ok <- FALSE
        if(verbose) print("portfolio P&L doesn't match sum of symbols P&L")
    }
    
    initEq <- as.numeric(first(a$summary$End.Eq))
    endEq <- as.numeric(last(a$summary$End.Eq))
    
    if(!isTRUE(all.equal(port.tot, endEq - initEq)) ) {
        ok <- FALSE
        if(verbose) print("portfolio P&L doesn't match account P&L")
    }
    
    if(sum(duplicated(index(p$summary)))) {
        ok <- FALSE
        if(verbose)print("duplicate timestamps in portfolio summary")
        
    }
    
    if(sum(duplicated(index(a$summary)))) {
        ok <- FALSE
        if(verbose) print("duplicate timestamps in account summary")
    }
    return(ok)
}


also the rest of "my" code:

library(quantstrat)

Sys.setenv(TZ = "UTC")
currency('USD')
init_date <- "2007-12-31"
start_date <- "2008-01-01"
end_date <- "2009-12-31"
init_equity <- 1e4 # $10,000
adjustment <- TRUE

basic_symbols <- function() {
  symbols <- c(
    "SPY", # iShares Russell 2000 Index ETF
    "QQQ", # PowerShares QQQ TRust, Series 1 ETF
    "IWM" # SPDR S&P 500 ETF Trust
  )
}
checkBlotterUpdate <- function(port.st = portfolio.st, 
                               acct.st = account.st, 
                               verbose = TRUE) {
  
  ok <- TRUE
  p <- getPortfolio(port.st)
  a <- getAccount(acct.st)
  syms <- names(p$symbols)
  port.tot <- sum(
    sapply(
      syms, 
      FUN = function(x) eval(
        parse(
          text = paste("sum(p$symbols", 
                       x, 
                       "posPL.USD$Net.Trading.PL)", 
                       sep = "$")))))
  
  port.sum.tot <- sum(p$summary$Net.Trading.PL)
  
  if(!isTRUE(all.equal(port.tot, port.sum.tot))) {
    ok <- FALSE
    if(verbose) print("portfolio P&L doesn't match sum of symbols P&L")
  }
  
  initEq <- as.numeric(first(a$summary$End.Eq))
  endEq <- as.numeric(last(a$summary$End.Eq))
  
  if(!isTRUE(all.equal(port.tot, endEq - initEq)) ) {
    ok <- FALSE
    if(verbose) print("portfolio P&L doesn't match account P&L")
  }
  
  if(sum(duplicated(index(p$summary)))) {
    ok <- FALSE
    if(verbose)print("duplicate timestamps in portfolio summary")
    
  }
  
  if(sum(duplicated(index(a$summary)))) {
    ok <- FALSE
    if(verbose) print("duplicate timestamps in account summary")
  }
  return(ok)
}
symbols <- basic_symbols()
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"
rm.strat(portfolio.st)
rm.strat(account.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)

add.indicator(strategy = strategy.st,
              name = "SMA",
              arguments = list(x = quote(Cl(mktdata)), 
                               n = 10),
              label = "nFast")
add.indicator(strategy = strategy.st, 
              name = "SMA", 
              arguments = list(x = quote(Cl(mktdata)), 
                               n = 30), 
              label = "nSlow")
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")
add.rule(strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol = "long",
                          sigval = TRUE,
                          orderqty = 100,
                          ordertype = "stoplimit",
                          orderside = "long", 
                          threshold = 0.0005,
                          prefer = "High", 
                          TxnFees = -10, 
                          replace = FALSE),
         type = "enter",
         label = "EnterLONG")
add.rule(strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol = "short",
                          sigval = TRUE,
                          orderqty = -100,
                          ordertype = "stoplimit",
                          threshold = -0.005, 
                          orderside = "short", 
                          replace = FALSE, 
                          TxnFees = -10, 
                          prefer = "Low"),
         type = "enter",
         label = "EnterSHORT")
add.rule(strategy.st, 
         name = "ruleSignal", 
         arguments = list(sigcol = "short", 
                          sigval = TRUE, 
                          orderside = "long", 
                          ordertype = "market", 
                          orderqty = "all", 
                          TxnFees = -10, 
                          replace = TRUE), 
         type = "exit", 
         label = "Exit2SHORT")

add.rule(strategy.st, 
         name = "ruleSignal", 
         arguments = list(sigcol = "long", 
                          sigval = TRUE, 
                          orderside = "short", 
                          ordertype = "market", 
                          orderqty = "all", 
                          TxnFees = -10, 
                          replace = TRUE), 
         type = "exit", 
         label = "Exit2LONG")

cwd <- getwd()

results_file <- paste("results", strategy.st, "RData", sep = ".")
if( file.exists(results_file) ) {
  load(results_file)
} else {
  results <- applyStrategy(strategy.st, portfolios = portfolio.st)
  updatePortf(portfolio.st)
  updateAcct(account.st)
  updateEndEq(account.st)
  if(checkBlotterUpdate(portfolio.st, account.st, verbose = TRUE)) {
    save(list = "results", file = results_file)
    save.strategy(strategy.st)
  }
}
setwd(cwd)
checkBlotterUpdate()


Chapter 12.3.8= addTxn gives error

I followed all steps (including saving and loading the strategy previously used on book) but when I try to add a new Transaction (by coping the code) I got this error message:

Error in if (PrevPosQty != 0 && sign(PrevPosQty + TxnQty) != sign(PrevPosQty) && :
missing value where TRUE/FALSE needed
In addition: Warning message:
In as.double.xts(getPos(pname, Symbol, Date, Columns = "Pos.Qty")) :
NAs introduced by coercion

In the whole book I had no problems but two cases: this one and the "apply.paramset" function. Anyway, I just focus on this one. Is there some bug I don't know? Thanks

Section 6.2, Table 6.2 not showing

ob <- as.data.table(getOrderBook(portfolio.st)$Quantstrat$SPY) has to be
ob <- as.data.table(getOrderBook(portfolio.st)$Port.Luxor$SPY) i believe
just in case someone like me who has just started runs into the same issue

Error in last(PosData[which(index(PosData) <= Date), ][, Columns], n = n) : unused argument (n = n)

When I try to apply the first simple strategy, it shows this error:

[1] "2008-02-25 00:00:00 ITSA4.SA 100 @ 6.41728275323511"
Error in last(PosData[which(index(PosData) <= Date), ][, Columns], n = n) :
unused argument (n = n)

I´ve followed the code exactly as it is. Can you tell me what is the problem, please?

sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252 LC_MONETARY=Portuguese_Brazil.1252
[4] LC_NUMERIC=C LC_TIME=Portuguese_Brazil.1252

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] pander_0.6.0 webshot_0.3.2 tidyr_0.6.0
[4] lattice_0.20-34 knitr_1.14 htmlwidgets_0.7
[7] htmltools_0.3.5 ggplot2_2.1.0 dplyr_0.5.0
[10] data.table_1.9.6 quantstrat_0.8.2 foreach_1.4.3
[13] blotter_0.9.1644 PerformanceAnalytics_1.4.3541 FinancialInstrument_1.2.0
[16] quantmod_0.4-6 TTR_0.23-1 xts_0.9-7
[19] zoo_1.7-13

loaded via a namespace (and not attached):
[1] Rcpp_0.12.7 magrittr_1.5 munsell_0.4.3 colorspace_1.2-6 R6_2.1.3 plyr_1.8.4
[7] tools_3.3.1 grid_3.3.1 gtable_0.2.0 DBI_0.5-1 iterators_1.0.8 digest_0.6.10
[13] assertthat_0.1 tibble_1.2 codetools_0.2-14 scales_0.4.0 chron_2.3-47

Table caption for DT::datatable is aligned left

In section 6.2 the table caption with both tables is aligned to the left. As I understand it the DT::datatable when using scrollX option (which IMO is needed to view the complete data) breaks the table into three sections, the first of which holds the caption. I'd like this to expand across the entire width but in addition I'd like it to automatically number as figures do in knitr.

Order book delayed by one day?

After implementing Luxor, I notice that the order book closes orders one day later than the date called for by mktdata, and getTxns shows the order filled on the next day at the next day's price.

Order.Qty Order.Price Order.Type Order.Side Order.Threshold Order.Status Order.StatusTime Prefer Order.Set Txn.Fees Rule Time.In.Force
2008-02-26 00:00:00 "100" "105.78775" "market" "long" NA "closed" "2008-02-27 00:00:00" "" NA "0" "EnterLONG" ""
2008-03-06 00:00:00 "all" "100.206276" "market" "long" NA "closed" "2008-03-07 00:00:00" "" NA "0" "Exit2SHORT" ""

getTxns(Portfolio = portfolio.st,

  •     Symbol = symbol.st[1],
    
  •     Dates = dates.st)
         Txn.Qty Txn.Price Txn.Fees  Txn.Value Txn.Avg.Cost Net.Txn.Realized.PL
    

2008-01-06 0 0.00000 0 0.000 0.00000 0.0000
2008-02-27 100 105.68068 0 10568.068 105.68068 0.0000

My code does set the time zone to UTC:

Sys.setenv(TZ="UTC") # Set time zone to UTC

It seems the results will not be accurate if quantstrat delays transactions by a day, compared to what is indicated in mktdata.

Probably a rookie mistake, but please help.

I imagine what's happening is that by the time the closing price is established, it's too late to trade, and the trade is executed at the closing price for the next day. It might be more realistic to trade at the opening price for the next day. I'll see if I can make that work.

results is NULL (section 5.5)

Thanks @timtrice for the great work. It is a great starting point.

I am using quantstrat 0.9.1739. I get NULL results when I run the code below:

results <- applyStrategy(strategy.st, portfolios = portfolio.st)

I'm not sure what was intended for this line to return and save. I have also tried setting debug = TRUE parameter and got a list of 3 environments as result. Is this what we're looking for?

Error in inherits(x, "xts") : could not find function "C1"

Hello,

I am currently on section 8.6 and I am getting an error.

Error in inherits(x, "xts") : could not find function "C1"

I have checked my code and I have followed the tutorial exactly. I have two functions called basic_symbols and checkBlotterUpdate.

The indicator C1 is located in the add.indicator

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

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



Best

Error in inherits(x, "xts") : could not find function "C1"

Hello, great introduction for me to backtesting in R.

I am currently working through sectin 5.5 Apply Strategy where I have ran into a small problem

  • Error in inherits(x, "xts") : could not find function "C1"

I have checked my functions and I do not have a C1 function, do you know where I may have gone wrong previosuly?

Thanks in advance!

Error: could not find function "currency"

require(quantstrat);require(data.table)
require(dplyr);require(DT)
require(ggplot2);require(htmltools)
require(htmlwidgets);require(knitr)
require(lattice);require(pander)
require(tidyr);require(webshot)
sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
locale:
[1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252 LC_MONETARY=Portuguese_Brazil.1252
[4] LC_NUMERIC=C LC_TIME=Portuguese_Brazil.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] webshot_0.3.2 tidyr_0.6.0 pander_0.6.0 lattice_0.20-33 knitr_1.14 htmlwidgets_0.7
[7] htmltools_0.3.5 ggplot2_2.1.0 DT_0.2 dplyr_0.5.0 data.table_1.9.6
loaded via a namespace (and not attached):
[1] Rcpp_0.12.6 digest_0.6.10 assertthat_0.1 plyr_1.8.4 chron_2.3-47 grid_3.2.3
[7] R6_2.1.3 gtable_0.2.0 DBI_0.5 magrittr_1.5 scales_0.4.0 tools_3.2.3
[13] munsell_0.4.3 colorspace_1.2-6 tibble_1.1

Sys.setenv(TZ = "UTC")
currency('USD')
Error: could not find function "currency"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.