Backtrader Community

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    Is this a sufficient program for backtesting ?

    General Code/Help
    1
    1
    289
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • ?
      A Former User last edited by

      Hi,
      In order to understand BackTrader I wanted to write a simple backtesting program on my own. Please take a look at the code and point out anything I might have missed out, diverted from, or areas where I lack understanding of how a backtesting system should function. Any other suggestion is also welcome. Thanks in advance.

      import talib, pandas, math
      
      class SimpleBacktest():
      
          def __init__(self):
              self.cash = 100000
              self.comm = 0.002815
              self.position = False
      
              # reading dataframe from CSV
              self.df = pandas.read_csv('data_csv.csv', delimiter=',') # please use your own CSV I am sure you have one handy
              self.df = self.df.astype({'close': 'float64', 'high': 'float64', 'low': 'float64', 'open': 'float64', 'timestamp': 'int64', 'volume': 'int64'})
          
      
          def calc_ti(self):
              self.df['sar'] = talib.SAR(self.df['high'], self.df['low'])
              
          def reset_df(self):
              self.df.dropna(inplace=True)
              self.df.reset_index(drop=True, inplace=True)
              self.r, self.c = self.df.shape
          
      
          def execute(self):
              for i in range(1, self.r):
                  if self.df['sar'].loc[[i-1]].values < self.df['close'].iloc[[i-1]].values:
                      if self.position == False:
                          c = self.cash * self.comm # calculating commission
                          self.cash = self.cash - c # substracting commission from cash
                          self.qty = math.floor(self.cash / self.df['close'].loc[[i]].values)
                          self.cash = self.cash - (self.qty * self.df['close'].loc[[i]].values)
                          self.position = True
                          self.tgt_price = math.ceil(self.df['close'].loc[[i]].values + (self.df['close'].loc[[i]].values * 0.03))
                          self.invested = self.qty * self.df['close'].loc[[i]].values + self.c
                          print('Bought ', str(self.qty), ' shares @ ', str(self.df['close'].loc[[i]].values), 'Balance is: ', str(self.cash), 'taxes & charges: ', str(c), 'target price:', str(self.tgt_price))
                  
                  if self.df['sar'].loc[[i-1]].values > self.df['close'].iloc[[i-1]].values:
                      if self.df['close'].loc[[i-1]].values >= self.tgt_price:
                          if self.position == True:
                              self.cash = self.cash + (self.qty * self.df['close'].loc[[i]].values)
                              self.c = self.cash * self.comm
                              self.cash = self.cash - self.c
                              self.pnl = self.cash - self.invested
                              print('Sold   ', str(self.qty), ' shares @ ', str(self.df['close'].loc[[i]].values), 'Balance is: ', str(self.cash), 'taxes & charges: ', str(c), 'profit/loss: ', str(self.pnl))
                              self.qty = 0
                              self.position = False
                          
                  if i == self.r-1:
                      if self.position == True:
                          self.cash = self.cash + (self.qty * self.df['close'].loc[[i]].values)
                          self.c = self.cash * self.comm
                          self.cash = self.cash - self.c
                          self.pnl = self.cash - self.invested
                          print('Sold   ', str(self.qty), ' shares @ ', str(self.df['close'].loc[[i]].values), 'Balance is: ', str(self.cash), 'taxes & charges: ', str(c), 'profit/loss: ', str(self.pnl))
                          self.qty = 0
                          self.position = False
                          # total profit or loss
                      print('\ntotal profit / loss: ', self.cash - 100000)
      
      tl = Talibtest()
      tl.calc_ti()
      tl.reset_df()
      tl.execute()
      
      1 Reply Last reply Reply Quote 0
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors