Navigation

    Backtrader Community

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

    wykazox

    @wykazox

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

    wykazox Unfollow Follow

    Best posts made by wykazox

    • RE: Optimise type of moving averages (ZLEMA/ZLEMA? ZLEMA/EMA? EMA/SMA?, etc.)

      @run-out Thanks, will try to adapt your code!
      I saw you also gave a very detailed description of the whole process on another thread, I'll check that too.
      Thanks!

      posted in Indicators/Strategies/Analyzers
      W
      wykazox

    Latest posts made by wykazox

    • Momentum indicator, arrays and linregress

      Dear all,

      Still trying to recreate the momentum indicator as part of the Squeeze momentum indicator of LazyBear in TradingView.

      Made some huge progress, but I am getting stuck with the linregress function.
      The formula involves calculating averages involving the highest high, lowest low and close prices over a certain period, and then calculating the linear regression, via arrays.

      I think I need help with using arrays properly.

      Here is the code of the indicator itself.

      from __future__ import (absolute_import, division, print_function,
                              unicode_literals)
      import backtrader as bt
      import yfinance as yf
      import numpy as np
      from scipy.stats import linregress
      
      
      # Create momentum indicator
      class MomInd(bt.Indicator):
          lines = ('Mom',)
          plotlines = dict(Mom=dict(_method='bar', alpha=0.5, width=0.66))  # need to add colours
      
          params = (('period', 20),)
      
          plotinfo = dict(subplot=True)
      
          def _plotlabel(self):
              plabels = [self.p.period]
              return plabels
      
          def __init__(self):
              self.addminperiod(self.p.period)
      
              highest = bt.ind.Highest(self.data.high, period=self.p.period)
              lowest = bt.ind.Lowest(self.data.low, period=self.p.period)
              midline = (highest + lowest) / 2
              mavg = bt.ind.MovingAverageSimple(self.data.close, period=self.p.period)
              delta = self.data.close - ((midline + mavg) / 2)
              y = np.array(delta)
              x = np.array(self.p.period)
              slope, _, _, _, _ = linregress(x, y)
              self.lines.Mom = slope
      

      and the error message when running the code:

      ValueError: Inputs must not be empty.
      
      Process finished with exit code 1
      

      Thanks for your help!

      posted in Indicators/Strategies/Analyzers
      W
      wykazox
    • Need help converting 2 lines of code to backtrader

      Hi All,

      Working on translating the famous Squeeze Momentum indicator from LazyBear (which is available in Pine on TradingView), to use it in Backtrader in Python.
      More specifically, I have issues with the momentum indicator itself.
      It uses the df.rolling.apply syntax from pandas and polyfit from numpy, but the syntax seems incompatible with Backtrader, so I need some help from the community.
      I think I need help to help with the last 2 lines of code (fit_y and self.lines.Mom), basically.

      The last 2 lines were transcribed from Pine to Python as:

      fit_y = np.array(range(0,length_KC))
      df['value'] = df['value'].rolling(window = length_KC).apply(lambda x: np.polyfit(fit_y, x, 1)[0] * (length_KC-1) + np.polyfit(fit_y, x, 1)[1], raw=True)
      

      The code I have translated to Backtrader so far:

      # Create Momentum indicator
      class MomentumInd(bt.Indicator):
          lines = ('Mom',)
          params = (('period', 20),)
          plotinfo = dict(subplot=False)
      
          def _plotlabel(self):
              plabels = [self.p.period]
              return plabels
      
          def __init__(self):
          highest = bt.ind.Highest(self.data.high, period=self.p.period)
          lowest = bt.ind.Lowest(self.data.low, period=self.p.period)
          midline = (highest + lowest) / 2
          mavg = bt.ind.MovingAverageSimple(self.data.close, period=self.p.period)
          delta = self.data.close - ((midline + mavg) / 2)
          fit_y = np.array(range(0, self.p.period, 1))
          self.lines.Mom = delta.rolling(window=self.p.period).apply(lambda x: np.polyfit(fit_y, x, 1)[0] * (self.p.period - 1) + np.polyfit(fit_y, x, 1)[1], raw=True)
      

      Unfortunately, I get the error:

      AttributeError: 'LinesOperation' object has no attribute 'rolling'
      

      I think it relates to the rolling window function in pandas, followed by the apply function, which seems incompatible with backtrader.
      Any idea how to translate these last 2 lines in a way that backtrader can interpret the programme by any chance?
      Thanks for your help!

      posted in Indicators/Strategies/Analyzers
      W
      wykazox
    • Sell when exit conditions are met or trailing stop loss?

      Hi everyone,

      Not sure if my question makes sense...

      Say I want to do a simple MA crossover strategy for entry and exit.
      But I just want to add a trailing stop loss to protect myself, just in case.

      How would I implement the sell orders so that I exit my position either when the exit conditions are met (MA crossdown) or when the trailing stop loss is triggered?

      At the moment, I have this code, but I am not sure it is actually doing what I intended...
      (i.e. it might actually look for trailing stop loss trigger after the crossdown occurs, instead of looking for either a crossdown OR a trailing stop loss trigger)

      elif self.order is None:
          if self.MAfast < self.MAslow:
              self.order = self.sell(exectype=bt.Order.StopTrail, trailpercent=self.p.trailpercent)
      

      Thanks to this knowledgeable community for helping!

      posted in Indicators/Strategies/Analyzers
      W
      wykazox
    • RE: Optimizing MA crossover periods in optstrategy

      @run-out OK, wow, I thought it would be something way simpler...
      I might just keep on deleting them from my results.

      posted in Indicators/Strategies/Analyzers
      W
      wykazox
    • Optimizing MA crossover periods in optstrategy

      Hi All,

      I have what I think is a fairly basic question, but can't seem to find the answer anywhere!

      Say I have a simple MA crossover strategy(buy when fast MA crosses over slow MA, sell when fast MA crosses under slow MA).
      Now, I want to test a wide range of parameters, but I would like to ensure that fast MA period is always smaller than the slow MA period.
      This could also roughly cut the optimisation time in half.

      I tried tinkering with cerebro.optstrategy:

      cerebro.optstrategy(
              MACross,
              MAfast=list(range(2, 50, 2)),
              MAslow=[x > MAfast for x in list(range(10, 200, 10))],)
      

      or

      cerebro.optstrategy(
              MACross,
              MAfast=list(range(2, 50, 2)),
              MAslow=[x > self.p.MAfast for x in list(range(10, 200, 10))],)
      

      or other variants using

              MAslow=[x > MACross.p.MAfast for x in list(range(10, 200, 10))],)
      
              MAslow=[x > strategy.p.MAfast for x in list(range(10, 200, 10))],)
      

      but none of these seem to work...
      I get errors like:

      NameError: name 'MAfast' is not defined
      

      or

      NameError: name 'self' is not defined
      

      etc...

      Not sure how I can approach that problem...
      Thanks for your help!

      posted in Indicators/Strategies/Analyzers
      W
      wykazox
    • RE: Optimise type of moving averages (ZLEMA/ZLEMA? ZLEMA/EMA? EMA/SMA?, etc.)

      @run-out Thanks, will try to adapt your code!
      I saw you also gave a very detailed description of the whole process on another thread, I'll check that too.
      Thanks!

      posted in Indicators/Strategies/Analyzers
      W
      wykazox
    • Optimise type of moving averages (ZLEMA/ZLEMA? ZLEMA/EMA? EMA/SMA?, etc.)

      Dear all,

      New user, and new on the forum, so please excuse me if my topic belongs somewhere else...

      I managed to successfully run the cerebro optimiser to find the optimal length of a moving average crossover.

      Now, I'd like to test different combinations of types of moving averages for the crossovers, for example:
      SMA/SMA
      EMA/SMA
      ZLEMA/SMA
      EMA/EMA
      ZLEMA/EMA
      ZLEMA/ZLEMA
      etc...

      I imagine I would need to do that when adding indicators/signals the strategy.

      But how can I get cerebro.optstrategy() to try different permutations of:
      bt.indicators.sma/zlema/ema/hma/etc...

      I just have no idea how to start optimising things that are not lists of numbers...

      Thanks for your help!

      posted in Indicators/Strategies/Analyzers
      W
      wykazox