File size: 3,529 Bytes
354fea5 | 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 | """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"},
)) |