Python Backtrader : Fibonacci Bollinger Bands - Example Indicator

In the last post, I had discussed the Fibonacci Bollinger Bands and its implementation on the TradingView platform through pinescript. If you want to implement the indicator in python, you can use BackTrader module for backtesting and quick development and implementation of any indicator script in python. 

Below is the code in Python for implementing the indicator Fibonacci Bollinger Bands through backtrader module.

import backtrader as bt
# Create a Stratey
class FiboBB(bt.Indicator):

    alias = ('FiboBB',)
    lines = ('mid', 't1','t2','t3','t4','t5','t6', 'b1','b2','b3','b4','b5','b6',)
    params = (
        ('period', 50), # Look Back Period
        ('devfactor', 3.0), # standard dev. for extreme lines
        ('movav', bt.ind.MovingAverageSimple),
                    )

    plotinfo = dict(
        subplot=False,
        plotlinelabels=False,
                            )

    plotlines = dict(
        mid=dict(ls='--'),
        t1=dict(_samecolor=True),
        t2=dict(_samecolor=True),
        t3=dict(_samecolor=True),
        t4=dict(_samecolor=True),
        t5=dict(_samecolor=True),
        t6=dict(_samecolor=True),
        b1=dict(_samecolor=True),
        b2=dict(_samecolor=True),
        b3=dict(_samecolor=True),
        b4=dict(_samecolor=True),
        b5=dict(_samecolor=True),
        b6=dict(_samecolor=True),
                            )

    def __init__(self):
        self.lines.mid = ma = self.p.movav(self.data, period=self.p.period)
        stddev = self.p.devfactor * bt.ind.StandardDeviation(self.data, ma, period=self.p.period,
movav=self.p.movav)
        self.lines.t1 = ma + stddev
        self.lines.t2 = ma + stddev*.764
        self.lines.t3 = ma + stddev*.618
        self.lines.t4 = ma + stddev*.5
        self.lines.t5 = ma + stddev*.382
        self.lines.t6 = ma + stddev*.236
        self.lines.b1 = ma - stddev
        self.lines.b2 = ma - stddev*.764
        self.lines.b3 = ma - stddev*.618
        self.lines.b4 = ma - stddev*.5
        self.lines.b5 = ma - stddev*.382
        self.lines.b6 = ma - stddev*.236

        super(FiboBB, self).__init__()


class MyStrategy(bt.Strategy):
    def __init__(self):
        self.FiboBBLines = FiboBB(self.data)

if __name__ == '__main__':
    cerebro = bt.Cerebro(stdstats=False)
    data = bt.feeds.YahooFinanceCSVData(dataname='AAPL.csv')
    cerebro.adddata(data)
    cerebro.addstrategy(MyStrategy)
    cerebro.run()
    cerebro.plot(style='candlestick',bardown='black',barupfill = False,bartrans = 1.0,barup='black',volume=False)


The resultant plot for Fibonacci Bollinger Band is shown below:


If you are new to the backtrader module of python or have no prior experience of coding in python or any other programming language. I strongly suggest you consider the Backtrader book provided in the resource section. The book has been written for traders with no prior experience of coding or programming in any language.

You can also download code from "backtraders/backtraderIndicators" on git hub

Coding and using vortex indicator in PineScript

Vortex Indicator

Vortex indicator is used to identify the start, end or continuation of a trend. It consists of two lines which are generally red and green. Greenline measures the strength of the uptrend while the other measures for downtrends. When the two cross, trend change can be expected. 

Vortex Indicator Calculation

Vortex is calculated by subtracting the previous low/high from the current high/low. Please note, the low of the previous bar is substructed from the current high and the high of the previous bar is substructed from the current low of the present bar. 

i.e. VM+ = high - low of previous bar and VM- = low-high of previous bar

In the above, we are considering VM+ as positive vortex movement and VM- as negative vortex movement. A vortex movement is a scientific term associated with the flow of fluid or water. As you can notice the calculation above can be positive or negative depending on the values of high/low. For this reason, we calculate the absolute value (all negative are also considered as positive) of the same. The above therefore becomes :

VM+ = absolute(high - low of previous bar) and VM- = absolute(low-high of previous bar)

The calculation of VM+ and VM- is similar to the way we calculate TR i.e. true range. The VM can be considered as cross TR with previous bars. 

Thus Vortex indicator can be considered as a comparison of cross TR with TR for a given period.

Before we compare, VM with TR we have to calculate TR i.e. TR = high - low.

Now we can compare these cross TR with actual TR. The comparison is done for a fixed lookback period. Generally, traders choose 14 or 21 days as a lookback period (because they are multiples of days in a week). If you are not working on the daily time frame, you may like to choose a different lookback period. 

For comparison just sum up value of VM+ and VM- and TR for lookback period. 

For calculation of Vortex Indicator Plus divide VM+ by TR summed up for lookback period.

VIP = (sum of  VM+ for lookback period)/(sum of  TR for lookback period)

VIM = (sum of  VM- for lookback period)/(sum of  TR for lookback period) 

Implementing Vortex Indicator in Pinescript

//@version=5
indicator(title = "Vortex Indicator", shorttitle="VI")
period = input.int(14, title="Length", minval=2)
VMPlus = math.sum( math.abs( high - low[1]), period )
VMMinus = math.sum( math.abs( low - high[1]), period )
SumTR = math.sum( ta.tr, period)
VIPlus = VMPlus / SumTR
VIMinus = VMMinus / SumTR
plot(VIPlus, title="VI +", color=#2962FF)
plot(VIMinus, title="VI -", color=#E91E63)

The above is code in pinescript for quick implementation of vortex indicator on trading view platform. 
The VM+ and VM- is calculated by calculating cross TR as high - low[1] and low - high[1]. Here the [1] notation after high and low represent the value of high or low one bar back. 

If you are new to pinescript or want to learn pinescript from scratch. Books and courses are recommended in the resource section. Even if you have no prior experience of coding or programming, you will be able to make code in pinescripts after going through the book or course.

You are encouraged to copy and use the above code in your pinescript editor for results. 

Vortex indicator best settings

The common question that many traders often ask is what is the best setting for an indicator. What could be vortex indicator settings for intraday ? No one can give you the correct answer for such types of questions but I can provide you with some guidelines on the selection of the best setting for any indicator. 

1.   Setting Shall depend on underlying asset and market timings. If the market works for  24X 7, its setting will always be different from other equity exchanges those work for 8 to 10 hours a day.

2. Timeframe do have impact on settings of any indicator. Setting for one timeframe may not work for another. 

Example : If you are using daily timeframe for an exchange that works for 5 days a week, a week is of 5 days , two weeks are of 10 days, month is of 20 days. I would suggest a setting of 15,20 for long term and 5 or 10 for short term. Your setting should be in line with higher time frame. 

If you are using a 5 min chart, try using 60 min / 5 = 12 as setting or 30 min / 5 min = 6 as settings.

In case of vortex, I am using 14 as setting which is equal to 2 weeks (7 X 7) or approx 3 weeks (5 X 3) if we consider 7 days or 5 days as days in a week. 

Vortex Indicator Strategy

VM being absolute number is always a positive number and being divided by TR, the Vortex Indicator for strength and weakness are always positive i.e. value greater than zero, however, as we had normalized the value of VM by TR, they are generally in a narrow range.

Any value of VI above 1.1 can be considered as a strength and value below 0.90 can be considered as weakness. Some traders use crossover of VI+ and VI- as single for trend reversal. Some traders also use other indicators in combination with VI for signal filtering.




vortex indicator screener

vortex indicator vs dmi

vortex indicator python

vortex indicator afl

vortex indicator accuracy

vortex indicator adalah

vortex angle indicator

vortex indicator vs adx

Fibonacci Bollinger Bands - PineScript Indicator Review

Fibonacci Bollinger Bands is a community script developed by "Rashad" and is one of the popular community scripts in tradingview. The author of the script has not given an explanation to the script, however, the entire code is open for the community for study and development.

Another script on the same is by "Shizaru". Shizaru has given an explanation of the indicator's construction but has not provided details about its uses.

Both the script have different logics for the calculation of bands and Fibonacci bands inside the Bollinger band. In this blog post, I will be discussing both of these scripts. The differences are as under:


Rashad

Shizaru

Uses standard deviation of 3 for calculation of upper and lower bands

Uses ATR for calculation of the extreme upper and lower bands

The 3 standard deviation is divided into Fibonacci ratios of 0.236, 0.382, 0.5, 0.618, 0.764, 1

ATR ratio of 1.618,2.618,4.236 defines the three lines above mean and below mean.

Seems more logical as Bollinger bands are based on standard deviations and the division of standard deviation with ratios is as per acceptable literature. 97% values should be under the bands.

Shizaru has used descriptions provided on the internet for Bollinger Bands® Fibonacci Ratio.

Fibonacci Bollinger Bands - by Rashad

Below is the indicator on the SBIN from the National Stock Exchange of India. The Fibonacci lines are represented by L1,L2,L3,L4 and L5. The below daily chart is from May 2021 to Aug 2021.


It may be observed from the above chart that price has received some reaction from the Fibonacci lines drawn inside Bollinger bands. During the period under examination, the price raised from below L2 to L4. No price reaction was observed when the first time price crossed/breached L2. However, on all occasions when price touched the Fibonacci level lines during rising or decline, they have to produce reactions as marked on the chart. 

Out of the 6 events of crossing/touching of price with levels for the first time, 5 times it produces a reaction.

Bollinger Bands Fibonacci ratios - by Shizaru

We have now applied the script developed by Shizaru on the same scrip for the same period and timeframe. We can observe that the band lines in this one are less than the earlier one but the gap between the band lines is smaller.


Due to the smaller gap between the band lines price has crossed/touched these lines many times during the same period. As compared to six events of band touching or crossing in the previous section as discussed above we can observe that there are nine such events in this script. Out of the nine such occasions, the price at E and H did not provide enough reaction. In fact, at E there was no reaction while at H there was a minor reaction. 

For all practical purposes, both the scripts were able to provide points of reaction through the band lines. You can choose any one of them as per your requirement and volatility in the market. It is suggested that you back test them on the scrip, forex, commodity onto which you would like to apply. 

Combining both Bollinger Bands and Fibonacci ratios




To-Do /Suggestions

For the script from Rashad - the colour scheme of the script makes it invisible in the lighter theme of the tradingview platform. To be able to use this script you have to be in the dark mode. In case you are more comfortable with the lighter theme of the trading view platform, you have to either change the theme or the colour scheme for better visualization.

Also, try to use another indicator like RSI to improve upon signal generation and filtering. 

Teach Yourself Python Backtrader: Step by Step backtesting implementation for non-programmers

 

Backtrader is a python package for backtesting of strategies in python. The backtrader is in use by many traders for backtesting as well as for trading in live market. The book "Teach Yourself Python Backtrader" is for those who want to learn python backtrader for backtesting.


Have you ever thought of a machine that could earn for you while you relax. There is no such machine but steps can be taken to build such a machine. It all depends on your skills and a winning strategy that can do trading on your behalf.



Backtrader is python module used for creating custom indicators, trade alerts, creating strategies and back-testing them on historical and real data. After, gaining skill from this book you will be able to make your scripts for custom indicators and backtest strategies on historical data and real market. This book has been written in simple language so that readers with no prior background of python or computer programming are able to learn and build upon the basics. This book will also introduce you to basics of python programming need by the traders for coding on backtrader. Act now to have a copy of this book to test your strategies and build your skills.

Python Backtrader : Mark Doji CandleSticks - Example Indicator

Python Backtrader: Mark Doji CandleSticks - Example Indicator

Below is the script in python using the backtrader package for marking Doji CandleSticks on the chart. Ideally, a doji is a candlestick pattern where the open price is exactly the same as the close price. However, since such ideal conditions seldom exist, in the script, I have used a tolerance of 0.05% between the open and close price for identifying and marking doji.

import backtrader as bt
# Create a Stratey
class DojiTest(bt.Indicator):

alias = ('DD',)
lines = ('doji',)
params = (
('tolerence', 0.05), # tolerence
)

plotinfo = dict(
subplot=False,
plotlinelabels=True,
)
plotlines = dict(
doji=dict(marker='^', markersize=8.0, color='blue', fillstyle='full', ls='',
),
)

def next(self):
# red doji
if ((self.datas[0].close[0] * (1 + (self.p.tolerence/100))) > self.datas[0].open[0]) and (self.datas[0].close[0]<self.datas[0].open[0]):
self.lines.doji[0]= self.datas[0].high[0]

# green doji
if ((self.datas[0].open[0] * (1 + (self.p.tolerence/100))) > self.datas[0].close[0]) and (self.datas[0].close[0]>self.datas[0].open[0]):
self.lines.doji[0]= self.datas[0].high[0]


class MyStrategy(bt.Strategy):
def __init__(self):
# self.BB = bt.ind.BBands(self.data,period=20,devfactor=1.5)
self.doji = DojiTest(self.data)

if __name__ == '__main__':
cerebro = bt.Cerebro(stdstats=False)
data = bt.feeds.YahooFinanceCSVData(dataname='AAPL.csv')
cerebro.adddata(data)
cerebro.addstrategy(MyStrategy)
cerebro.run()
cerebro.plot(style='candlestick')

The script is using Cerebro engine of backtrader for plotting of custom indicators created in backtrader. A new indicator class named DojiTest has been written and implemented.

Resources

Highest Rated Udemy Course on PineScript - Grab your Seat Now 

Udemy Discount Coupon Code : UDEMY-JAN23 (Valid upto 30th Nov 2023)

Learn more about coding on tradingview in PineScript through Books on pinescript available on amazon and kindle.


200+ pages book100 pages book200+ pages book


Point and Figure Charts : A Time-Tested Tool for Technical Analysis

In the dynamic world of financial markets, investors and traders constantly seek tools that can provide valuable insights into market trends...