Navigation

    Backtrader Community

    • Register
    • 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/

    How to print and plot ta-lib candlestick patterns ?

    General Code/Help
    4
    10
    2179
    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.
    • Rushi Chaudhari
      Rushi Chaudhari last edited by

      import backtrader as bt
      from datetime import datetime
      
      class firstStrategy(bt.Strategy):
          params = (
              ('period',21),
              )
      
          def __init__(self):
              self.startcash = self.broker.getvalue()
              self.rsi = bt.indicators.RSI_SMA(self.data.close, period=self.params.period)
              self.morningstar = bt.talib.CDLMORNINGSTAR(self.data.open,self.data.high,self.data.low, self.data.close, penetration=0.3)
      
          def next(self):
              print(self.morningstar)
              if not self.position:
                  if self.rsi < 30:
                      self.buy(size=5)
                  if self.morningstar == 100:
                      self.buy(size=2)
              else:
                  if self.rsi > 70:
                      self.sell(size=5)
      
      if __name__ == '__main__':
          #Variable for our starting cash
          startcash = 10000
      
          #Create an instance of cerebro
          cerebro = bt.Cerebro(optreturn=False)
      
          #Add our strategy
          cerebro.optstrategy(firstStrategy, period=range(14,16))
      
          #Get Apple data from Yahoo Finance.
          data = bt.feeds.YahooFinanceData(
              dataname='IBULHSGFIN.NS',
              fromdate = datetime(2019,1,1),
              todate = datetime(2020,1,1),
              buffered= True
              )
      
      
          #Add the data to Cerebro
          cerebro.adddata(data)
      
          # Set our desired cash start
          cerebro.broker.setcash(startcash)
      
          # Run over everything
          opt_runs = cerebro.run()
      
          # Generate results list
          final_results_list = []
          for run in opt_runs:
              for strategy in run:
                  value = round(strategy.broker.get_value(),2)
                  PnL = round(value - startcash,2)
                  period = strategy.params.period
                  final_results_list.append([period,PnL])
      
          #Sort Results List
          by_period = sorted(final_results_list, key=lambda x: x[0])
          by_PnL = sorted(final_results_list, key=lambda x: x[1], reverse=True)
      
          #Print results
          print('Results: Ordered by period:')
          for result in by_period:
              print('Period: {}, PnL: {}'.format(result[0], result[1]))
          print('Results: Ordered by Profit:')
          for result in by_PnL:
              print('Period: {}, PnL: {}'.format(result[0], result[1]))
      
          cerebro.optstrategy(firstStrategy, period=by_PnL[0])
          
          cerebro.plot(style='candlestick')
       
      
      

      I am not able to access self.morningstar as a value in next() function.

      1 Reply Last reply Reply Quote 0
      • A
        ab_trader last edited by ab_trader

        That is is really sad. Why do you think so?

        It would be nice if you post some details, so others can make an educated guess and might be even able to help you.

        UPDATE: By the way I ran your code and it accesses the self.morningstar in the next().

        • If my answer helped, hit reputation up arrow at lower right corner of the post.
        • Python Debugging With Pdb
        • New to python and bt - check this out
        1 Reply Last reply Reply Quote 0
        • Rushi Chaudhari
          Rushi Chaudhari last edited by Rushi Chaudhari

          @ab_trader Morning star returns -100 or 0 or 100
          How can I print what is being returned ?
          For eg. print(self.rsi) prints a number, but print(self.morningstar) is printing an object.

          also is it possible to circle a pattern like this ?

          7306380d-cdca-46a0-a9f0-a7ceebc8a2d4-image.png

          B 2 Replies Last reply Reply Quote 0
          • A
            ab_trader last edited by

            Ok, it is clear that you can access it, but printing is wrong.

            In your code you print the object, so bt works as expected:

            print(self.morningstar)
            

            In order to print the last value the code should be like this:

            print(self.morningstar[0])
            

            You can probably make circle like you shown, but it might take a lot of coding. Much easier is just to put a marker (arrow or triangle) at the pattern.

            • If my answer helped, hit reputation up arrow at lower right corner of the post.
            • Python Debugging With Pdb
            • New to python and bt - check this out
            1 Reply Last reply Reply Quote 2
            • B
              backtrader administrators @Rushi Chaudhari last edited by backtrader

              @Rushi-Chaudhari said in How to print and plot ta-lib candlestick patterns ?:

              For eg. print(self.rsi) prints a number, but print(self.morningstar) is printing an object.

              This is IMPOSSIBLE. Because both are objects. You also said that you couldn't access self.morningstar, but it is obviously accessible.

              @Rushi-Chaudhari said in How to print and plot ta-lib candlestick patterns ?:

              also is it possible to circle a pattern like this ?

              No, there is no such thing as a circle. You could in any case plot a marker which is a 0 with no filling at the maximum. Have a look at the BuySell observer code.

              Rushi Chaudhari 1 Reply Last reply Reply Quote 1
              • Rushi Chaudhari
                Rushi Chaudhari @backtrader last edited by

                @backtrader Is it possible to check if a candlestick pattern has been observed today? How should i return yes/no value ?

                1 Reply Last reply Reply Quote 0
                • B
                  backtrader administrators @Rushi Chaudhari last edited by

                  @Rushi-Chaudhari said in How to print and plot ta-lib candlestick patterns ?:

                  Is it possible to check if a candlestick pattern has been observed today?

                  Never used it. But you apparently already know the values to look for

                  @Rushi-Chaudhari said in How to print and plot ta-lib candlestick patterns ?:

                  @ab_trader Morning star returns -100 or 0 or 100

                  Rushi Chaudhari 1 Reply Last reply Reply Quote 1
                  • Rushi Chaudhari
                    Rushi Chaudhari @backtrader last edited by Rushi Chaudhari

                    Oh, finally got it working, can you add this in documentation, or can I ?

                    1 Reply Last reply Reply Quote 0
                    • Eddy Bennett
                      Eddy Bennett last edited by

                      How did you resolve this in the end?

                      1 Reply Last reply Reply Quote 0
                      • B
                        backtrader administrators last edited by

                        I think he meant ... he understood which values to consider. Obviously if the current [0] value evaluates to True, one can confidently assume that ta-lib has detected a pattern. If it evaluates to False, there is no pattern.

                        1 Reply Last reply Reply Quote 0
                        • 1 / 1
                        • First post
                          Last post
                        Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors