Bollinger Bands

Hi, I would like to code a mean reverting system based on bands similar to Bolliger bands. Do you have an example for coding Bollinger bands?

@anthony_m
Bollinger Bands are actually quite easy to calculate.
The middle band is just the simple moving average, the default period is 20.
For the other bands you need the standard deviation for the same period.
The upper band is middle + multiplier * std
The lower band is middle  multiplier * std
Where the default for the multiplier is 2.There's an article on the formula for Bollinger Bands on Investopedia  they use the 'typical price' (high + low + close) / 3 but I think most people just use the close price.
For the code it depends if you only need the latest values or the history.
Using pandas the code for the first alternative could be:def strategy(data): close = data.sel(field='close').copy().to_pandas().ffill().bfill().fillna(0) # let's just use the default 20 period: period = 20 sma = close.iloc[period:].mean() std = close.iloc[period:].std() # and the default multiplier of 2: multiplier = 2 upper = sma + multiplier * std lower = sma  multiplier * std
If you need more than the last values you can use pandas.rolling:
def strategy(data): close = data.sel(field='close').copy().to_pandas().ffill().bfill().fillna(0) # let's just use the default 20 period: period = 20 sma = close.rolling(period).mean() std = close.rolling(period).std() # and the default multiplier of 2: multiplier = 2 upper = sma + multiplier * std lower = sma  multiplier * std

@antinomy wow, thank you so much, this is awesome!