Calculating Top & Bottom Bollinger Bands with Python
Python
1| """ 2| Calculate closing price standard moving averages and the standard deviation 3| for each stock over the previous 20 days. These are features that used to 4| calculate the bollinger bands. 5| """ 6| df['sma_20'] = df.groupby(['stock'])['close'].transform(lambda x: x.rolling(20).mean()) 7| df['std_20'] = df.groupby(['stock'])['close'].transform(lambda x: x.rolling(20).std()) 8| 9| """ 10| Calculate top and bottom bollinger bands. 11| """ 12| df['bollinger_top'] = df['sma_20'] + (df['std_20'] * 2) 13| df['bollinger_bottom'] = df['sma_20'] - (df['std_20'] * 2)
130
118
115
108