43 lines
1.4 KiB
Python
Raw Normal View History

2025-06-07 14:01:20 +08:00
"""
Simple Moving Average (SMA) indicator implementation.
"""
import pandas as pd
from ..base import BaseIndicator
class SMAIndicator(BaseIndicator):
"""
Simple Moving Average (SMA) technical indicator.
Calculates the unweighted mean of previous n periods.
Handles sparse data appropriately without interpolation.
"""
def calculate(self, df: pd.DataFrame, period: int = 20,
price_column: str = 'close') -> pd.DataFrame:
2025-06-07 14:01:20 +08:00
"""
Calculate Simple Moving Average (SMA).
Args:
df: DataFrame with OHLCV data
period: Number of periods for moving average (default: 20)
price_column: Price column to use ('open', 'high', 'low', 'close')
Returns:
DataFrame with SMA values and metadata, indexed by timestamp
2025-06-07 14:01:20 +08:00
"""
# Validate input data
if not self.validate_dataframe(df, period):
return pd.DataFrame()
2025-06-07 14:01:20 +08:00
try:
df = df.copy()
2025-06-07 14:01:20 +08:00
df['sma'] = df[price_column].rolling(window=period, min_periods=period).mean()
# Only keep rows with valid SMA, and only 'timestamp' and 'sma' columns
result_df = df.loc[df['sma'].notna(), ['timestamp', 'sma']].copy()
result_df = result_df.iloc[period-1:]
result_df.set_index('timestamp', inplace=True)
return result_df
except Exception:
return pd.DataFrame()