Spaces:
Paused

Rukku / demo_interface /visualization.py
whassan's picture
Upload folder using huggingface_hub
354fea5 verified
Raw History Blame Contribute Delete
3.53 kB
"""Demo visualization interface for backtest results.
Renders comparative line graphs of actual market performance alongside
algorithm predictions.
"""
import os
import json
from dataclasses import dataclass, field
from typing import Optional
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from backtest.reporting.result_header import generate_result_report
from backtest.engine.exceptions import EngineError
from demo_interface.exceptions import (
InvalidResultData,
UnauthorizedMetric,
VisualizationError,
)
@dataclass
class ChartSeries:
"""A single data series for charting."""
label: str
x: list
y: list
color: str
linestyle: str
dtype: str # "actual" | "predicted" | "benchmark"
@dataclass
class ChartConfig:
"""Configuration for a comparison chart."""
title: str
x_label: str
y_label: str
series: list = field(default_factory=list)
include_benchmark: bool = True
include_disclosure: bool = True
def _validate_result_file(path: str) -> dict:
"""Load a result file."""
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
return data
class ValidationError(VisualizationError):
"""Result validation failed."""
def load_result_data(path: str) -> dict:
"""Load a result data file."""
return _validate_result_file(path)
def _extract_series(data: dict, series_type: str) -> ChartSeries:
"""Extract a chart series from result data."""
if series_type not in ("actual", "predicted", "benchmark"):
raise UnauthorizedMetric(
f"Series type not authorized: {series_type}"
)
return ChartSeries(
label=f"{series_type.title()} Data",
x=[1, 2, 3],
y=[10, 20, 30],
color="blue",
linestyle="-",
dtype=series_type
)
def render_comparison_chart(config: ChartConfig, output_path: str) -> None:
"""Render a comparative line chart of market performance.
"""
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
ax1.set_title(config.title)
ax1.set_xlabel(config.x_label)
ax1.set_ylabel(config.y_label)
if config.include_disclosure:
fig.text(
0.5, 0.01,
"WARNING: This result measures the current algorithm's "
"performance on historical data.",
fontsize=8, ha="center",
)
plt.savefig(output_path, dpi=150, bbox_inches="tight")
plt.close(fig)
def generate_performance_report(result_path: str, output_dir: str) -> None:
"""Generate a performance comparison report from a result file."""
try:
_validate_result_file(result_path)
except Exception as e:
print(f"Result validation failed: {e}")
return
os.makedirs(output_dir, exist_ok=True)
report_path = os.path.join(output_dir, "result_report.txt")
with open(report_path, "w", encoding="utf-8") as f:
f.write(generate_result_report(
repo_url="unknown",
commit_sha="unknown",
algorithm_name="unknown",
algorithm_type="unknown",
assets=["QQQ", "SPY", "DIA"],
test_period="unknown",
horizon=0,
frequency="unknown",
training="unknown",
temporal_leakage="unknown",
execution_risk="unknown",
reproducibility={"repository_url": "unknown", "branch": "unknown",
"commit_sha": "unknown", "commit_timestamp": "unknown"},
))