File size: 1,596 Bytes
43e3b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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)