netflypsb commited on
Commit
aee56f7
·
verified ·
1 Parent(s): 1a01da0

Create indicators/bollinger_bands.py

Browse files
Files changed (1) hide show
  1. indicators/bollinger_bands.py +39 -0
indicators/bollinger_bands.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # indicators/bollinger_bands.py
2
+
3
+ import pandas as pd
4
+
5
+ def calculate_bollinger_bands(data, period=21, std_multiplier=1.7):
6
+ """
7
+ Calculates Bollinger Bands for a given period and standard deviation multiplier.
8
+
9
+ Parameters:
10
+ - data: DataFrame containing stock prices with a 'Close' column (DataFrame).
11
+ - period: The period over which to calculate the SMA and standard deviation (int).
12
+ - std_multiplier: The multiplier for the standard deviation to calculate the upper and lower bands (float).
13
+
14
+ Returns:
15
+ - A DataFrame with columns 'BB_Middle', 'BB_Upper', 'BB_Lower'.
16
+ """
17
+ # Calculate the middle band (SMA)
18
+ data['BB_Middle'] = data['Close'].rolling(window=period, min_periods=1).mean()
19
+
20
+ # Calculate the standard deviation
21
+ std_dev = data['Close'].rolling(window=period, min_periods=1).std()
22
+
23
+ # Calculate the upper and lower bands
24
+ data['BB_Upper'] = data['BB_Middle'] + (std_multiplier * std_dev)
25
+ data['BB_Lower'] = data['BB_Middle'] - (std_multiplier * std_dev)
26
+
27
+ return data[['BB_Middle', 'BB_Upper', 'BB_Lower']]
28
+
29
+ # Example usage
30
+ if __name__ == "__main__":
31
+ # Assuming 'data' is a DataFrame that contains stock price data including a 'Close' column.
32
+ # For the sake of example, let's create a dummy DataFrame.
33
+ dates = pd.date_range(start="2023-01-01", end="2023-02-28", freq='D')
34
+ prices = pd.Series([100 + i * 0.5 for i in range(len(dates))], index=dates)
35
+ data = pd.DataFrame(prices, columns=['Close'])
36
+
37
+ # Calculate Bollinger Bands
38
+ bollinger_bands = calculate_bollinger_bands(data)
39
+ print(bollinger_bands.head()) # Display the first few rows to verify the calculations