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

Create indicators/sma.py

Browse files
Files changed (1) hide show
  1. indicators/sma.py +42 -0
indicators/sma.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # indicators/sma.py
2
+
3
+ import pandas as pd
4
+
5
+ def calculate_sma(data, period):
6
+ """
7
+ Calculates the Simple Moving Average (SMA) for a given period.
8
+
9
+ Parameters:
10
+ - data: DataFrame containing stock prices with a 'Close' column (DataFrame).
11
+ - period: The period over which to calculate the SMA (int).
12
+
13
+ Returns:
14
+ - sma: The calculated SMA as a Series (pd.Series).
15
+ """
16
+ sma = data['Close'].rolling(window=period, min_periods=1).mean()
17
+ return sma
18
+
19
+ def add_sma_columns(data):
20
+ """
21
+ Adds SMA columns for the 21 and 50 periods to the input DataFrame.
22
+
23
+ Parameters:
24
+ - data: DataFrame containing stock prices. Must include a 'Close' column (DataFrame).
25
+
26
+ Modifies:
27
+ - data: The input DataFrame is modified in-place, adding two new columns: 'SMA_21' and 'SMA_50'.
28
+ """
29
+ data['SMA_21'] = calculate_sma(data, 21)
30
+ data['SMA_50'] = calculate_sma(data, 50)
31
+
32
+ # Example usage
33
+ if __name__ == "__main__":
34
+ # Assuming 'data' is a DataFrame that contains stock price data including a 'Close' column.
35
+ # For the sake of example, let's create a dummy DataFrame.
36
+ dates = pd.date_range(start="2023-01-01", end="2023-02-28", freq='D')
37
+ prices = pd.Series([i * 0.01 for i in range(len(dates))], index=dates)
38
+ data = pd.DataFrame(prices, columns=['Close'])
39
+
40
+ # Add SMA columns
41
+ add_sma_columns(data)
42
+ print(data.head()) # Display the first few rows to verify the SMA calculations