netflypsb commited on
Commit
40603e9
1 Parent(s): 1c344c6

Update indicators/bollinger_bands.py

Browse files
Files changed (1) hide show
  1. indicators/bollinger_bands.py +35 -20
indicators/bollinger_bands.py CHANGED
@@ -1,39 +1,54 @@
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
 
 
 
 
1
  import pandas as pd
2
 
3
+ def calculate_sma(data, window):
4
  """
5
+ Calculate the Simple Moving Average (SMA) for the given data.
6
+
7
  Parameters:
8
+ - data (pd.Series): The stock data (typically closing prices).
9
+ - window (int): The period over which to calculate the SMA.
10
+
11
+ Returns:
12
+ - pd.Series: The calculated SMA values.
13
+ """
14
+ return data.rolling(window=window, min_periods=1).mean()
15
 
16
+ def calculate_bollinger_bands(data, window=21, std_multiplier=1.7):
17
+ """
18
+ Calculate Bollinger Bands for the given stock data.
19
+
20
+ Parameters:
21
+ - data (pd.DataFrame): The stock data, expected to have a 'Close' column.
22
+ - window (int): The SMA period for the middle band. Defaults to 21.
23
+ - std_multiplier (float): The standard deviation multiplier for the upper and lower bands. Defaults to 1.7.
24
+
25
  Returns:
26
+ - pd.DataFrame: The input data frame with added columns for the Bollinger Bands ('BB_Middle', 'BB_Upper', 'BB_Lower').
27
  """
28
+ if 'Close' not in data.columns:
29
+ raise ValueError("Data frame must contain a 'Close' column.")
30
+
31
  # Calculate the middle band (SMA)
32
+ data['BB_Middle'] = calculate_sma(data['Close'], window)
33
 
34
  # Calculate the standard deviation
35
+ std_dev = data['Close'].rolling(window=window).std()
36
 
37
  # Calculate the upper and lower bands
38
  data['BB_Upper'] = data['BB_Middle'] + (std_multiplier * std_dev)
39
  data['BB_Lower'] = data['BB_Middle'] - (std_multiplier * std_dev)
40
 
41
+ return data
42
 
 
43
  if __name__ == "__main__":
44
+ # Example usage
45
+ # Generate a sample DataFrame with 'Close' prices
46
+ import numpy as np
47
+ dates = pd.date_range(start='2023-01-01', periods=100, freq='D')
48
+ close_prices = pd.Series((100 + np.random.randn(100).cumsum()), index=dates)
49
+ sample_data = pd.DataFrame({'Close': close_prices})
50
 
51
  # Calculate Bollinger Bands
52
+ bb_data = calculate_bollinger_bands(sample_data)
53
+
54
+ print(bb_data.head()) # Print the first few rows to verify