import pandas as pd class BollingerBands: """ Calculates Bollinger Bands for given financial data. """ def __init__(self, period: int = 20, std_dev_multiplier: float = 2.0): """ Initializes the BollingerBands calculator. Args: period (int): The period for the moving average and standard deviation. std_dev_multiplier (float): The number of standard deviations for the upper and lower bands. """ if period <= 0: raise ValueError("Period must be a positive integer.") if std_dev_multiplier <= 0: raise ValueError("Standard deviation multiplier must be positive.") self.period = period self.std_dev_multiplier = std_dev_multiplier def calculate(self, data_df: pd.DataFrame, price_column: str = 'close') -> pd.DataFrame: """ Calculates Bollinger Bands and adds them to the DataFrame. Args: data_df (pd.DataFrame): DataFrame with price data. Must include the price_column. price_column (str): The name of the column containing the price data (e.g., 'close'). Returns: pd.DataFrame: The original DataFrame with added columns: 'SMA' (Simple Moving Average), 'UpperBand', 'LowerBand'. """ if price_column not in data_df.columns: raise ValueError(f"Price column '{price_column}' not found in DataFrame.") # Calculate SMA data_df['SMA'] = data_df[price_column].rolling(window=self.period).mean() # Calculate Standard Deviation std_dev = data_df[price_column].rolling(window=self.period).std() # Calculate Upper and Lower Bands data_df['UpperBand'] = data_df['SMA'] + (self.std_dev_multiplier * std_dev) data_df['LowerBand'] = data_df['SMA'] - (self.std_dev_multiplier * std_dev) return data_df