Skip to content

Reports

Performance reports for a BacktestResult, built on quantstats.

Warning

full_report() and the comparison reports write HTML and open a browser by default.

cjtrade.pkgs.analytics.evaluation.quantstats

pkgs/analytics/evaluation/quantstats.py ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Thin facade around BacktestResult → quantstats.

Usage (as the CJTrade app and the oneshot backtester do):
from cjtrade.pkgs.analytics.evaluation.quantstats import BacktestReport

report = BacktestReport(result)
report.summary()           # print key stats to stdout
report.full_report()       # open quantstats HTML report
report.save_html("out.html")
report.save_csv("out.csv")

BacktestReport(result)

Wraps a BacktestResult and exposes reporting helpers.

Parameters:

Name Type Description Default
result BacktestResult

Backtest output to report on.

required

Examples:

>>> report = BacktestReport(result)
>>> report.summary()
>>> report.save_html("report.html")
Source code in src/cjtrade/pkgs/analytics/evaluation/quantstats.py
90
91
92
def __init__(self, result: "BacktestResult") -> None:
    self.result = result
    self._returns = None   # lazy

returns property

Daily returns pd.Series (cached).

summary()

Print key performance metrics to stdout (no external deps).

Source code in src/cjtrade/pkgs/analytics/evaluation/quantstats.py
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
def summary(self) -> None:
    """Print key performance metrics to stdout (no external deps)."""
    r = self.result
    # PnL now includes both realized (balance change) and unrealized (position value)
    final_equity = r.final_equity if r.final_equity is not None else r.final_balance
    pnl = final_equity - r.initial_balance
    pnl_pct = pnl / r.initial_balance * 100 if r.initial_balance else 0.0

    # uPnL = unrealized PnL = position value
    unrealized_pnl = final_equity - r.final_balance
    unrealized_pnl_pct = unrealized_pnl / r.initial_balance * 100 if r.initial_balance else 0.0

    # rPnL = realized PnL = balance change only
    realized_pnl = r.final_balance - r.initial_balance

    out.info("=" * 50)
    out.info("  Backtest Summary")
    out.info("=" * 50)
    out.info(f"  Session      : {r.session_id or 'N/A'}")
    out.info(f"  Start time   : {r.start_time or 'N/A'}")
    out.info(f"  Init balance : {r.initial_balance:>15,.2f}")
    out.info(f"  Final balance: {r.final_balance:>15,.2f}")
    out.info(f"  Final equity : {final_equity:>15,.2f}")
    out.info(f"  PnL (Total)  : {pnl:>+15,.2f}  ({pnl_pct:+.2f}%)")
    out.info(f"  rPnL         : {realized_pnl:>+15,.2f}")
    out.info(f"  uPnL         : {unrealized_pnl:>+15,.2f}  ({unrealized_pnl_pct:+.2f}%)")
    out.info(f"  Total fills  : {len(r.fill_history)}")
    total_commission = sum(f.get("commission", 0.0) for f in r.fill_history)
    total_tax        = sum(f.get("tax", 0.0)        for f in r.fill_history)
    total_slippage   = sum(f.get("slippage_cost", 0.0) for f in r.fill_history)
    total_cost       = total_commission + total_tax + total_slippage
    if total_cost > 0:
        out.info(f"  Commission   : {total_commission:>15,.2f}")
        out.info(f"  Tax (證交稅)  : {total_tax:>15,.2f}")
        if total_slippage > 0:
            out.info(f"  Slippage     : {total_slippage:>15,.2f}")
        out.info(f"  Total cost   : {total_cost:>15,.2f}")
    out.info(f"  Equity pts   : {len(r.equity_curve)}")

    if not self.returns.empty:
        try:
            qs = self._require_qs()
            p = self.result._returns_periods_per_year
            sharpe = qs.stats.sharpe(self.returns, periods=p)
            # quantstats.stats.cagr() accepts 'periods' for annualisation in some versions
            # prefer 'periods' to remain compatible across quantstats versions
            cagr   = qs.stats.cagr(self.returns, periods=p)
            mdd    = qs.stats.max_drawdown(self.returns)
            label  = "minute" if p > 252 else "daily"
            out.info(f"  Sharpe ratio : {sharpe:.4f}  ({label} resolution, annualised)")
            out.info(f"  CAGR         : {cagr*100:.2f}%")
            out.info(f"  Max drawdown : {mdd*100:.2f}%")
        except ImportError:
            pass   # quantstats optional; basic stats already printed

    # Round-trip analysis (summary only; full table via print_round_trips())
    try:
        rts = self.result.compute_round_trips()
        if rts:
            wins   = [rt for rt in rts if rt.pnl > 0]
            losses = [rt for rt in rts if rt.pnl <= 0]
            avg_pnl  = sum(rt.pnl for rt in rts) / len(rts)
            avg_hold = sum(rt.holding_days for rt in rts) / len(rts)
            win_rate = len(wins) / len(rts) * 100
            out.info(f"  Round trips  : {len(rts)}  (win {len(wins)} / loss {len(losses)},  win rate {win_rate:.1f}%)")
            out.info(f"  Avg PnL/trip : {avg_pnl:>+,.2f}")
            out.info(f"  Avg hold days: {avg_hold:.1f}")
    except Exception:
        pass

    out.info("=" * 50)

print_round_trips()

Print every round-trip (entry→exit) in a compact table.

Uses the same FIFO matching as BacktestResult.compute_round_trips(). Format mirrors the full-simulation trade history for easy comparison.

Source code in src/cjtrade/pkgs/analytics/evaluation/quantstats.py
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
def print_round_trips(self) -> None:
    """Print every round-trip (entry→exit) in a compact table.

    Uses the same FIFO matching as BacktestResult.compute_round_trips().
    Format mirrors the full-simulation trade history for easy comparison.
    """
    try:
        rts = self.result.compute_round_trips()
    except Exception as e:
        log.warning("round-trip computation failed: %s", e)
        return

    if not rts:
        out.info("  No round trips found.")
        return

    wins   = [rt for rt in rts if rt.pnl > 0]
    losses = [rt for rt in rts if rt.pnl <= 0]
    total_pnl = sum(rt.pnl for rt in rts)

    out.info("")
    out.info("=" * 80)
    out.info(f"  Round-Trip History  ({len(rts)} trades,  "
          f"win {len(wins)} / loss {len(losses)},  "
          f"total PnL {total_pnl:+,.2f})")
    out.info("=" * 80)
    out.info(f"  {'#':>3}  {'Symbol':<8}  {'Entry Date':<12}  {'Entry $':>9}  "
          f"{'Exit Date':<12}  {'Exit $':>9}  {'Qty':>6}  {'PnL':>10}  {'Days':>5}")
    out.info("  " + "-" * 76)
    for i, rt in enumerate(rts, 1):
        icon = "🟢" if rt.pnl > 0 else "🔴"
        entry_date = rt.entry_time[:10] if rt.entry_time else "?"
        exit_date  = rt.exit_time[:10]  if rt.exit_time  else "?"
        out.info(f"  {i:>3}  {rt.symbol:<8}  {entry_date:<12}  {rt.entry_price:>9.2f}  "
              f"{exit_date:<12}  {rt.exit_price:>9.2f}  {rt.quantity:>6}  "
              f"{rt.pnl:>+10.2f}  {rt.holding_days:>4}d  {icon}")
    out.info("=" * 80)
    out.info("")

metrics()

Return key metrics as a plain dict (suitable for logging/JSON).

Source code in src/cjtrade/pkgs/analytics/evaluation/quantstats.py
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
def metrics(self) -> dict:
    """Return key metrics as a plain dict (suitable for logging/JSON)."""
    r = self.result
    final_equity = r.final_equity if r.final_equity is not None else r.final_balance
    pnl = final_equity - r.initial_balance
    unrealized_pnl = final_equity - r.final_balance
    realized_pnl = r.final_balance - r.initial_balance

    base = {
        "session_id":      r.session_id,
        "initial_balance": r.initial_balance,
        "final_balance":   r.final_balance,
        "final_equity":    round(final_equity, 2),
        "pnl":             round(pnl, 2),
        "pnl_pct":         round(pnl / r.initial_balance * 100, 4) if r.initial_balance else 0.0,
        "realized_pnl":    round(realized_pnl, 2),
        "unrealized_pnl":  round(unrealized_pnl, 2),
        "n_fills":         len(r.fill_history),
        "n_equity_pts":    len(r.equity_curve),
    }
    if not self.returns.empty:
        try:
            qs = self._require_qs()
            p = r._returns_periods_per_year
            base["sharpe"]       = round(float(qs.stats.sharpe(self.returns, periods=p)), 4)
            base["cagr"]         = round(float(qs.stats.cagr(self.returns, periods=p)), 4)
            base["max_drawdown"] = round(float(qs.stats.max_drawdown(self.returns)), 4)
        except ImportError:
            pass
    return base

full_report(path=None, open_browser=True, title=None)

Save a full quantstats HTML tearsheet and optionally open it in the browser.

Parameters:

Name Type Description Default
path str

Output HTML file path. Defaults to backtest_<session>.html.

None
open_browser bool

If True (default), open the saved file in the default browser.

True
title str

Custom title to display at the top of the HTML report (e.g., strategy name). If None, defaults to "Strategy Tearsheet".

None

Returns:

Type Description
str

Absolute path to the saved HTML file.

Raises:

Type Description
ImportError

If quantstats is not installed.

ValueError

If the equity curve is empty.

Warnings

Writes (overwrites) an HTML file and, by default, opens a browser. With no fills, a minimal "no trades" page is written instead.

Source code in src/cjtrade/pkgs/analytics/evaluation/quantstats.py
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
def full_report(self, path: str = None, open_browser: bool = True, title: str = None) -> str:
    """Save a full quantstats HTML tearsheet and optionally open it in the browser.

    Parameters
    ----------
    path : str, optional
        Output HTML file path.  Defaults to ``backtest_<session>.html``.
    open_browser : bool
        If True (default), open the saved file in the default browser.
    title : str, optional
        Custom title to display at the top of the HTML report (e.g., strategy name).
        If None, defaults to "Strategy Tearsheet".

    Returns
    -------
    str
        Absolute path to the saved HTML file.

    Raises
    ------
    ImportError
        If quantstats is not installed.
    ValueError
        If the equity curve is empty.

    Warnings
    --------
    Writes (overwrites) an HTML file and, by default, opens a browser. With no
    fills, a minimal "no trades" page is written instead.
    """
    import os, webbrowser
    qs = self._require_qs()
    self._require_nonempty()
    if path is None:
        sid = (self.result.session_id or "result")[:8]
        path = f"backtest_{sid}.html"

    # No fills → quantstats would operate on a flat returns series and emit
    # a flood of numpy divide-by-zero / empty-slice warnings.  Write a
    # minimal "no trades" HTML instead.
    if not self.result.fill_history:
        _write_no_trades_html(path, title or "Strategy Tearsheet", self.result)
        abs_path = os.path.abspath(path)
        out.info(f"HTML saved -> {abs_path}  (no trades executed)")
        if open_browser:
            webbrowser.open(f"file://{abs_path}")
        return abs_path

    # Use provided title or default
    report_title = title or "Strategy Tearsheet"

    qs.reports.html(
        self.returns,
        output=path,
        periods_per_year=self.result._returns_periods_per_year,
        title=report_title,
    )

    # Inject round-trip table after quantstats saves the HTML
    self._inject_round_trips_html(path)

    abs_path = os.path.abspath(path)
    out.info(f"HTML saved -> {abs_path}")
    if open_browser:
        webbrowser.open(f"file://{abs_path}")
    return abs_path

basic_report()

Print a compact quantstats report to stdout.

Source code in src/cjtrade/pkgs/analytics/evaluation/quantstats.py
336
337
338
339
340
def basic_report(self) -> None:
    """Print a compact quantstats report to stdout."""
    qs = self._require_qs()
    self._require_nonempty()
    qs.reports.basic(self.returns)

save_html(path)

Save a full quantstats HTML report to path.

Warnings

Writes (overwrites) path; does not open a browser.

Source code in src/cjtrade/pkgs/analytics/evaluation/quantstats.py
421
422
423
424
425
426
427
428
def save_html(self, path: str) -> None:
    """Save a full quantstats HTML report to ``path``.

    Warnings
    --------
    Writes (overwrites) `path`; does not open a browser.
    """
    return self.full_report(path=path, open_browser=False)

save_csv(path)

Save daily_summary() as a CSV to path.

Warnings

Writes (overwrites) path.

Source code in src/cjtrade/pkgs/analytics/evaluation/quantstats.py
430
431
432
433
434
435
436
437
438
439
def save_csv(self, path: str) -> None:
    """Save daily_summary() as a CSV to ``path``.

    Warnings
    --------
    Writes (overwrites) `path`.
    """
    df = self.result.daily_summary()
    df.to_csv(path, index=False)
    out.info(f"CSV saved -> {path}")

quick_report(result, output='html', path=None)

Generate a quantstats report from a BacktestResult in one call.

Parameters:

Name Type Description Default
result BacktestResult

Backtest output to report on.

required
output 'html' | 'full' | 'basic'

"html" → save HTML file (requires path) "full" → open full quantstats report in browser "basic" → print key metrics to stdout only

'html'
path str

File path for HTML output (used when output="html"). Defaults to backtest_<session>.html.

None
Warnings

"html" and "full" write an HTML file in the working directory unless path is given; "full" also opens it in the default browser.

Source code in src/cjtrade/pkgs/analytics/evaluation/quantstats.py
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
def quick_report(result: "BacktestResult", output: str = "html",
                 path: Optional[str] = None) -> None:
    """Generate a quantstats report from a BacktestResult in one call.

    Parameters
    ----------
    result : BacktestResult
        Backtest output to report on.
    output : "html" | "full" | "basic"
        "html"  → save HTML file (requires ``path``)
        "full"  → open full quantstats report in browser
        "basic" → print key metrics to stdout only
    path : str, optional
        File path for HTML output (used when output="html"). Defaults to
        ``backtest_<session>.html``.

    Warnings
    --------
    "html" and "full" write an HTML file in the working directory unless
    `path` is given; "full" also opens it in the default browser.
    """
    report = BacktestReport(result)
    if output == "html":
        report.save_html(path or f"backtest_{result.session_id[:8] if result.session_id else 'result'}.html")
    elif output == "full":
        report.full_report()
    else:
        report.summary()

cjtrade.pkgs.analytics.evaluation.multi_strategy_report

pkgs/analytics/evaluation/multi_strategy_report.py ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Multi-strategy comparison report generator.

Run multiple strategies on the same kbars and generate side-by-side comparison reports using quantstats.

Usage
from cjtrade.pkgs.analytics.evaluation.multi_strategy_report import MultiStrategyBacktestReport
from cjtrade.pkgs.strategy.dca_monthly import DCA_Monthly
from cjtrade.pkgs.strategy.example_strategy import BollingerStrategy

msr = MultiStrategyBacktestReport(kbars, initial_balance=1_000_000, params={...})
msr.add_strategy("DCA_Monthly", DCA_Monthly())
msr.add_strategy("BollingerBands", BollingerStrategy())
msr.run()
msr.compare_summary()
msr.save_comparison_html("comparison.html")

MultiStrategyBacktestReport(kbars, initial_balance=1000000.0, params=None)

Run multiple strategies on the same kbars and generate side-by-side comparison report.

Attributes:

Name Type Description
kbars list

Pre-fetched list of Kbar objects (time-sorted, all symbols, each tagged).

initial_balance float

Starting cash for each strategy.

params dict

Shared parameters passed to all strategies.

_strategies dict

Map of strategy_name → strategy instance.

_results dict

Map of strategy_name → BacktestResult.

_returns_series dict

Map of strategy_name → returns pd.Series.

Source code in src/cjtrade/pkgs/analytics/evaluation/multi_strategy_report.py
62
63
64
65
66
67
68
69
def __init__(self, kbars: List, initial_balance: float = 1_000_000.0,
             params: Optional[Dict] = None) -> None:
    self.kbars = kbars
    self.initial_balance = initial_balance
    self.params = params or {}
    self._strategies: Dict[str, "BaseStrategy"] = {}
    self._results: Dict[str, "BacktestResult"] = {}
    self._returns_series: Dict[str, pd.Series] = {}

add_strategy(name, strategy)

Register a strategy to be tested.

Parameters:

Name Type Description Default
name str

Display name for this strategy (e.g., "DCA_Monthly", "BollingerBands").

required
strategy BaseStrategy

Strategy instance to run.

required
Source code in src/cjtrade/pkgs/analytics/evaluation/multi_strategy_report.py
71
72
73
74
75
76
77
78
79
80
81
82
def add_strategy(self, name: str, strategy: "BaseStrategy") -> None:
    """Register a strategy to be tested.

    Parameters
    ----------
    name : str
        Display name for this strategy (e.g., "DCA_Monthly", "BollingerBands").
    strategy : BaseStrategy
        Strategy instance to run.
    """
    self._strategies[name] = strategy
    log.info("added strategy %s", name)

run()

Run all registered strategies on the same kbars.

Each strategy gets its own BacktestEngine and a random session id.

Raises:

Type Description
ValueError

If no strategies are registered.

Source code in src/cjtrade/pkgs/analytics/evaluation/multi_strategy_report.py
 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
def run(self) -> None:
    """Run all registered strategies on the same kbars.

    Each strategy gets its own BacktestEngine and a random session id.

    Raises
    ------
    ValueError
        If no strategies are registered.
    """
    from cjtrade.pkgs.analytics.backtest.engine import BacktestEngine
    import uuid

    if not self._strategies:
        raise ValueError("No strategies registered. Use add_strategy() first.")

    log.info("running %d strategies", len(self._strategies))
    for name, strategy in self._strategies.items():
        log.info("running %s", name)
        session_id = str(uuid.uuid4())
        engine = BacktestEngine(
            kbars=self.kbars,
            symbol=None,
            initial_balance=self.initial_balance,
            params=self.params,
            session_id=session_id,
        )
        result = engine.run(strategy)
        self._results[name] = result
        self._returns_series[name] = result.to_returns()
        final_equity = result.final_equity if result.final_equity is not None else result.final_balance
        pnl = final_equity - result.initial_balance
        log.info(
            f"{name} done: {len(result.fill_history)} fills, "
            f"PnL={pnl:+.2f}"
        )

compare_summary()

Print a comparison table of all strategies' key metrics to stdout.

Raises:

Type Description
ValueError

If run has not been called.

ImportError

If quantstats is not installed.

Source code in src/cjtrade/pkgs/analytics/evaluation/multi_strategy_report.py
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
def compare_summary(self) -> None:
    """Print a comparison table of all strategies' key metrics to stdout.

    Raises
    ------
    ValueError
        If `run` has not been called.
    ImportError
        If quantstats is not installed.
    """
    if not self._results:
        raise ValueError("No results to compare. Call run() first.")

    qs = self._require_qs()

    out.info("\n" + "=" * 130)
    out.info("  MULTI-STRATEGY COMPARISON")
    out.info("=" * 130)

    # Header
    header = (
        f"{'Strategy':<20} | "
        f"{'PnL':>15} | "
        f"{'PnL %':>10} | "
        f"{'Sharpe':>10} | "
        f"{'CAGR':>10} | "
        f"{'Max DD':>10} | "
        f"{'Fills':>8} | "
        f"{'Equity Pts':>12}"
    )
    out.info(header)
    out.info("-" * 130)

    for name, result in self._results.items():
        final_equity = result.final_equity if result.final_equity is not None else result.final_balance
        pnl = final_equity - result.initial_balance
        pnl_pct = pnl / result.initial_balance * 100 if result.initial_balance else 0.0
        returns = self._returns_series[name]

        if returns.empty:
            sharpe, cagr, mdd = float('nan'), float('nan'), float('nan')
        else:
            try:
                p = result._returns_periods_per_year
                sharpe = float(qs.stats.sharpe(returns, periods=p))
                cagr = float(qs.stats.cagr(returns, periods=p))
                mdd = float(qs.stats.max_drawdown(returns))
            except Exception as e:
                log.warning("metrics for %s failed: %s", name, e)
                sharpe, cagr, mdd = float('nan'), float('nan'), float('nan')

        row = (
            f"{name:<20} | "
            f"{pnl:>15,.2f} | "
            f"{pnl_pct:>+10.2f} | "
            f"{sharpe:>10.4f} | "
            f"{cagr*100:>+10.2f}% | "
            f"{mdd*100:>+10.2f}% | "
            f"{len(result.fill_history):>8} | "
            f"{len(result.equity_curve):>12}"
        )
        out.info(row)
    out.info("=" * 130 + "\n")

save_comparison_html(path='comparison.html', open_browser=True)

Save a multi-strategy HTML comparison report.

Parameters:

Name Type Description Default
path str

Output HTML file path. Default: "comparison.html"

'comparison.html'
open_browser bool

If True (default), open the saved file in the default browser.

True

Returns:

Type Description
str

Absolute path to the saved HTML file.

Raises:

Type Description
ValueError

If run has not been called.

ImportError

If quantstats is not installed.

Warnings

Writes (overwrites) path and, by default, opens a browser.

Source code in src/cjtrade/pkgs/analytics/evaluation/multi_strategy_report.py
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def save_comparison_html(self, path: str = "comparison.html",
                         open_browser: bool = True) -> str:
    """Save a multi-strategy HTML comparison report.

    Parameters
    ----------
    path : str
        Output HTML file path. Default: "comparison.html"
    open_browser : bool
        If True (default), open the saved file in the default browser.

    Returns
    -------
    str
        Absolute path to the saved HTML file.

    Raises
    ------
    ValueError
        If `run` has not been called.
    ImportError
        If quantstats is not installed.

    Warnings
    --------
    Writes (overwrites) `path` and, by default, opens a browser.
    """
    if not self._results:
        raise ValueError("No results to compare. Call run() first.")

    qs = self._require_qs()

    # Build custom HTML comparison table
    html_parts = [
        "<!DOCTYPE html>",
        "<html>",
        "<head>",
        "  <meta charset='utf-8'>",
        "  <title>Multi-Strategy Comparison</title>",
        "  <style>",
        "    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 30px; background-color: #f5f5f5; }",
        "    .container { max-width: 1400px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }",
        "    h1 { color: #333; text-align: center; margin-bottom: 30px; }",
        "    table { border-collapse: collapse; width: 100%; margin-bottom: 30px; }",
        "    th, td { border: 1px solid #ddd; padding: 14px; text-align: right; }",
        "    th { background-color: #2c3e50; color: white; font-weight: bold; text-align: left; }",
        "    td:first-child { text-align: left; font-weight: bold; color: #2c3e50; }",
        "    tr:nth-child(even) { background-color: #f9f9f9; }",
        "    tr:hover { background-color: #f0f0f0; }",
        "    .positive { color: #27ae60; font-weight: bold; }",
        "    .negative { color: #e74c3c; font-weight: bold; }",
        "    .neutral { color: #34495e; }",
        "    .summary { margin-top: 30px; padding: 15px; background-color: #ecf0f1; border-left: 4px solid #2c3e50; }",
        "    .summary h3 { margin-top: 0; color: #2c3e50; }",
        "  </style>",
        "</head>",
        "<body>",
        "  <div class='container'>",
        "    <h1>📊 Multi-Strategy Comparison Report</h1>",
        "    <table>",
        "      <tr>",
        "        <th>Strategy</th>",
        "        <th>PnL (TWD)</th>",
        "        <th>PnL %</th>",
        "        <th>Sharpe Ratio</th>",
        "        <th>CAGR %</th>",
        "        <th>Max Drawdown %</th>",
        "        <th>Fills</th>",
        "        <th>Equity Points</th>",
        "      </tr>"
    ]

    best_pnl_name = max(self._results.keys(),
                        key=lambda n: self._results[n].final_balance - self._results[n].initial_balance)
    best_sharpe_name = None
    best_sharpe = float('-inf')

    for name, result in self._results.items():
        returns = self._returns_series[name]
        if not returns.empty:
            try:
                p = result._returns_periods_per_year
                sharpe = float(qs.stats.sharpe(returns, periods=p))
                if sharpe > best_sharpe:
                    best_sharpe = sharpe
                    best_sharpe_name = name
            except Exception:
                pass

    for name, result in self._results.items():
        pnl = result.final_balance - result.initial_balance
        pnl_pct = pnl / result.initial_balance * 100 if result.initial_balance else 0.0
        returns = self._returns_series[name]

        if returns.empty:
            sharpe, cagr, mdd = float('nan'), float('nan'), float('nan')
        else:
            try:
                p = result._returns_periods_per_year
                sharpe = float(qs.stats.sharpe(returns, periods=p))
                cagr = float(qs.stats.cagr(returns, periods=p))
                mdd = float(qs.stats.max_drawdown(returns))
            except Exception as e:
                log.warning("metrics for %s failed: %s", name, e)
                sharpe, cagr, mdd = float('nan'), float('nan'), float('nan')

        pnl_class = "positive" if pnl >= 0 else "negative"
        cagr_class = "positive" if cagr >= 0 else "negative"
        mdd_class = "negative" if mdd < 0 else "neutral"
        sharpe_class = "positive" if sharpe > 1.0 else ("neutral" if sharpe > 0 else "negative")

        is_best_pnl = " ⭐" if name == best_pnl_name else ""
        is_best_sharpe = " ⭐" if name == best_sharpe_name else ""

        html_parts.append(
            f"      <tr>"
            f"        <td><strong>{name}{is_best_pnl}</strong></td>"
            f"        <td class='{pnl_class}'>{pnl:>12,.2f}</td>"
            f"        <td class='{pnl_class}'>{pnl_pct:>+9.2f}%</td>"
            f"        <td class='{sharpe_class}'>{sharpe:>13.4f}{is_best_sharpe}</td>"
            f"        <td class='{cagr_class}'>{cagr*100:>+9.2f}%</td>"
            f"        <td class='{mdd_class}'>{mdd*100:>+15.2f}%</td>"
            f"        <td>{len(result.fill_history):>8}</td>"
            f"        <td>{len(result.equity_curve):>15}</td>"
            f"      </tr>"
        )

    html_parts.extend([
        "    </table>",
        "    <div class='summary'>",
        "      <h3>📈 Legend</h3>",
        "      <p>⭐ = Best in that category</p>",
        "      <p><span class='positive'>Green</span> = Positive result</p>",
        "      <p><span class='negative'>Red</span> = Negative result</p>",
        "      <p>Sharpe Ratio > 1.0 is generally considered good.</p>",
        "      <p>CAGR = Compound Annual Growth Rate (annualized return).</p>",
        "    </div>",
        "  </div>",
        "</body>",
        "</html>"
    ])

    html_content = "\n".join(html_parts)
    with open(path, "w", encoding="utf-8") as f:
        f.write(html_content)

    abs_path = os.path.abspath(path)
    out.info(f"HTML saved -> {abs_path}")
    if open_browser:
        webbrowser.open(f"file://{abs_path}")
    return abs_path

compare_returns_overlay(path='compare_returns.html', open_browser=True)

Generate overlaid returns chart using plotly for direct comparison.

Plots daily returns % for each strategy on the same chart so you can directly compare their volatility and drawdowns side-by-side.

Parameters:

Name Type Description Default
path str

Output HTML file path.

'compare_returns.html'
open_browser bool

If True, open the file in the default browser.

True

Returns:

Type Description
str

Absolute path to the saved HTML file.

Raises:

Type Description
ImportError

If plotly is not installed.

ValueError

If run has not been called.

Warnings

Writes (overwrites) path and, by default, opens a browser.

Source code in src/cjtrade/pkgs/analytics/evaluation/multi_strategy_report.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
def compare_returns_overlay(self, path: str = "compare_returns.html",
                             open_browser: bool = True) -> str:
    """Generate overlaid returns chart using plotly for direct comparison.

    Plots daily returns % for each strategy on the same chart so you can
    directly compare their volatility and drawdowns side-by-side.

    Parameters
    ----------
    path : str
        Output HTML file path.
    open_browser : bool
        If True, open the file in the default browser.

    Returns
    -------
    str
        Absolute path to the saved HTML file.

    Raises
    ------
    ImportError
        If plotly is not installed.
    ValueError
        If `run` has not been called.

    Warnings
    --------
    Writes (overwrites) `path` and, by default, opens a browser.
    """
    try:
        import plotly.graph_objects as go
    except ImportError:
        raise ImportError("plotly not installed – run: pip install plotly")

    if not self._results:
        raise ValueError("No results to compare. Call run() first.")

    fig = go.Figure()
    colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]

    for idx, (name, returns_series) in enumerate(self._returns_series.items()):
        if returns_series.empty:
            continue
        color = colors[idx % len(colors)]
        fig.add_trace(go.Scatter(
            x=returns_series.index,
            y=returns_series.values * 100,  # convert to percentage
            mode="lines",
            name=name,
            line=dict(color=color, width=2.5),
            hovertemplate=f"<b>{name}</b><br>Date: %{{x|%Y-%m-%d}}<br>Return: %{{y:.3f}}%<extra></extra>",
        ))

    fig.update_layout(
        title="Daily Returns Comparison",
        xaxis_title="Date",
        yaxis_title="Daily Return (%)",
        hovermode="x unified",
        template="plotly_white",
        height=700,
        legend=dict(x=0.01, y=0.99, bgcolor="rgba(255,255,255,0.8)", bordercolor="black", borderwidth=1),
    )

    fig.write_html(path)
    abs_path = os.path.abspath(path)
    out.info(f"Returns overlay chart saved -> {abs_path}")

    if open_browser:
        webbrowser.open(f"file://{abs_path}")

    return abs_path

compare_cumulative_equity_overlay(path='compare_equity.html', open_browser=True)

Generate overlaid cumulative equity chart using plotly.

Plots the equity curve (in TWD, not normalized) for each strategy on the same chart.

Parameters:

Name Type Description Default
path str

Output HTML file path.

'compare_equity.html'
open_browser bool

If True, open the file in the default browser.

True

Returns:

Type Description
str

Absolute path to the saved HTML file.

Raises:

Type Description
ImportError

If plotly is not installed.

ValueError

If run has not been called.

Warnings

Writes (overwrites) path and, by default, opens a browser.

Source code in src/cjtrade/pkgs/analytics/evaluation/multi_strategy_report.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
def compare_cumulative_equity_overlay(self, path: str = "compare_equity.html",
                                      open_browser: bool = True) -> str:
    """Generate overlaid cumulative equity chart using plotly.

    Plots the equity curve (in TWD, not normalized) for each strategy on the
    same chart.

    Parameters
    ----------
    path : str
        Output HTML file path.
    open_browser : bool
        If True, open the file in the default browser.

    Returns
    -------
    str
        Absolute path to the saved HTML file.

    Raises
    ------
    ImportError
        If plotly is not installed.
    ValueError
        If `run` has not been called.

    Warnings
    --------
    Writes (overwrites) `path` and, by default, opens a browser.
    """
    try:
        import plotly.graph_objects as go
    except ImportError:
        raise ImportError("plotly not installed – run: pip install plotly")

    if not self._results:
        raise ValueError("No results to compare. Call run() first.")

    fig = go.Figure()
    colors = ["#1f77b4", "#ffe100", "#00d500", "#d40000", "#956bbc", "#8c564b"]

    for idx, (name, result) in enumerate(self._results.items()):
        eq_series = result.to_equity_series()
        if eq_series.empty:
            continue
        color = colors[idx % len(colors)]
        fig.add_trace(go.Scatter(
            x=eq_series.index,
            y=eq_series.values,
            mode="lines",
            name=name,
            line=dict(color=color, width=2.5),
            hovertemplate=f"<b>{name}</b><br>Date: %{{x|%Y-%m-%d}}<br>Equity: NT$%{{y:,.0f}}<extra></extra>",
        ))

    fig.update_layout(
        title="Cumulative Equity Comparison",
        xaxis_title="Date",
        yaxis_title="Equity (TWD)",
        hovermode="x unified",
        template="plotly_white",
        height=700,
        legend=dict(x=0.01, y=0.99, bgcolor="rgba(255,255,255,0.8)", bordercolor="black", borderwidth=1),
    )

    fig.write_html(path)
    abs_path = os.path.abspath(path)
    out.info(f"Equity overlay chart saved -> {abs_path}")

    if open_browser:
        webbrowser.open(f"file://{abs_path}")

    return abs_path