59 lines
1.9 KiB
Python
59 lines
1.9 KiB
Python
"""
|
|
Simple Moving Average (SMA) indicator implementation.
|
|
"""
|
|
|
|
from typing import List
|
|
import pandas as pd
|
|
|
|
from ..base import BaseIndicator
|
|
from ..result import IndicatorResult
|
|
|
|
|
|
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') -> List[IndicatorResult]:
|
|
"""
|
|
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:
|
|
List of indicator results with SMA values
|
|
"""
|
|
# Validate input data
|
|
if not self.validate_dataframe(df, period):
|
|
return []
|
|
|
|
try:
|
|
# Calculate SMA using pandas rolling window
|
|
df['sma'] = df[price_column].rolling(window=period, min_periods=period).mean()
|
|
|
|
# Convert results to IndicatorResult objects
|
|
results = []
|
|
for timestamp, row in df.iterrows():
|
|
if not pd.isna(row['sma']):
|
|
result = IndicatorResult(
|
|
timestamp=timestamp,
|
|
symbol=row['symbol'],
|
|
timeframe=row['timeframe'],
|
|
values={'sma': row['sma']},
|
|
metadata={'period': period, 'price_column': price_column}
|
|
)
|
|
results.append(result)
|
|
|
|
return results
|
|
|
|
except Exception as e:
|
|
if self.logger:
|
|
self.logger.error(f"Error calculating SMA: {e}")
|
|
return [] |