stock_15min_signal / indicators /bollinger_bands.py
netflypsb's picture
Create bollinger_bands.py
43e3b42 verified
raw
history blame
No virus
1.6 kB
import pandas as pd
def calculate_bollinger_bands(prices, ma_length=20, std_dev_multiplier=2):
"""
Calculates the Bollinger Bands for a given set of stock prices.
Parameters:
- prices (pd.Series): A pandas Series containing the stock's closing prices.
- ma_length (int): The length of the moving average. Defaults to 20.
- std_dev_multiplier (int): The number of standard deviations to calculate the upper and lower bands. Defaults to 2.
Returns:
- pd.DataFrame: A DataFrame containing the Moving Average, Upper Band, and Lower Band.
"""
# Calculate the Moving Average
ma = prices.rolling(window=ma_length).mean()
# Calculate the standard deviation
std_dev = prices.rolling(window=ma_length).std()
# Calculate the Upper and Lower Bollinger Bands
upper_band = ma + (std_dev_multiplier * std_dev)
lower_band = ma - (std_dev_multiplier * std_dev)
bollinger_bands_df = pd.DataFrame(data={
'Moving_Average': ma,
'Upper_Band': upper_band,
'Lower_Band': lower_band
})
return bollinger_bands_df
if __name__ == "__main__":
# Example usage
data = {'Close': [22, 24, 23, 25, 26, 28, 27, 29, 30, 32, 31, 33]}
prices = pd.Series(data['Close'])
# User-defined parameters for Bollinger Bands
ma_length = 20 # Moving Average length
std_dev_multiplier = 2 # Standard Deviation Multiplier
# Calculate Bollinger Bands
bollinger_bands_df = calculate_bollinger_bands(prices, ma_length, std_dev_multiplier)
print(bollinger_bands_df)