Download scripts/strategies.py from anonymous-quantinv/quantinvbench: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/datasets/anonymous-quantinv/quantinvbench/resolve/main/scripts/strategies.py
- Command line
-
hf download hf://datasets/anonymous-quantinv/quantinvbench/scripts/strategies.py
-
curl -L -o strategies.py https://huggingface.co/datasets/anonymous-quantinv/quantinvbench/resolve/main/scripts/strategies.py
10 kB
| """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 | |
| ] | |