Spaces:
Runtime error
Runtime error
# indicators/bollinger_bands.py | |
import pandas as pd | |
def calculate_bollinger_bands(data, period=21, std_multiplier=1.7): | |
""" | |
Calculates Bollinger Bands for a given period and standard deviation multiplier. | |
Parameters: | |
- data: DataFrame containing stock prices with a 'Close' column (DataFrame). | |
- period: The period over which to calculate the SMA and standard deviation (int). | |
- std_multiplier: The multiplier for the standard deviation to calculate the upper and lower bands (float). | |
Returns: | |
- A DataFrame with columns 'BB_Middle', 'BB_Upper', 'BB_Lower'. | |
""" | |
# Calculate the middle band (SMA) | |
data['BB_Middle'] = data['Close'].rolling(window=period, min_periods=1).mean() | |
# Calculate the standard deviation | |
std_dev = data['Close'].rolling(window=period, min_periods=1).std() | |
# Calculate the upper and lower bands | |
data['BB_Upper'] = data['BB_Middle'] + (std_multiplier * std_dev) | |
data['BB_Lower'] = data['BB_Middle'] - (std_multiplier * std_dev) | |
return data[['BB_Middle', 'BB_Upper', 'BB_Lower']] | |
# Example usage | |
if __name__ == "__main__": | |
# Assuming 'data' is a DataFrame that contains stock price data including a 'Close' column. | |
# For the sake of example, let's create a dummy DataFrame. | |
dates = pd.date_range(start="2023-01-01", end="2023-02-28", freq='D') | |
prices = pd.Series([100 + i * 0.5 for i in range(len(dates))], index=dates) | |
data = pd.DataFrame(prices, columns=['Close']) | |
# Calculate Bollinger Bands | |
bollinger_bands = calculate_bollinger_bands(data) | |
print(bollinger_bands.head()) # Display the first few rows to verify the calculations | |