Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. kk7134
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    K
    • Profile
    • Following 1
    • Followers 0
    • Topics 3
    • Posts 4
    • Best 0
    • Groups 0

    kk7134

    @kk7134

    0
    Reputation
    1
    Profile views
    4
    Posts
    0
    Followers
    1
    Following
    Joined Last Online

    kk7134 Unfollow Follow

    Latest posts made by kk7134

    • MA Cross Over & FibonacciPivotPoint

      Hi All

      I am trying to create a strategy, where whenever the MA's crossover I have to check the FibonacciPivotPoint() to see at what range (s1, r1 etc) the closing price is before I make the decision to Buy or Sell

      For MA I am using '1Day' data for the period of 1 Year and for Fibonacci I am using '1Month' data.

      The problems I am facing are

      1. I am not sure how to pass the "month" data name (the one that I am planning to use for Fibonacci) to the FibonacciPivotPoint() and get the computed values

      2. I also want to check the MA cross over with previous month Fibonacci Values. Meaning, if the trade signal is generated based on MA for say 23.06.22. I need to check the previous month(01.05.2022) fibonacci calculated values to see whether the close price is in support range or resistance range

      If someone can help me here or modify the code to accomplish the functionality that I am looking for, that would be great

      I am pasting some data point for review

      1 Day Data
      2021-06-23,402.8999938964844,404.95001220703125,396.6000061035156,397.54998779296875,397.54998779296875,1824603
      2021-06-24,398.20001220703125,400.8999938964844,394.0,395.20001220703125,395.20001220703125,1888424
      2021-06-25,396.0,399.95001220703125,394.3999938964844,396.95001220703125,396.95001220703125,642550
      2021-06-28,398.3500061035156,409.70001220703125,397.54998779296875,404.1499938964844,404.1499938964844,3019858
      2021-06-29,406.8999938964844,411.0,402.0,407.54998779296875,407.54998779296875,2239813
      2021-06-30,408.75,411.0,403.54998779296875,404.45001220703125,404.45001220703125,1217199

      1 Month Data

      2021-05-01,380.95001220703125,393.6499938964844,370.1499938964844,388.20001220703125,388.20001220703125,55544400
      2021-06-01,390.70001220703125,420.25,382.8500061035156,404.45001220703125,404.45001220703125,60320960
      2021-07-01,404.5,414.3999938964844,376.70001220703125,386.3500061035156,386.3500061035156,59979772
      2021-08-01,387.29998779296875,392.45001220703125,327.54998779296875,358.8500061035156,358.8500061035156,42858605
      2021-09-01,360.0,394.1499938964844,350.04998779296875,362.70001220703125,362.70001220703125,58722361
      2021-10-01,362.0,370.6000061035156,314.79998779296875,351.1000061035156,351.1000061035156,55033772

      from __future__ import (absolute_import, division, print_function,
                              unicode_literals)
      
      import datetime  # For datetime objects
      import os.path  # To manage paths
      import sys  # To find out the script name (in argv[0])
      import pandas as pd
      
      # Import the backtrader platform
      import backtrader as bt
      
      '''
      Pending issuse
      1. When a trade is booked it is using the next days closing price, need to change it to next days opening price
      2. Fibonacci pivot points data are yet to be brought in to the equation
      '''
      
      
      # Create a Stratey
      class TestStrategy(bt.Strategy):
          params = (
              ('sl_maperiod', 10),
              ('ft_maperiod', 12)
          )
      
          def log(self, txt, dt=None):
              ''' Logging function fot this strategy'''
              dt = self.dnames.days.datetime.date(0)
              self.fib_dt = self.dnames.month.datetime.date(0)
              print('%s, %s' % (dt.isoformat(), txt))
      
          def __init__(self):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.dnames.days.close
              #self.dataclose_m = self.dnames.month.close
      
              #self.fb_close = self.datas[1][0].close
              #print(self.fb_close[0])
              #print(self.dataclose[0])
      
              # To keep track of pending orders and buy price/commission
              self.order = None
      
              # for d in self.getdatanames():
              #     if d == "days":
              #         # Add a MovingAverageSimple indicator
              self.sl_sma = bt.indicators.ExponentialMovingAverage(self.dnames.days, period=self.params.sl_maperiod)
              self.ft_sma = bt.indicators.ExponentialMovingAverage(self.dnames.days, period=self.params.ft_maperiod)
              #self.regime = self.ft_sma - self.sl_sma
      
                  # else:
              self.Fib = bt.indicators.FibonacciPivotPoint(self.dnames.month)
      
          def notify_order(self, order):
              if order.status in [order.Submitted, order.Accepted]:
                  # Buy/Sell order submitted/accepted to/by broker - Nothing to do
                  return
      
              # Check if an order has been completed
              # Attention: broker could reject order if not enough cash
              if order.status in [order.Completed]:
                  if order.isbuy():
                      # self.log(
                      #     'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                      #     (order.executed.price,
                      #      order.executed.value,
                      #      order.executed.comm))
                      pass
      
                  elif order.issell():  # Sell
                      # self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                      #          (order.executed.price,
                      #           order.executed.value,
                      #           order.executed.comm))
                      pass
      
                  self.bar_executed = len(self)
      
              elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  self.log('Order Canceled/Margin/Rejected')
      
              self.order = None
      
          def notify_trade(self, trade):
              if not trade.isclosed:
                  return
      
              # self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
              #          (trade.pnl, trade.pnlcomm))
      
          def next(self):
              # Simply log the closing price of the series from the reference
              self.log('Close, %.2f' % self.dataclose[0])
              self.log(self.fib_dt.isoformat())
              #self.log('Close, %.2f' % self.dataclose_m[0])
      
              #self.log('Close, %.2f' % self.data1.close[0])
      
              # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.order:
                  return
      
              # Check if we are in the market
              for d in self.getdatanames():
                  #print(d)
                  pos = self.getpositionbyname(d).size
                  if d == "days" and pos == 0:
                      print(d, pos)
                      if self.sl_sma[0] > self.ft_sma[0]:
                          #print(self.regime[0], self.sl_sma[0], self.ft_sma[0])
                          self.log('BUY CREATE, %.2f, %.2f ,%.2f' % (self.dataclose[0],self.sl_sma[0], self.ft_sma[0]))
                          self.order = self.buy()
      
                      elif self.sl_sma[0] < self.ft_sma[0]:
                          print(d, pos)
      
                          #print(self.regime[0], self.sl_sma[0], self.ft_sma[0])
                          self.log('SELL CREATE, %.2f, %.2f ,%.2f' % (self.dataclose[0],self.sl_sma[0], self.ft_sma[0]))
                          self.order = self.sell()
                  elif d == "days" and pos !=0:
                      if pos > 0:
                          if self.sl_sma[0] < self.ft_sma[0]:
                              self.log('BUY CLOSE, %.2f, %.2f ,%.2f' % (self.dataclose[0],self.sl_sma[0], self.ft_sma[0]))
                              self.order = self.close()
                      else:
                          if self.sl_sma[0] > self.ft_sma[0]:
                              self.log('SELL CLOSE, %.2f, %.2f ,%.2f' % (self.dataclose[0],self.sl_sma[0], self.ft_sma[0]))
                              self.order = self.close()
      
      if __name__ == '__main__':
          cerebro = bt.Cerebro()
          cerebro.addstrategy(TestStrategy)
      
          modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
          datapath = os.path.join(modpath, "data", "BIOCON.NS1YR.csv")
          datapath1 = os.path.join(modpath, "data", "BIOCON.NS1MO.csv")
      
          #pv_datapath = os.path.join(modpath, "data", "BIOCON.NS1YR.csv")
      
      
          cerebro.broker.set_cash(100000.00)
          cerebro.addsizer(bt.sizers.FixedSize, stake=10)  # Quantity
          cerebro.broker.setcommission(commission=0.001)
      
          data = bt.feeds.YahooFinanceCSVData(
              dataname=datapath,
              fromdate=datetime.datetime(2021, 6, 23 ),
              todate=datetime.datetime(2022, 6, 24),
              reverse=False)
      
          fib_data = bt.feeds.YahooFinanceCSVData(
              dataname=datapath1,
              fromdate=datetime.datetime(2021, 5, 1),
              todate=datetime.datetime(2022, 5, 31),
              reverse=False)
      
          # data1 = bt.feeds.YahooFinanceCSVData(
          #     dataname=pv_datapath,
          #     fromdate=datetime.datetime(2021, 7, 1),
          #     todate=datetime.datetime(2022, 6, 1),
          #     reverse=False)
      
          #fib_resample_data = cerebro.resampledata(fib_data, timeframe = bt.TimeFrame.Months)
      
          cerebro.adddata(data, name="days")
          cerebro.adddata(fib_data, name="month")
      
          print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
          cerebro.run()
      
          print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
          #cerebro.plot()[link text]([link url](link url))```
      posted in Indicators/Strategies/Analyzers
      K
      kk7134
    • Help with FibonacciPivotPoint()

      Hi All

      I want to call FibonacciPivotPoint() method using the High, Low & Close values and use the results in the strategy. I am not sure how to pass the HLC info and get back the calculated values like PP, R1, S1 etc. Any help here is much appreciated

      self.pvData_H = 377.75
      self.pvData_L = 317.05
      self.pvData_C = 334.10
      
      self.Fib = bt.indicators.FibonacciPivotPoint()
      
      
      posted in Indicators/Strategies/Analyzers
      K
      kk7134
    • Help with Sorting the Python List

      Hi All

      I am using optimizer functionality to evaluate the best parameter combination that I can use in my trading strategy. The output from the optimizer for each parameter set (Slow_EMA, Fast_EMA) along with it's value are added to the list and the code for the same is

      val_list = [self.params.sl_maperiod, self.params.ft_maperiod,self.broker.getvalue()]
      print (val_list)

      the first column is Slow_EMA value and the second column is Fast_EMA value and the third column is the cash value that the optimizer generates for the Slow_EMA and Fast_EMA combination. I am providing the output below

      [5, 20, 101416.90550000001]
      [5, 21, 101717.35600000001]
      [5, 22, 101942.15999999999]
      [5, 23, 101938.65450000002]
      [5, 24, 101785.45050000002]
      [5, 25, 102084.91550000002]
      [5, 26, 101634.87550000002]
      [5, 27, 101835.576]
      [5, 28, 101889.99200000001]
      [5, 29, 101906.11300000001]

      I want to sort this output in a descending order based on column 3(Cash Value) such that the record with the highest value gets displayed at the top.

      Please help me here

      posted in Indicators/Strategies/Analyzers
      K
      kk7134
    • RE: How do I set up correct position close logic?

      @bernardlin You have to check whether the position is a Long Position or Short position, before trying to close it. The position object has size property which will be +ve for Long position and -Ve for short position. You have to check for this before trying to close a position

      What it happening in your code is, the position check is being evaluated and since the system does not know whether you are looking to close a long or short position it is simply executing the condition that is being met in the 'Else' block

      Hope it helps

      posted in General Code/Help
      K
      kk7134