File size: 10,006 Bytes
8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 | 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | """Causal, deterministic strategy implementations used by the HF generator."""
from __future__ import annotations
import json
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Mapping
import numpy as np
import pandas as pd
from scipy.optimize import minimize
from common import COINS, STRATEGIES, usdt_fallback, validated_weights
History = Mapping[str, pd.DataFrame]
def _normalize(raw: Mapping[str, float], name: str) -> list[float]:
return validated_weights(raw, label=name)
def _positive_signal_or_usdt(signal: Mapping[str, float]) -> dict[str, float]:
raw = {coin: max(0.0, float(signal.get(coin, 0.0))) for coin in COINS}
if sum(raw.values()) <= 1e-15:
return usdt_fallback()
return raw
def momentum(history: History, lookback: int = 5) -> list[float]:
raw = {}
for coin in COINS:
prices = history[coin]["open"].to_numpy(dtype=float)
if len(prices) < lookback + 1 or prices[-lookback - 1] <= 0:
raw[coin] = 0.0
continue
change = prices[-1] / prices[-lookback - 1] - 1.0
raw[coin] = max(0.0, float(np.tanh(5.0 * change)))
raw = _positive_signal_or_usdt(raw)
total = sum(raw.values())
if total < 1.0 and raw != usdt_fallback():
raw["tether"] += 1.0 - total
return _normalize(raw, "Momentum")
def max_sharpe(history: History, lookback: int = 252) -> list[float]:
return_series = []
for coin in COINS:
prices = history[coin]["open"].tail(lookback + 1).to_numpy(dtype=float)
if len(prices) < 3 or np.any(prices[:-1] <= 0):
raise ValueError(f"MaxSharpe: insufficient price history for {coin}")
return_series.append(np.diff(prices) / prices[:-1])
common_length = min(len(values) for values in return_series)
matrix = np.column_stack([values[-common_length:] for values in return_series])
expected = matrix.mean(axis=0)
covariance = np.cov(matrix, rowvar=False)
raw_vector = np.linalg.pinv(covariance, rcond=1e-10) @ expected
raw_vector = np.maximum(raw_vector, 0.0)
raw = dict(zip(COINS, raw_vector.tolist()))
return _normalize(_positive_signal_or_usdt(raw), "MaxSharpe")
def ts_momentum(history: History, period: int, name: str) -> list[float]:
raw = {}
for coin in COINS:
prices = history[coin]["open"].to_numpy(dtype=float)
if len(prices) <= period or prices[-period - 1] <= 0 or prices[-1] <= 0:
raw[coin] = 0.0
continue
raw[coin] = max(0.0, float(np.log(prices[-1]) - np.log(prices[-period - 1])))
return _normalize(_positive_signal_or_usdt(raw), name)
def risk_parity(history: History, lookback: int = 60) -> list[float]:
inverse_volatility = {}
for coin in COINS:
prices = history[coin]["open"].tail(lookback + 1).to_numpy(dtype=float)
if len(prices) < 11 or np.any(prices[:-1] <= 0):
raise ValueError(f"RiskParity: insufficient price history for {coin}")
volatility = float(np.std(np.diff(prices) / prices[:-1]))
inverse_volatility[coin] = 1.0 / max(volatility, 1e-8)
return _normalize(inverse_volatility, "RiskParity")
def min_variance(history: History, lookback: int = 60) -> list[float]:
return_series = []
for coin in COINS:
prices = history[coin]["open"].tail(lookback + 1).to_numpy(dtype=float)
if len(prices) < 11 or np.any(prices[:-1] <= 0):
raise ValueError(f"MinVar: insufficient price history for {coin}")
return_series.append(np.diff(prices) / prices[:-1])
common_length = min(len(values) for values in return_series)
matrix = np.column_stack([values[-common_length:] for values in return_series])
covariance = np.atleast_2d(np.cov(matrix, rowvar=False))
if covariance.shape != (len(COINS), len(COINS)) or not np.isfinite(
covariance
).all():
raise ValueError("MinVar: invalid covariance matrix")
# Scaling preserves the optimum while keeping SLSQP's stopping criteria
# meaningful for daily return covariances, which are typically very small.
scale = float(np.max(np.abs(covariance)))
scaled_covariance = covariance / scale if scale > 0 else covariance
initial = np.full(len(COINS), 1.0 / len(COINS), dtype=float)
result = minimize(
fun=lambda weights: float(weights @ scaled_covariance @ weights),
x0=initial,
jac=lambda weights: 2.0 * scaled_covariance @ weights,
method="SLSQP",
bounds=[(0.0, 1.0)] * len(COINS),
constraints={
"type": "eq",
"fun": lambda weights: float(np.sum(weights) - 1.0),
"jac": lambda weights: np.ones_like(weights),
},
options={"ftol": 1e-12, "maxiter": 1_000, "disp": False},
)
if not result.success or not np.isfinite(result.x).all():
raise ValueError(f"MinVar: optimization failed: {result.message}")
return _normalize(dict(zip(COINS, result.x.tolist())), "MinVar")
class SentimentIndex:
"""Precomputed FinBERT scores indexed without retaining article text."""
def __init__(self, path: Path):
if not path.exists():
raise FileNotFoundError(
f"Missing FinBERT sentiment file: {path}. "
"Run scripts/compute_sentiment.py before generate.py."
)
with path.open(encoding="utf-8") as handle:
payload = json.load(handle)
articles = payload if isinstance(payload, list) else payload.get("articles", [])
self._records: dict[
str, list[tuple[datetime, float, tuple[str, ...]]]
] = defaultdict(list)
for article in articles:
timestamp = str(article.get("timestamp", ""))
score = article.get("sentiment")
coins = tuple(coin for coin in article.get("coins", COINS) if coin in COINS)
if len(timestamp) < 10 or not isinstance(score, (int, float)) or not coins:
continue
try:
published_at = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
except ValueError:
continue
if published_at.tzinfo is None:
published_at = published_at.replace(tzinfo=timezone.utc)
published_at = published_at.astimezone(timezone.utc)
self._records[published_at.date().isoformat()].append(
(published_at, float(score), coins)
)
def weights(self, as_of: datetime, lookback_days: int = 45) -> list[float]:
scores: dict[str, list[float]] = {coin: [] for coin in COINS}
for offset in range(lookback_days):
day = (as_of - timedelta(days=offset)).date().isoformat()
for published_at, score, mentioned_coins in self._records.get(day, []):
if published_at > as_of:
continue
for coin in mentioned_coins:
scores[coin].append(score)
averages = np.array(
[float(np.mean(scores[coin])) if scores[coin] else 0.0 for coin in COINS]
)
standard_deviation = float(averages.std())
z_scores = (
(averages - averages.mean()) / standard_deviation
if standard_deviation > 1e-8
else np.zeros_like(averages)
)
tilted = np.maximum((1.0 / len(COINS)) * (1.0 + 0.3 * z_scores), 0.0)
return validated_weights(tilted.tolist(), label="NewsSentiment")
def size(history: History, lookback: int = 30) -> list[float]:
inverse_size = {}
for coin in COINS:
recent = history[coin].tail(lookback)
proxy = float((recent["close"] * recent["volume"]).mean())
if not np.isfinite(proxy) or proxy <= 0:
raise ValueError(f"Size: invalid size proxy for {coin}")
inverse_size[coin] = 1.0 / proxy
return _normalize(inverse_size, "Size")
def value_nvt(history: History, lookback: int = 30) -> list[float]:
inverse_nvt = {}
for coin in COINS:
recent = history[coin].tail(lookback)
quote_volume = recent["quote_volume"].to_numpy(dtype=float)
close = recent["close"].to_numpy(dtype=float)
valid = quote_volume > 0
if not valid.any():
raise ValueError(f"ValueNVT: invalid quote volume for {coin}")
nvt = float(np.median(np.square(close[valid]) / quote_volume[valid]))
inverse_nvt[coin] = 1.0 / max(nvt, 1e-18)
return _normalize(inverse_nvt, "ValueNVT")
def liquidity(history: History, lookback: int = 30) -> list[float]:
inverse_illiquidity = {}
for coin in COINS:
recent = history[coin].tail(lookback + 1)
close = recent["close"].to_numpy(dtype=float)
quote_volume = recent["quote_volume"].to_numpy(dtype=float)[1:]
returns = np.abs(np.diff(close) / close[:-1])
valid = quote_volume > 0
if not valid.any():
raise ValueError(f"Liquidity: invalid quote volume for {coin}")
illiquidity = float(np.mean(returns[valid] / quote_volume[valid]))
inverse_illiquidity[coin] = 1.0 / max(illiquidity, 1e-18)
return _normalize(inverse_illiquidity, "Liquidity")
def compute_proposals(
history: History,
sentiment: SentimentIndex,
as_of: datetime,
) -> list[dict]:
if as_of.tzinfo is None:
as_of = as_of.replace(tzinfo=timezone.utc)
proposal_map = {
"Momentum": momentum(history),
"MaxSharpe": max_sharpe(history),
"TSMom14": ts_momentum(history, 14, "TSMom14"),
"TSMom60": ts_momentum(history, 60, "TSMom60"),
"RiskParity": risk_parity(history),
"MinVar": min_variance(history),
"NewsSentiment": sentiment.weights(as_of),
"Size": size(history),
"ValueNVT": value_nvt(history),
"Liquidity": liquidity(history),
}
return [
{"strategy": name, "weights": proposal_map[name]}
for name in STRATEGIES
]
|