Spaces:
Runtime error
Runtime error
Update indicators/sma.py
Browse files- indicators/sma.py +29 -26
indicators/sma.py
CHANGED
|
@@ -1,42 +1,45 @@
|
|
| 1 |
-
# indicators/sma.py
|
| 2 |
-
|
| 3 |
import pandas as pd
|
| 4 |
|
| 5 |
-
def calculate_sma(data,
|
| 6 |
"""
|
| 7 |
-
|
| 8 |
|
| 9 |
Parameters:
|
| 10 |
-
- data:
|
| 11 |
-
-
|
| 12 |
|
| 13 |
Returns:
|
| 14 |
-
-
|
| 15 |
"""
|
| 16 |
-
|
| 17 |
-
return sma
|
| 18 |
|
| 19 |
-
def
|
| 20 |
"""
|
| 21 |
-
|
| 22 |
|
| 23 |
Parameters:
|
| 24 |
-
- data
|
| 25 |
|
| 26 |
-
|
| 27 |
-
-
|
| 28 |
"""
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
# Example usage
|
| 33 |
if __name__ == "__main__":
|
| 34 |
-
#
|
| 35 |
-
#
|
| 36 |
-
dates = pd.date_range(start=
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 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_21_50_sma(data):
|
| 17 |
"""
|
| 18 |
+
Calculate both the 21-period and 50-period SMAs for the given stock data.
|
| 19 |
|
| 20 |
Parameters:
|
| 21 |
+
- data (pd.DataFrame): The stock data, expected to have a 'Close' column.
|
| 22 |
|
| 23 |
+
Returns:
|
| 24 |
+
- pd.DataFrame: The input data frame with added columns for the 21-period and 50-period SMAs.
|
| 25 |
"""
|
| 26 |
+
if 'Close' not in data.columns:
|
| 27 |
+
raise ValueError("Data frame must contain a 'Close' column.")
|
| 28 |
+
|
| 29 |
+
# Calculate the SMAs
|
| 30 |
+
data['SMA_21'] = calculate_sma(data['Close'], 21)
|
| 31 |
+
data['SMA_50'] = calculate_sma(data['Close'], 50)
|
| 32 |
+
|
| 33 |
+
return data
|
| 34 |
|
|
|
|
| 35 |
if __name__ == "__main__":
|
| 36 |
+
# Example usage
|
| 37 |
+
# Generate a sample DataFrame with 'Close' prices
|
| 38 |
+
dates = pd.date_range(start='2023-01-01', periods=100, freq='D')
|
| 39 |
+
close_prices = pd.Series((100 + np.random.randn(100).cumsum()), index=dates)
|
| 40 |
+
sample_data = pd.DataFrame({'Close': close_prices})
|
| 41 |
+
|
| 42 |
+
# Calculate the 21 and 50 period SMAs
|
| 43 |
+
sma_data = calculate_21_50_sma(sample_data)
|
| 44 |
+
|
| 45 |
+
print(sma_data.head()) # Print the first few rows to verify
|