-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindicators.py
More file actions
51 lines (40 loc) · 1.67 KB
/
indicators.py
File metadata and controls
51 lines (40 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from abc import ABC, abstractmethod
import pandas as pd
from typing import Dict
class Indicator(ABC):
@property
@abstractmethod
def column_name(self) -> str:
"""The name of the column this indicator will generate."""
pass
@abstractmethod
def calculate(self, data: pd.DataFrame) -> Dict[str, pd.Series]:
pass
class SMAIndicator(Indicator):
def __init__(self, period: int):
self.period = period
self._column_name = f"SMA_{self.period}"
@property
def column_name(self) -> str:
return self._column_name
def calculate(self, data: pd.DataFrame) -> Dict[str, pd.Series]:
return {self.column_name: data['Close'].rolling(window=self.period).mean()}
class ATRIndicator(Indicator):
def __init__(self, period: int = 14):
self.period = period
self._column_name = f"ATR_{self.period}"
@property
def column_name(self) -> str:
return self._column_name
def calculate(self, data: pd.DataFrame) -> Dict[str, pd.Series]:
"""Calculates the Average True Range (ATR)."""
data_copy = data.copy()
# Calculate the components of True Range
high_low = data_copy['High'] - data_copy['Low']
high_prev_close = abs(data_copy['High'] - data_copy['Close'].shift(1))
low_prev_close = abs(data_copy['Low'] - data_copy['Close'].shift(1))
# Determine the True Range (TR)
tr = pd.concat([high_low, high_prev_close, low_prev_close], axis=1).max(axis=1)
# Calculate the Average True Range (ATR) using an exponential moving average
atr = tr.ewm(span=self.period, adjust=False).mean()
return {self.column_name: atr}