File size: 10,499 Bytes
ff4becd | 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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | """Evaluation functions for MacroLens benchmark."""
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
from ._compat import (
evaluate_generation,
evaluate_re_valuation,
evaluate_scenario_forecast,
evaluate_valuation,
)
from ._meta import BENCHMARK_NAME, BENCHMARK_VERSION
_TASK_ALIASES: dict[str, str] = {
# Task 1 (TSF)
"1": "TSF",
"tsf": "TSF",
"time_series": "TSF",
"forecasting": "TSF",
# Task 2 (Val-PT)
"2": "A",
"a": "A",
"valuation": "A",
"val-pt": "A",
# Task 3 (Stmt-Gen)
"3": "B",
"b": "B",
"statement": "B",
"stmt-gen": "B",
# Task 4 (Scen-Ret)
"4": "C",
"c": "C",
"scenario": "C",
"scen-ret": "C",
# Task 5 (Priv-Val)
"5": "D",
"d": "D",
"private_valuation": "D",
"priv-val": "D",
# Task 6 (Gen-Eval)
"6": "E",
"e": "E",
"generator": "E",
"gen-eval": "E",
# Task 7 (RE-Val)
"7": "F",
"f": "F",
"real_estate": "F",
"re-val": "F",
}
def _evaluate_tsf(
predictions: np.ndarray,
targets: np.ndarray,
) -> dict[str, Any]:
"""Compute TSF metrics: MSE, RMSE, MAE, Directional Accuracy.
Parameters
----------
predictions : np.ndarray
Shape ``(N, horizon)`` or ``(N,)`` — predicted values.
targets : np.ndarray
Shape ``(N, horizon)`` or ``(N,)`` — ground-truth values.
"""
predictions = np.asarray(predictions, dtype=np.float64)
targets = np.asarray(targets, dtype=np.float64)
if predictions.shape != targets.shape:
raise ValueError(
f"Shape mismatch: predictions {predictions.shape} "
f"vs targets {targets.shape}"
)
mse = float(np.mean((predictions - targets) ** 2))
rmse = float(np.sqrt(mse))
mae = float(np.mean(np.abs(predictions - targets)))
# Directional accuracy: compare sign of consecutive differences
if predictions.ndim == 2 and predictions.shape[1] > 1:
pred_diff = np.diff(predictions, axis=1)
target_diff = np.diff(targets, axis=1)
da = float(np.mean(np.sign(pred_diff) == np.sign(target_diff)))
elif predictions.ndim == 1 and len(predictions) > 1:
pred_diff = np.diff(predictions)
target_diff = np.diff(targets)
da = float(np.mean(np.sign(pred_diff) == np.sign(target_diff)))
else:
da = 0.0
return {
"mse": round(mse, 6),
"rmse": round(rmse, 6),
"mae": round(mae, 6),
"directional_accuracy": round(da, 4),
"n_instances": int(predictions.shape[0]),
}
def evaluate(
task: str,
predictions: pd.DataFrame | np.ndarray | None = None,
targets: np.ndarray | None = None,
ground_truth: pd.DataFrame | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""Evaluate predictions on a MacroLens task.
Parameters
----------
task : str
Task identifier: ``"tsf"``, ``"A"``, ``"B"``, or ``"C"``.
predictions : DataFrame or ndarray
Model predictions. Format depends on the task (see below).
targets : ndarray, optional
Ground-truth values for TSF (shape matches ``predictions``).
ground_truth : DataFrame, optional
Ground-truth DataFrame for Tasks A, B, C.
**kwargs
Additional arguments passed to the underlying evaluator.
Returns
-------
dict
Task-specific metrics dictionary.
Examples
--------
**TSF** — pass parallel arrays of predictions and targets::
results = macrolens.evaluate("tsf", predictions=preds, targets=targets)
# preds, targets: np.ndarray of shape (N, horizon)
**Task 2 (Val-PT)** — pass DataFrames::
results = macrolens.evaluate(
"A",
predictions=pred_df, # cols: ticker, date, predicted_equity_value
ground_truth=gt_df, # cols: ticker, date, actual_market_cap
)
**Task 3 (Stmt-Gen)** — pass DataFrames::
results = macrolens.evaluate(
"B",
predictions=pred_df, # cols: ticker, field, value
ground_truth=gt_df, # cols: ticker, field, value
)
**Task 4 (Scen-Ret)** — pass DataFrames::
results = macrolens.evaluate(
"C",
predictions=pred_df, # cols: scenario_id, ticker, predicted_return_pct
ground_truth=gt_df, # cols: scenario_id, ticker, actual_return_pct
)
"""
canonical = _TASK_ALIASES.get(task.lower(), task.upper())
if canonical == "TSF":
if predictions is None or targets is None:
raise ValueError(
"TSF evaluation requires both `predictions` and `targets` arrays."
)
return _evaluate_tsf(np.asarray(predictions), np.asarray(targets))
if canonical == "A":
if not isinstance(predictions, pd.DataFrame) or ground_truth is None:
raise ValueError(
"Task 2 (Val-PT) requires `predictions` (DataFrame with cols: "
"ticker, date, predicted_equity_value) and "
"`ground_truth` (DataFrame with cols: ticker, date, actual_market_cap)."
)
_validate_columns(predictions, ["ticker", "date", "predicted_equity_value"], "predictions")
return evaluate_valuation(predictions, ground_truth, **kwargs)
if canonical == "B":
if not isinstance(predictions, pd.DataFrame) or ground_truth is None:
raise ValueError(
"Task 3 (Stmt-Gen) requires `predictions` (DataFrame with cols: "
"ticker, field, value) and `ground_truth` (same format)."
)
_validate_columns(predictions, ["ticker", "field", "value"], "predictions")
return evaluate_generation(predictions, ground_truth, **kwargs)
if canonical == "C":
if not isinstance(predictions, pd.DataFrame) or ground_truth is None:
raise ValueError(
"Task 4 (Scen-Ret) requires `predictions` (DataFrame with cols: "
"scenario_id, ticker, predicted_return_pct) and "
"`ground_truth` (DataFrame with cols: scenario_id, ticker, actual_return_pct)."
)
_validate_columns(
predictions, ["scenario_id", "ticker", "predicted_return_pct"], "predictions"
)
return evaluate_scenario_forecast(predictions, ground_truth, **kwargs)
if canonical == "D":
# Task D (Priv-Val) uses the same evaluation as Task A
if not isinstance(predictions, pd.DataFrame) or ground_truth is None:
raise ValueError(
"Task 5 (Priv-Val) requires `predictions` (DataFrame with cols: "
"ticker, date, predicted_equity_value) and "
"`ground_truth` (DataFrame with cols: ticker, date, actual_market_cap)."
)
_validate_columns(predictions, ["ticker", "date", "predicted_equity_value"], "predictions")
return evaluate_valuation(predictions, ground_truth, **kwargs)
if canonical == "E":
# Task E (Gen-Eval) uses the same evaluation as Task B (per-field MAPE)
if not isinstance(predictions, pd.DataFrame) or ground_truth is None:
raise ValueError(
"Task 6 (Gen-Eval) requires `predictions` (DataFrame with cols: "
"ticker, field, value) and `ground_truth` (same format). "
"Use 'generator_field' as the field column name."
)
# Normalise: Gen-Eval GT uses 'generator_field' instead of 'field'
gt = ground_truth.copy()
if "generator_field" in gt.columns and "field" not in gt.columns:
gt = gt.rename(columns={"generator_field": "field"})
preds = predictions.copy()
if "generator_field" in preds.columns and "field" not in preds.columns:
preds = preds.rename(columns={"generator_field": "field"})
_validate_columns(preds, ["ticker", "field", "value"], "predictions")
return evaluate_generation(preds, gt, **kwargs)
if canonical == "F":
# Task F (RE-Val) uses evaluate_re_valuation
if not isinstance(predictions, pd.DataFrame) or ground_truth is None:
raise ValueError(
"Task 7 (RE-Val) requires `predictions` (DataFrame with rent/price "
"predictions) and `ground_truth` (DataFrame with actual rent/price)."
)
return evaluate_re_valuation(predictions, ground_truth, **kwargs)
raise ValueError(
f"Unknown task '{task}'. Valid: 'tsf', 'A', 'B', 'C', 'D', 'E', 'F' "
"(or aliases like 'valuation', 'private_valuation', 'real_estate', etc.)"
)
def _validate_columns(df: pd.DataFrame, required: list[str], name: str) -> None:
"""Raise ValueError if required columns are missing."""
missing = [c for c in required if c not in df.columns]
if missing:
raise ValueError(
f"{name} DataFrame is missing columns: {missing}. "
f"Expected: {required}. Got: {df.columns.tolist()}"
)
def format_submission(
results: dict[str, Any],
task: str = "tsf",
method_name: str | None = None,
granularity: str = "daily",
output_path: str | Path | None = None,
) -> dict[str, Any]:
"""Format evaluation results as a benchmark submission.
Parameters
----------
results : dict
Metrics dictionary returned by :func:`evaluate`.
task : str
Task identifier.
method_name : str, optional
Name of the method/model.
granularity : str
Data granularity used.
output_path : str or Path, optional
If provided, write the submission JSON to this path.
Returns
-------
dict
Formatted submission dictionary.
Example
-------
>>> sub = macrolens.format_submission(results, task="tsf", method_name="MyModel")
>>> sub["benchmark"]
'MacroLens'
"""
submission = {
"benchmark": BENCHMARK_NAME,
"version": BENCHMARK_VERSION,
"task": _TASK_ALIASES.get(task.lower(), task.upper()),
"granularity": granularity,
"method": method_name or "unnamed",
"results": results,
"timestamp": datetime.now(timezone.utc).isoformat(),
}
if output_path is not None:
Path(output_path).write_text(json.dumps(submission, indent=2, default=str))
return submission
|