82 lines
3.1 KiB
Python
Executable File
82 lines
3.1 KiB
Python
Executable File
"""Indicator helpers shared by strategies. All take closed candles, oldest first."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import math
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
|
|
MINUTES_PER_YEAR = 365 * 24 * 60
|
|
|
|
|
|
def periods_per_year(interval_minutes: int) -> float:
|
|
return MINUTES_PER_YEAR / interval_minutes
|
|
|
|
|
|
def sma(series: pd.Series, n: int) -> float:
|
|
return float(series.iloc[-n:].mean())
|
|
|
|
|
|
def ema(series: pd.Series, n: int) -> float:
|
|
return float(series.ewm(span=n, adjust=False).mean().iloc[-1])
|
|
|
|
|
|
def total_return(close: pd.Series, n: int) -> float:
|
|
return float(close.iloc[-1] / close.iloc[-1 - n] - 1)
|
|
|
|
|
|
def realized_vol(close: pd.Series, n: int, interval_minutes: int) -> float:
|
|
"""Annualized volatility of log returns over the last n candles."""
|
|
returns = np.log(close.iloc[-n - 1:]).diff().dropna()
|
|
return float(returns.std() * math.sqrt(periods_per_year(interval_minutes)))
|
|
|
|
|
|
def efficiency_ratio(close: pd.Series, n: int) -> float:
|
|
"""Kaufman efficiency ratio: 1 = straight-line trend, ~0 = pure chop."""
|
|
window = close.iloc[-n - 1:]
|
|
path = window.diff().abs().sum()
|
|
return float(abs(window.iloc[-1] - window.iloc[0]) / path) if path else 0.0
|
|
|
|
|
|
def zscore(close: pd.Series, n: int) -> float:
|
|
window = close.iloc[-n:]
|
|
std = window.std()
|
|
return float((window.iloc[-1] - window.mean()) / std) if std else 0.0
|
|
|
|
|
|
def is_rebalance_candle(candles: pd.DataFrame, interval_minutes: int, every: int) -> bool:
|
|
"""True on every `every`-th candle, aligned to the Unix epoch so it survives restarts."""
|
|
minutes = int(candles.index[-1].timestamp() // 60)
|
|
return (minutes // interval_minutes) % every == 0
|
|
|
|
|
|
def vol_scale(close: pd.Series, target_vol: float, window: int, interval_minutes: int) -> float:
|
|
"""Leverage-free volatility targeting: shrink exposure when an asset is wilder than target."""
|
|
vol = realized_vol(close, window, interval_minutes)
|
|
return min(1.0, target_vol / vol) if vol > 0 else 0.0
|
|
|
|
|
|
def select_with_buffer(
|
|
scores: dict[str, float], weights: dict[str, float], top_k: int, buffer: int, floor: float | None = 0.0
|
|
) -> list[str]:
|
|
"""Top-k by score, but keep current holdings that still rank within top_k + buffer.
|
|
Pairs scoring at or below `floor` are never selected."""
|
|
eligible = {p: s for p, s in scores.items() if floor is None or s > floor}
|
|
ranked = sorted(eligible, key=eligible.get, reverse=True)
|
|
keep = [p for p in ranked[: top_k + buffer] if weights.get(p, 0) > 0][:top_k]
|
|
fill = [p for p in ranked if p not in keep][: top_k - len(keep)]
|
|
return keep + fill
|
|
|
|
|
|
def banded(targets: dict[str, float], current: dict[str, float], band: float) -> dict[str, float]:
|
|
"""Drop target changes smaller than `band` to avoid paying fees for tiny resizes.
|
|
Moves to or from zero always go through."""
|
|
out = {}
|
|
for pair, target in targets.items():
|
|
now = current.get(pair, 0.0)
|
|
if target == 0 or now == 0 or abs(target - now) >= band:
|
|
if not (target == 0 and now == 0):
|
|
out[pair] = target
|
|
return out
|