Bollinger Bands
Bollinger Bands¶
The idea of bollinger bands is that we may see reversion to a rolling mean over time. Essentially, what one does is takes the rolling mean as well as two standard deviations above and below and you see at what times there is a breakout from these bands. Some people believe that if there is a breakout it will reverse, but others do not believe this is a viable trading strategy. This dataset is purposely created in a way for this to work, but in the real world you will have to determine for yourself what you think is correct or not.
#Let's create bollinger bands by adding two standard deviations above and below
#Create the lower and upper bands
upper_band = rolling_mean + std*2
lower_band = rolling_mean - std*2
#Plot the bands
df.plot(kind="line",color="k")
rolling_mean.plot(kind="line",color="b")
upper_band.plot(kind="line",color="r")
lower_band.plot(kind="line",color="r")
plt.show()
To identify what points are below or above the bollinger bands, we can use our boolean indexing. Let's create two indices, one for above the upper band and one for below the lower band.
#Index for above the upper bound
i1 = df > upper_band
#Index for above the lower bound
i2 = df < lower_band
print(i1[:5])
print()
print(i2[:5])
We may also want to combine the two to make an index that tells us whether the price is either above or below the bands. First, we can see one example of where the price is above the band below (we also see no points are below the bands):
print(i1[55:65])
print()
print(i2[55:65])
To combine them as an or statement, we can use the | (pipe) operator which will go index by index comparing if either is true.
#Create an index for either i1 or i2 being true
i3 = i1 | i2
print(i3[55:65])
The reason you need to use the pipe operator is because pandas uses C libraries under the hood. The shorthand way to achieve this without setting variables would be the following (notice you need parantheses around the two conditions):
#Achieves the same goal:
print( (df > upper_band) | (df < lower_band) )
We are able to use this to index into the actual data.
print(df[(df > upper_band) | (df < lower_band)])