Spaces:
Sleeping
Sleeping
| # models/technical_analysis.py | |
| import pandas as pd | |
| import numpy as np | |
| import ta | |
| class EnhancedTechnicalAnalysis: | |
| def __init__(self, data: pd.DataFrame): | |
| """Initialize with DataFrame containing OHLCV data.""" | |
| self.data = data.copy() | |
| def calculate_all_indicators(self) -> pd.DataFrame: | |
| """Calculate all technical indicators.""" | |
| try: | |
| # Convert numeric columns without setting index | |
| numeric_columns = ['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'] | |
| for col in numeric_columns: | |
| if col in self.data.columns: | |
| self.data[col] = pd.to_numeric(self.data[col], errors='coerce') | |
| # Use Close price for calculations | |
| close_price = self.data['Adj Close'] if 'Adj Close' in self.data.columns else self.data['Close'] | |
| # Trend Indicators | |
| self.data['SMA_20'] = ta.trend.sma_indicator(close=close_price, window=20) | |
| self.data['SMA_50'] = ta.trend.sma_indicator(close=close_price, window=50) | |
| self.data['EMA_20'] = ta.trend.ema_indicator(close=close_price, window=20) | |
| macd = ta.trend.MACD(close=close_price) | |
| self.data['MACD'] = macd.macd() | |
| self.data['MACD_Signal'] = macd.macd_signal() | |
| # Momentum Indicators | |
| self.data['RSI'] = ta.momentum.RSIIndicator(close=close_price).rsi() | |
| if all(col in self.data.columns for col in ['High', 'Low']): | |
| self.data['Stoch'] = ta.momentum.StochasticOscillator( | |
| high=self.data['High'], | |
| low=self.data['Low'], | |
| close=close_price | |
| ).stoch() | |
| # Volatility Indicators | |
| bb = ta.volatility.BollingerBands(close=close_price) | |
| self.data['BB_Upper'] = bb.bollinger_hband() | |
| self.data['BB_Lower'] = bb.bollinger_lband() | |
| self.data['BB_Middle'] = bb.bollinger_mavg() | |
| # Volume Indicators | |
| if 'Volume' in self.data.columns: | |
| self.data['OBV'] = ta.volume.OnBalanceVolumeIndicator( | |
| close=close_price, | |
| volume=self.data['Volume'] | |
| ).on_balance_volume() | |
| return self.data | |
| except Exception as e: | |
| print(f"Error calculating indicators: {str(e)}") | |
| return self.data |