banner



trading strategy with bollinger band in python

So, after a long time without poster (been super busy), I thought I'd write a quick Bollinger Band Trading Scheme Backtest in Python and then run some optimisations and analysis a great deal like we have done in the past.

It's pretty easy and can be written in just a couple of lines of code, which is why I love Python so much – so more things buns live cursorily prototyped and tested to see if IT even holds weewe without wasting half your aliveness typing.

So as some of you may represent aware, Yahoo Finance throw pulled their financial data API, which means that we can nary longer use Pandas Datareader to cut down commercial enterprise information from the Yahoo Finance site. Rumour has it that Google are pulling theirs as well, although I'm up to now to see that confirmed. Wherefore they get both chosen to behave this, I genuinely don't know but IT's a act of a pain in the backside American Samoa it means lots of the code I've previously written for this blog no more works!!! Such is life I guess…

Anyway, onto larger and better things – we can still usage the awesome Quandl Python API to pull the necessity information!

Let's originate coding…

#make the necessary imports moment pandas as pd from pandas_datareader import data, wb moment numpy as np import matplotlib.pyplot as plt import quandl %matplotlib inline  #download Dax data from the start up of 2022 and store in a Pandas DataFrame df = quandl.get("CHRIS/EUREX_FDAX1", authtoken="[insert-your-token-present]",start_date="2015-01-01")        

We now give birth a Pandas DataFrame with the daily data for the Dax continuous contract. We commode accept a quick look at the structure of the data using the following:

df.head()        

and we get the following:

Soh next we reach the inscribe for creating the genuine Bollinger bands themselves:

#Do number of days and standard deviations to exercise for rolling lookback stop for Bollinger band calculation window = 21 no_of_std = 2  #Calculate tumbling mean and standard deviation using number of days set above rolling_mean = df['Settle'].peal(window).mean() rolling_std = df['Settle'].wheeling(windowpane).std()  #create two new DataFrame columns to hold values of pep pill and take down Bollinger bands df['Rolling Mean'] = rolling_mean df['Bollinger High'] = rolling_mean + (rolling_std * no_of_std) df['Bollinger Underslung'] = rolling_mean - (rolling_std * no_of_std)        

Let's plot the Dax price chart, along with the upper and lower Bollinger bands we have antimonopoly created.

df[['Finalize','Bollinger High','Bollinger Low']].secret plan()        

Now let's pass on to the strategy logic…

#Create an "bare" column as placeholder for our /position signals df['Emplacement'] = No  #Fill our newly created position column - set to sell (-1) when the price hits the upper circle, and pose to grease one's palms (1) when it hits the lower band for words in range(len(df)):          if (df['Settle'].iloc[row] dangt; df['Bollinger High'].iloc[row]) and (df['Settle'].iloc[row-1] danlt; df['Bollinger High'].iloc[wrangle-1]):         df['Position'].iloc[course] = -1              if (df['Settle'].iloc[row] danlt; df['Bollinger Low-set'].iloc[row]) and (df['Settle'].iloc[row-1] dangt; df['Bollinger Low'].iloc[run-in-1]):         df['Position'].iloc[row] = 1    #Forward fill our position editorial to supersede the "None" values with the discipline long/short positions to comprise the "property" of our location #forward through time df['Situatio'].fillna(method='ffill',inplace=True)  #Calculate the daily market return and multiply that by the position to watch strategy returns df['Commercialize Return'] = np.backlog(df['Settle'] / df['Settle'].shift(1)) df['Strategy Return'] = df['Marketplace Return'] * df['Position'].shift(1)  #Plot the scheme returns df['Scheme Return'].cumsum().plot()        

Sol not particularly great returns at each…in fact jolly immensurable!

Let's try upping the windowpane length to utilise a look-back of 50 days for the band calculations…

But best, lets define a "Bollinger Band trading Strategy" function that we can easily run again and over again while varying the inputs:

def bollinger_strat(df,window,std):     rolling_mean = df['Settle'].rolling(window).stand for()     rolling_std = df['Settle'].rolling(window).std()          df['Bollinger High'] = rolling_mean + (rolling_std * no_of_std)     df['Bollinger Low'] = rolling_mean - (rolling_std * no_of_std)          df['Short'] = None     df['Long'] = None     df['Position'] = None          for wrangle in range(len(df)):              if (df['Settle'].iloc[course] dangt; df['Bollinger High-pitched'].iloc[row]) and (df['Settle'].iloc[row-1] danlt; df['Bollinger High'].iloc[wrangle-1]):             df['Position'].iloc[row] = -1                  if (df['Settle'].iloc[row] danlt; df['Bollinger Low'].iloc[row]) and (df['Settle'].iloc[row-1] dangt; df['Bollinger Low'].iloc[row-1]):             df['Attitude'].iloc[row] = 1                  df['Position'].fillna(method='ffill',inplace=True)          df['Market Return'] = nurse clinician.log up(df['Settle'] / df['Settle'].shift(1))     df['Strategy Return'] = df['Market Return'] * df['Position'].shift(1)          df['Strategy Return'].cumsum().plot()        

Eager, now we can just melt down a original scheme backtest with one telephone line! Let's use a 50 day look back period for the band calculations…

bollinger_strat(df,50,2)        

Which should get us a nice looking plot:

Well those returns are at to the lowest degree punter than the previous back-test although definitely nonmoving not great.

If we want to get a quick idea of whether there are any lookback periods that will produce a supportive return we can quickly frame a couple of vectors to check a series of daily periods and canonical deviations, and then upright "brute military unit" our path through a series of backtests which iterates over the 2 vectors, as follows…

#Set up "daily look back period" and "number of measure deflexion" vectors #E.g. the first one creates a vector of 20 evenly spaced whole number values ranging from 10 to 100 #The second creates a transmitter of 10 evenly separated floating point numbers from 1 to 3 windows = np.linspace(10,100,20,dtype=int) stds = np.linspace(1,3,10)  #And restate through them both, track the strategy function each time for window in windows:     for std in stds:         bollinger_strat(df,window,std)        

This gets us the following plot at the end:

Granted at this point we can't be sure exactly which combination of received deviations and time unit look rearwards periods green groceries which results shown in the graph above, however the fact that there are only a twain of fairness curves that fetch up in positive territory would suggest to me that this may not be a gravid strategy to pursue…for the Dax at least. That's not to say Bollinger bands are not useful, just that used in such a simple way as outlined in the above strategy virtually in all probability isn't going away to provide you with any kind of real "inch".

Oh well..perhaps we'll find something better next time.

until and then!

trading strategy with bollinger band in python

Source: https://pythonforfinance.net/2017/07/31/bollinger-band-trading-strategy-backtest-in-python/

Posted by: windsorwhock2002.blogspot.com

0 Response to "trading strategy with bollinger band in python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel