Spaces:
Running
Running
Download modules/backtest/models.py from Arrechenash/stocks: direct link, hf CLI and curl.
- Browser
- Download file 7.9 kB
-
https://huggingface.co/spaces/Arrechenash/stocks/resolve/main/modules/backtest/models.py
- Command line
-
hf download hf://spaces/Arrechenash/stocks/modules/backtest/models.py
-
curl -L -o models.py https://huggingface.co/spaces/Arrechenash/stocks/resolve/main/modules/backtest/models.py
7.9 kB
| """Backtest run configuration and progress state.""" | |
| from dataclasses import dataclass, field | |
| from typing import Any | |
| from pydantic import BaseModel | |
| from core.detectors.alert_elements import DetectorGroup | |
| SUPPORTED_DETECTORS = { | |
| "trend_reversal", | |
| "crossing_vwap", | |
| "dsl_expression", | |
| "volume_spike", | |
| "crossing_ema", | |
| "breakout", | |
| "reject_level", | |
| "opening_range", | |
| "session_extremes", | |
| "vwap_bounce", | |
| } | |
| class BacktestConfig: | |
| date: str # "YYYY-MM-DD" | |
| from_time: str # "HH:MM" | |
| to_time: str # "HH:MM" | |
| timeframe: str = "15M" # bar timeframe token: 1M/5M/15M/30M/1H/4H/1D | |
| # Optional now: a run needs symbols and/or candidate_filter (below), not | |
| # necessarily both -- see BacktestService.start's validation. | |
| symbols: list[str] = field(default_factory=list) | |
| # Optional daily DSL filter (core.dsl), evaluated against the same | |
| # full-market daily dataset modules/scan/service.py scans (DataManager. | |
| # get_candidates), for `date` only -- selects which symbols this run | |
| # fetches intraday data for (BacktestService._resolve_candidate_symbols). | |
| # Mirrors ChartsWatcher's backtest, where "Restrict to symbols" is an | |
| # OPTIONAL/ADDITIONAL narrowing on top of the alert/filter config rather | |
| # than a replacement for it: when both `candidate_filter` and `symbols` | |
| # are given, the filter selects the day's matching universe and | |
| # `symbols` intersects it further, instead of one silently overriding | |
| # the other. Daily-only: pipeline (`|>`) stages are rejected, since Phase | |
| # 1 (this filter) runs before any intraday data has been fetched. | |
| candidate_filter: str | None = None | |
| # One-or-more detector types, OR'd: a bar reports a signal if ANY of | |
| # these detectors fires on it. Kept as a list (not a single string) so | |
| # a saved AlertConfig can combine detectors without a new "combo" | |
| # detector type. | |
| detector_types: list[str] = field(default_factory=lambda: ["trend_reversal"]) | |
| # Optional filing filter that restricts backtest to symbols with SEC filings | |
| # matching this expression, e.g. for bankruptcy notifications or other | |
| # SEC event types observed in the notification feed. | |
| filings_filter: str | None = None | |
| # Ad-hoc/resolved DSL boolean expression (core.dsl), evaluated per-bar | |
| # against that bar's own fields (see service._symbol_passes_filter). | |
| filter_expression: str | None = None | |
| # Legacy single DSL expression for the "dsl_expression" detector type -- | |
| # kept for backward compat with configs saved before detector_expressions | |
| # (below) existed. Only used when detector_expressions is empty. | |
| detector_expression: str | None = None | |
| # One-or-more simultaneous DSL-template alert expressions (e.g. several | |
| # candle patterns OR'd together), each run as its OWN DslExpressionDetector | |
| # instance so SignalEvent.reason keeps its per-template identity instead | |
| # of conflating which sub-pattern fired (design decision: one detector instance per DSL template, not one | |
| # detector evaluating an OR of all templates). "dsl_expression" must be | |
| # present in detector_types for these to run. | |
| detector_expressions: list[str] = field(default_factory=list) | |
| # One entry per selected stateful-detector alert element (volume_spike/ | |
| # crossing_ema/breakout/reject_level/opening_range/session_extremes/ | |
| # vwap_bounce), e.g. [("crossing_ema", {"period": 9, "direction": "above"}), | |
| # ("crossing_ema", {"period": 9, "direction": "below"})]. A flat list, not | |
| # a dict keyed by detector_type: two elements of the same type (both | |
| # crossing directions, or volume_spike's 10x/2x presets) are two | |
| # independent entries here, so there is no shared mutable structure for | |
| # one selection to silently overwrite another's config (findings #1 and | |
| # #2 were both exactly that collision, on the dict-keyed shape this | |
| # replaces). Missing param keys fall back to each detector's | |
| # dataclass defaults. | |
| detector_instances: list[tuple[str, dict[str, Any]]] = field(default_factory=list) | |
| # The resolved form of a saved AlertConfig's condition tree, when the run | |
| # came from one. Each group is an AND/OR over its own leaves, which is what | |
| # makes "bullish engulfing AND volume spike" expressible at all; the flat | |
| # fields above stay as the legacy path and are used unchanged when this is | |
| # empty (a run started without an alert config). | |
| detector_groups: list[DetectorGroup] = field(default_factory=list) | |
| class BacktestProgress: | |
| state: str = "idle" # idle -> running -> paused -> running -> done | stopped | error | |
| processed: int = 0 | |
| total: int = 0 | |
| error: str | None = None | |
| # Non-fatal, e.g. candidate_filter's daily prefilter matched more than | |
| # BacktestService.MAX_CANDIDATE_SYMBOLS and was truncated -- the run | |
| # still proceeds, this is just surfaced to the client. | |
| warning: str | None = None | |
| # When a candidate_filter is used, surface the total match count and the | |
| # MAX_CANDIDATE_SYMBOLS cap so the user knows the limit exists even when | |
| # truncation does not actually occur. | |
| candidate_matched: int | None = None | |
| candidate_limit: int | None = None | |
| config: BacktestConfig | None = field(default=None) | |
| def as_dict(self) -> dict[str, object]: | |
| d: dict[str, object] = { | |
| "state": self.state, | |
| "processed": self.processed, | |
| "total": self.total, | |
| "error": self.error, | |
| "warning": self.warning, | |
| } | |
| if self.candidate_matched is not None: | |
| d["candidate_matched"] = self.candidate_matched | |
| d["candidate_limit"] = self.candidate_limit | |
| return d | |
| class AlertConfigRequest(BaseModel): | |
| name: str | |
| # Optional now: a hand-written DSL alert condition (see | |
| # detector_expression below) implies detector_types == ["dsl_expression"] | |
| # and needs no explicit list. Still accepted for the legacy alert_elements | |
| # path (frontend no longer sends it, but old saved configs still carry | |
| # it -- see validation.validate_alert_config_request). | |
| detector_types: list[str] = [] | |
| filter_name: str | None = None | |
| filter_expression: str | None = None | |
| # A whole hand-written DSL alert condition: a plain core.dsl boolean | |
| # expression, e.g. "close > open and volume > avg(volume, 20) * 2". The | |
| # editor writes a `condition` tree, in which a dsl leaf carries the same | |
| # string, so this field is only read -- a config saved with it, or with a | |
| # bare detector_types list, still resolves to an equivalent tree. | |
| detector_expression: str | None = None | |
| # Legacy structured multi-alert-element selection: a flat OR of catalog | |
| # elements, written by the editor that predated the condition tree -- | |
| # resolved into detector_expressions/detector_instances at save time by | |
| # validate_alert_config_request, and again at /start time from the saved | |
| # row. Kept only so pre-existing saved configs keep working; the editor now | |
| # writes `condition`, whose flat projection is derived server-side. | |
| alert_elements: list[dict[str, Any]] | None = None | |
| # The condition tree -- the alert's actual definition. Present on | |
| # everything the new editor writes; the legacy fields above stay | |
| # optional and are still honored (normalized into an equivalent tree) so | |
| # a config saved by an older build keeps running untouched. | |
| condition: dict[str, Any] | None = None | |
| class AlertPreviewRequest(BaseModel): | |
| """Body of POST /api/backtest/alert-configs/preview: a builder selection | |
| exactly as it would be saved, resolved WITHOUT persisting anything so the | |
| builder can show what will actually run while the user edits.""" | |
| alert_elements: list[dict[str, Any]] = [] | |
| condition: dict[str, Any] | None = None | |