tvta-vision / src /indicators.py
s31EmDe's picture ismailtasdelen's picture
Duplicate from ismailtasdelen/tvta-vision
922bf26
Raw History Blame Contribute Delete
11.4 kB
"""
Technical Indicator Calculator
Calculates trend, momentum, volatility, and volume indicators for the TVTA Vision Dataset.
"""
import numpy as np
import pandas as pd
from typing import Dict, Any, Optional
def calc_ema(series: pd.Series, period: int) -> pd.Series:
return series.ewm(span=period, adjust=False).mean()
def calc_sma(series: pd.Series, period: int) -> pd.Series:
return series.rolling(window=period).mean()
def calc_rsi(series: pd.Series, period: int = 14) -> pd.Series:
delta = series.diff()
gain = delta.where(delta > 0, 0.0)
loss = -delta.where(delta < 0, 0.0)
avg_gain = gain.ewm(alpha=1.0 / period, adjust=False).mean()
avg_loss = loss.ewm(alpha=1.0 / period, adjust=False).mean()
rs = avg_gain / avg_loss
return 100.0 - (100.0 / (1.0 + rs))
def calc_macd(
series: pd.Series, fast: int = 12, slow: int = 26, signal: int = 9
) -> tuple[pd.Series, pd.Series, pd.Series]:
ema_fast = calc_ema(series, fast)
ema_slow = calc_ema(series, slow)
macd_line = ema_fast - ema_slow
signal_line = calc_ema(macd_line, signal)
histogram = macd_line - signal_line
return macd_line, signal_line, histogram
def calc_bollinger_bands(
series: pd.Series, period: int = 20, std_dev: float = 2.0
) -> tuple[pd.Series, pd.Series, pd.Series]:
sma = calc_sma(series, period)
std = series.rolling(window=period).std()
upper = sma + std_dev * std
lower = sma - std_dev * std
return upper, sma, lower
def calc_atr(
df: pd.DataFrame, period: int = 14
) -> pd.Series:
high = df["high"]
low = df["low"]
close = df["close"]
prev_close = close.shift(1)
tr = pd.concat(
[
(high - low),
(high - prev_close).abs(),
(low - prev_close).abs(),
],
axis=1,
).max(axis=1)
return tr.ewm(alpha=1.0 / period, adjust=False).mean()
def calc_stochastic(
df: pd.DataFrame, k_period: int = 14, d_period: int = 3
) -> tuple[pd.Series, pd.Series]:
low_min = df["low"].rolling(window=k_period).min()
high_max = df["high"].rolling(window=k_period).max()
k = 100.0 * (df["close"] - low_min) / (high_max - low_min)
d = k.rolling(window=d_period).mean()
return k, d
def calc_cci(df: pd.DataFrame, period: int = 20) -> pd.Series:
typical_price = (df["high"] + df["low"] + df["close"]) / 3.0
sma_tp = calc_sma(typical_price, period)
mad = typical_price.rolling(window=period).apply(
lambda x: np.abs(x - x.mean()).mean(), raw=True
)
return (typical_price - sma_tp) / (0.015 * mad)
def calc_williams_r(df: pd.DataFrame, period: int = 14) -> pd.Series:
high_max = df["high"].rolling(window=period).max()
low_min = df["low"].rolling(window=period).min()
return -100.0 * (high_max - df["close"]) / (high_max - low_min)
def calc_obv(df: pd.DataFrame) -> pd.Series:
direction = np.sign(df["close"].diff())
direction.iloc[0] = 0
return (direction * df["volume"]).cumsum()
def calc_adx(df: pd.DataFrame, period: int = 14) -> pd.Series:
"""Average Directional Index."""
high = df["high"]
low = df["low"]
close = df["close"]
up_move = high.diff()
down_move = -low.diff()
plus_dm = pd.Series(np.where((up_move > down_move) & (up_move > 0), up_move, 0.0), index=df.index)
minus_dm = pd.Series(np.where((down_move > up_move) & (down_move > 0), down_move, 0.0), index=df.index)
atr = calc_atr(df, period)
plus_di = 100.0 * (calc_ema(plus_dm, period) / atr)
minus_di = 100.0 * (calc_ema(minus_dm, period) / atr)
dx = 100.0 * np.abs(plus_di - minus_di) / (plus_di + minus_di)
dx = dx.fillna(0)
adx = calc_ema(dx, period)
return adx
def calc_vwap(df: pd.DataFrame) -> pd.Series:
"""Volume Weighted Price (intraday, resets daily)."""
typical_price = (df["high"] + df["low"] + df["close"]) / 3.0
return (typical_price * df["volume"]).cumsum() / df["volume"].cumsum()
def calc_ichimoku(df: pd.DataFrame) -> dict:
"""Ichimoku Cloud components."""
high = df["high"]
low = df["low"]
close = df["close"]
tenkan = (high.rolling(9).max() + low.rolling(9).min()) / 2.0
kijun = (high.rolling(26).max() + low.rolling(26).min()) / 2.0
senkou_a = ((tenkan + kijun) / 2.0).shift(26)
senkou_b = ((high.rolling(52).max() + low.rolling(52).min()) / 2.0).shift(26)
chikou = close.shift(-26)
return {
"tenkan_sen": tenkan,
"kijun_sen": kijun,
"senkou_span_a": senkou_a,
"senkou_span_b": senkou_b,
"chikou_span": chikou,
}
def calc_stoch_rsi(
series: pd.Series, rsi_period: int = 14, stoch_period: int = 14, k_smooth: int = 3, d_smooth: int = 3
) -> tuple[pd.Series, pd.Series]:
rsi = calc_rsi(series, rsi_period)
rsi_min = rsi.rolling(stoch_period).min()
rsi_max = rsi.rolling(stoch_period).max()
stoch = 100.0 * (rsi - rsi_min) / (rsi_max - rsi_min)
k = stoch.rolling(k_smooth).mean()
d = k.rolling(d_smooth).mean()
return k, d
def calc_historical_volatility(
series: pd.Series, period: int = 20
) -> pd.Series:
"""Annualized historical volatility from log returns."""
log_ret = np.log(series / series.shift(1))
return log_ret.rolling(period).std() * np.sqrt(252)
def calc_keltner_channels(
df: pd.DataFrame, ema_period: int = 20, atr_period: int = 10, multiplier: float = 1.5
) -> tuple[pd.Series, pd.Series, pd.Series]:
ema = calc_ema(df["close"], ema_period)
atr = calc_atr(df, atr_period)
upper = ema + multiplier * atr
lower = ema - multiplier * atr
return upper, ema, lower
def compute_all_indicators(df: pd.DataFrame) -> pd.DataFrame:
"""Compute all indicators and return enriched DataFrame."""
out = df.copy()
# Trend
for p in [9, 20, 50, 100, 200]:
out[f"ema_{p}"] = calc_ema(out["close"], p)
for p in [20, 50, 100, 200]:
out[f"sma_{p}"] = calc_sma(out["close"], p)
out["vwap"] = calc_vwap(out)
out["adx"] = calc_adx(out)
# Momentum
out["rsi_14"] = calc_rsi(out["close"], 14)
macd, signal, hist = calc_macd(out["close"])
out["macd"] = macd
out["macd_signal"] = signal
out["macd_histogram"] = hist
out["cci_20"] = calc_cci(out, 20)
out["williams_r_14"] = calc_williams_r(out, 14)
stoch_k, stoch_d = calc_stochastic(out, 14, 3)
out["stoch_k"] = stoch_k
out["stoch_d"] = stoch_d
stoch_rsi_k, stoch_rsi_d = calc_stoch_rsi(out["close"])
out["stoch_rsi_k"] = stoch_rsi_k
out["stoch_rsi_d"] = stoch_rsi_d
# Volatility
out["atr_14"] = calc_atr(out, 14)
bb_upper, bb_mid, bb_lower = calc_bollinger_bands(out["close"])
out["bb_upper"] = bb_upper
out["bb_middle"] = bb_mid
out["bb_lower"] = bb_lower
kc_upper, kc_mid, kc_lower = calc_keltner_channels(out)
out["kc_upper"] = kc_upper
out["kc_middle"] = kc_mid
out["kc_lower"] = kc_lower
out["hist_vol_20"] = calc_historical_volatility(out["close"], 20)
# Volume
out["obv"] = calc_obv(out)
out["volume_sma_20"] = calc_sma(out["volume"], 20)
# Ichimoku
ichi = calc_ichimoku(out)
for k, v in ichi.items():
out[f"ichi_{k}"] = v
return out
def get_indicator_state(df: pd.DataFrame, idx: int = -1) -> Dict[str, Any]:
"""Extract indicator state at a given index for labeling."""
if idx < 0:
idx = len(df) + idx
if idx < 0 or idx >= len(df):
idx = len(df) - 1
row = df.iloc[idx]
prev = df.iloc[idx - 1] if idx > 0 else row
# RSI state
rsi_val = row.get("rsi_14", 50)
if rsi_val > 70:
rsi_zone = "overbought"
rsi_state = "bearish_warning"
elif rsi_val > 60:
rsi_zone = "neutral_bullish"
rsi_state = "bullish_momentum"
elif rsi_val > 40:
rsi_zone = "neutral"
rsi_state = "neutral_momentum"
elif rsi_val > 30:
rsi_zone = "neutral_bearish"
rsi_state = "bearish_momentum"
else:
rsi_zone = "oversold"
rsi_state = "bullish_warning"
# MACD state
macd_val = row.get("macd", 0)
macd_sig = row.get("macd_signal", 0)
macd_hist = row.get("macd_histogram", 0)
prev_hist = prev.get("macd_histogram", 0) if idx > 0 else 0
if macd_val > macd_sig and macd_hist > prev_hist:
macd_state = "bullish_strengthening"
elif macd_val > macd_sig:
macd_state = "bullish"
elif macd_val < macd_sig and macd_hist < prev_hist:
macd_state = "bearish_strengthening"
else:
macd_state = "bearish"
# EMA alignment
ema20 = row.get("ema_20", 0)
ema50 = row.get("ema_50", 0)
ema100 = row.get("ema_100", 0)
ema200 = row.get("ema_200", 0)
close = row.get("close", 0)
ema_alignment = "neutral"
if ema20 > ema50 > ema100 > ema200:
ema_alignment = "bullish"
elif ema20 < ema50 < ema100 < ema200:
ema_alignment = "bearish"
price_above_ema200 = close > ema200 if ema200 > 0 else False
# Bollinger position
bb_upper = row.get("bb_upper", 0)
bb_lower = row.get("bb_lower", 0)
bb_width = (bb_upper - bb_lower) / row.get("bb_middle", 1) if row.get("bb_middle", 0) > 0 else 0
if close > bb_upper * 0.99:
bb_position = "above_upper"
elif close > row.get("bb_middle", 0):
bb_position = "upper_half"
elif close > bb_lower * 1.01:
bb_position = "lower_half"
else:
bb_position = "below_lower"
# ADX trend strength
adx_val = row.get("adx", 20)
if adx_val > 40:
trend_strength = "very_strong"
elif adx_val > 25:
trend_strength = "strong"
elif adx_val > 20:
trend_strength = "moderate"
else:
trend_strength = "weak"
# Volume analysis
vol = row.get("volume", 0)
vol_sma = row.get("volume_sma_20", 1)
vol_ratio = vol / vol_sma if vol_sma > 0 else 1.0
if vol_ratio > 2.0:
vol_class = "very_high_volume"
elif vol_ratio > 1.5:
vol_class = "high_volume"
elif vol_ratio > 0.75:
vol_class = "normal_volume"
elif vol_ratio > 0.5:
vol_class = "low_volume"
else:
vol_class = "very_low_volume"
return {
"rsi": {"value": round(float(rsi_val), 2), "state": rsi_state, "zone": rsi_zone},
"macd": {
"value": round(float(macd_val), 4),
"signal": round(float(macd_sig), 4),
"histogram": round(float(macd_hist), 4),
"state": macd_state,
},
"ema_structure": {
"ema20_above_ema50": bool(ema20 > ema50),
"ema50_above_ema200": bool(ema50 > ema200),
"price_above_ema200": bool(price_above_ema200),
"alignment": ema_alignment,
},
"bollinger_position": bb_position,
"bollinger_width": round(float(bb_width), 4),
"adx": {"value": round(float(adx_val), 2), "trend_strength": trend_strength},
"volume_analysis": {
"current_volume_vs_average": round(float(vol_ratio), 2),
"classification": vol_class,
},
"stochastic": {
"k": round(float(row.get("stoch_k", 50)), 2),
"d": round(float(row.get("stoch_d", 50)), 2),
},
"cci": round(float(row.get("cci_20", 0)), 2),
"williams_r": round(float(row.get("williams_r_14", -50)), 2),
"atr": round(float(row.get("atr_14", 0)), 4),
}