Spaces:
Running
Running
Create bollinger_bands.py
Browse files
indicators/bollinger_bands.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
|
3 |
+
def calculate_bollinger_bands(prices, ma_length=20, std_dev_multiplier=2):
|
4 |
+
"""
|
5 |
+
Calculates the Bollinger Bands for a given set of stock prices.
|
6 |
+
|
7 |
+
Parameters:
|
8 |
+
- prices (pd.Series): A pandas Series containing the stock's closing prices.
|
9 |
+
- ma_length (int): The length of the moving average. Defaults to 20.
|
10 |
+
- std_dev_multiplier (int): The number of standard deviations to calculate the upper and lower bands. Defaults to 2.
|
11 |
+
|
12 |
+
Returns:
|
13 |
+
- pd.DataFrame: A DataFrame containing the Moving Average, Upper Band, and Lower Band.
|
14 |
+
"""
|
15 |
+
# Calculate the Moving Average
|
16 |
+
ma = prices.rolling(window=ma_length).mean()
|
17 |
+
|
18 |
+
# Calculate the standard deviation
|
19 |
+
std_dev = prices.rolling(window=ma_length).std()
|
20 |
+
|
21 |
+
# Calculate the Upper and Lower Bollinger Bands
|
22 |
+
upper_band = ma + (std_dev_multiplier * std_dev)
|
23 |
+
lower_band = ma - (std_dev_multiplier * std_dev)
|
24 |
+
|
25 |
+
bollinger_bands_df = pd.DataFrame(data={
|
26 |
+
'Moving_Average': ma,
|
27 |
+
'Upper_Band': upper_band,
|
28 |
+
'Lower_Band': lower_band
|
29 |
+
})
|
30 |
+
|
31 |
+
return bollinger_bands_df
|
32 |
+
|
33 |
+
if __name__ == "__main__":
|
34 |
+
# Example usage
|
35 |
+
data = {'Close': [22, 24, 23, 25, 26, 28, 27, 29, 30, 32, 31, 33]}
|
36 |
+
prices = pd.Series(data['Close'])
|
37 |
+
|
38 |
+
# User-defined parameters for Bollinger Bands
|
39 |
+
ma_length = 20 # Moving Average length
|
40 |
+
std_dev_multiplier = 2 # Standard Deviation Multiplier
|
41 |
+
|
42 |
+
# Calculate Bollinger Bands
|
43 |
+
bollinger_bands_df = calculate_bollinger_bands(prices, ma_length, std_dev_multiplier)
|
44 |
+
|
45 |
+
print(bollinger_bands_df)
|