MacroLens / code /macrolens /_evaluate.py
itouchz's picture
Duplicate from macrolens/MacroLens
ff4becd
Raw
History Blame Contribute Delete
10.5 kB
"""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