Special Relativity in Financial Modeling 1.0.0
Lorentz transforms, spacetime classification, and geodesic price paths for quantitative finance
Loading...
Searching...
No Matches
causal_cone.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file include/srfm/causal_cone.hpp
4/// @brief Causal Cone Filter — light-cone analogue for financial time series.
5///
6/// # Module: Causal Cone Filter
7///
8/// ## Conceptual Basis
9/// In special relativity, an event B is causally influenced by event A only
10/// if A lies within the *past light cone* of B — i.e. the spacetime interval
11/// ds²(A→B) < 0 (TIMELIKE). Events outside the light cone (SPACELIKE) cannot
12/// causally affect B.
13///
14/// This module applies the same logic to financial OHLCV bars:
15///
16/// - A historical bar A is a *causal predecessor* of the current bar B iff
17/// ``ds²(A, B) < 0`` (TIMELIKE or near-LIGHTLIKE) in the embedded
18/// financial spacetime.
19/// - Only causal predecessors contribute to feature computation.
20/// - SPACELIKE bars are excluded as "causally disconnected" noise sources.
21///
22/// ## Hypothesis
23/// Signals computed exclusively from causally-connected bars should exhibit
24/// higher predictive accuracy because they exclude market noise that arrived
25/// at speeds inconsistent with the bar's causal past.
26///
27/// ## Core Types
28/// - ``CausalHistory`` — the causal predecessors of one bar
29/// - ``CausalConeFilter`` — scans a bar sequence and builds causal histories
30/// - ``CausalSignal`` — a feature vector built only from causal predecessors
31/// - ``CausalBacktest`` — compares CausalSignal vs all-bars signal on a dataset
32///
33/// ## Guarantees
34/// - All methods are `noexcept` where no allocation can fail
35/// - No raw pointers; ownership by value or `const&`
36/// - Returns `std::optional` for all fallible operations
37/// - Thread-safe reads: const methods can be called concurrently
38
39#include "srfm/manifold.hpp"
40#include "srfm/backtest.hpp"
41#include "srfm/engine.hpp"
42
43#include <optional>
44#include <span>
45#include <string>
46#include <vector>
47
48namespace srfm::causal {
49
50// ─── CausalHistory ────────────────────────────────────────────────────────────
51
52/// The set of past bars that causally "matter" to a given bar.
53///
54/// A bar is a causal predecessor iff the spacetime interval from that bar to
55/// the current bar is TIMELIKE (ds² < 0). SPACELIKE bars are excluded.
57 /// The current bar (the "effect" event).
59
60 /// Ordered list of causal predecessor events (oldest first).
61 /// Contains only TIMELIKE (ds² < 0) predecessors of ``event``.
62 std::vector<manifold::SpacetimeEvent> causal_predecessors;
63
64 /// Indices into the original bar array for each causal predecessor.
65 std::vector<std::size_t> predecessor_indices;
66
67 /// Number of bars scanned (including SPACELIKE/excluded ones).
68 std::size_t total_bars_scanned{0};
69
70 /// Return the fraction of scanned bars that are causal predecessors.
71 [[nodiscard]] double causal_fraction() const noexcept {
72 if (total_bars_scanned == 0) return 0.0;
73 return static_cast<double>(causal_predecessors.size())
74 / static_cast<double>(total_bars_scanned);
75 }
76};
77
78// ─── CausalSignal ─────────────────────────────────────────────────────────────
79
80/// A trading feature vector computed only from causally-connected bars.
81///
82/// Features:
83/// - causal_mean_return: Mean return of causal predecessor bars.
84/// - causal_vol: Volatility (std dev) of causal predecessor returns.
85/// - causal_momentum: Weighted sum of returns, γ-weighted by causal strength.
86/// - causal_fraction: Fraction of look-back bars that are causal.
87/// - all_bars_mean_return: Same metric computed over ALL bars (for comparison).
89 double causal_mean_return{0.0}; ///< Mean return, causal bars only.
90 double causal_vol{0.0}; ///< Volatility of causal bar returns.
91 double causal_momentum{0.0}; ///< Weighted momentum from causal bars.
92 double causal_fraction{0.0}; ///< Fraction of bars that are causal.
93 double all_bars_mean_return{0.0}; ///< Baseline: mean over ALL look-back bars.
94 std::size_t n_causal{0}; ///< Number of causal predecessor bars used.
95 std::size_t n_total{0}; ///< Total bars in the look-back window.
96};
97
98// ─── CausalConeFilter ─────────────────────────────────────────────────────────
99
100/// Filters a bar sequence to identify causal predecessors for each bar.
101///
102/// For every bar B in the sequence, looks back up to ``look_back`` bars and
103/// classifies each as TIMELIKE (causal) or SPACELIKE (excluded) using
104/// ``SpacetimeInterval::classify``.
105///
106/// Usage:
107/// ```cpp
108/// CausalConeFilter filter(look_back = 20);
109/// auto histories = filter.build_histories(bars);
110/// for (auto& h : histories) {
111/// auto sig = filter.compute_signal(h, bars, bar_index);
112/// // use sig.causal_mean_return instead of all-bars mean
113/// }
114/// ```
116public:
117 /// Configuration for the causal cone filter.
118 struct Config {
119 /// Number of past bars to scan for causal predecessors.
120 std::size_t look_back{20};
121
122 /// Speed of information (same as SPEED_OF_INFORMATION in manifold).
124
125 /// If true, include LIGHTLIKE (ds² ≈ 0) bars in the causal set.
127
128 /// If true, emit per-bar diagnostics to stderr.
129 bool verbose{false};
130 };
131
132 /// Construct with an optional configuration.
133 explicit CausalConeFilter(Config config = Config{}) noexcept;
134
135 /// Build a CausalHistory for every bar in the sequence.
136 ///
137 /// The first ``look_back`` bars will have fewer predecessors as the
138 /// rolling window fills up.
139 ///
140 /// @param bars Sequence of OHLCV bars (must be pre-converted to events).
141 /// @param events Corresponding spacetime events for each bar.
142 /// @returns One CausalHistory per bar (same size as ``bars``).
143 [[nodiscard]] std::vector<CausalHistory>
145 std::span<const core::OHLCV> bars,
146 std::span<const manifold::SpacetimeEvent> events
147 ) const noexcept;
148
149 /// Compute a CausalSignal for bar at index ``bar_idx``.
150 ///
151 /// @param history The CausalHistory for this bar.
152 /// @param returns Close-to-close returns for the full bar sequence.
153 /// @param bar_idx Index of the current bar in ``returns``.
154 /// @returns CausalSignal or nullopt if history has no causal predecessors.
155 [[nodiscard]] std::optional<CausalSignal>
157 const CausalHistory& history,
158 std::span<const double> returns,
159 std::size_t bar_idx
160 ) const noexcept;
161
162 /// Return the configured look_back window.
163 [[nodiscard]] std::size_t look_back() const noexcept { return config_.look_back; }
164
165private:
166 Config config_;
167
168 /// True if the interval type should be included in the causal set.
169 [[nodiscard]] bool is_causal(manifold::IntervalType t) const noexcept;
170};
171
172// ─── CausalBacktestResult ─────────────────────────────────────────────────────
173
174/// Comparison of CausalSignal-based strategy vs all-bars baseline strategy.
176 /// Performance of the causal-only signal strategy.
178
179 /// Performance of the all-bars baseline strategy.
181
182 /// Mean fraction of bars that were causal across the full dataset.
184
185 /// Improvement in Sharpe ratio: causal − baseline.
186 [[nodiscard]] double sharpe_improvement() const noexcept {
188 }
189
190 /// Improvement in Sortino ratio: causal − baseline.
191 [[nodiscard]] double sortino_improvement() const noexcept {
193 }
194
195 /// Format a one-line human-readable summary.
196 [[nodiscard]] std::string to_string() const;
197};
198
199// ─── CausalBacktest ───────────────────────────────────────────────────────────
200
201/// Runs a backtest comparison: CausalSignal strategy vs all-bars baseline.
202///
203/// Usage:
204/// ```cpp
205/// CausalBacktest cb;
206/// auto result = cb.run(bars);
207/// if (result) fmt::print("{}\n", result->to_string());
208/// ```
210public:
211 /// Construct with optional filter and engine configs.
212 explicit CausalBacktest(
215 ) noexcept;
216
217 /// Run the full comparison backtest on a sequence of OHLCV bars.
218 ///
219 /// Pipeline:
220 /// 1. Convert bars to spacetime events via the Engine.
221 /// 2. Build CausalHistory for every bar.
222 /// 3. Compute CausalSignal for every bar.
223 /// 4. Evaluate both strategies via the Backtester.
224 ///
225 /// @param bars Input OHLCV sequence (minimum look_back + 30 bars).
226 /// @returns CausalBacktestResult or nullopt on insufficient data.
227 [[nodiscard]] std::optional<CausalBacktestResult>
228 run(std::span<const core::OHLCV> bars) const noexcept;
229
230private:
231 CausalConeFilter filter_;
232 core::Engine engine_;
233};
234
235} // namespace srfm::causal
Relativistic Backtester — AGT-05 public API.
std::optional< CausalBacktestResult > run(std::span< const core::OHLCV > bars) const noexcept
std::size_t look_back() const noexcept
Return the configured look_back window.
std::vector< CausalHistory > build_histories(std::span< const core::OHLCV > bars, std::span< const manifold::SpacetimeEvent > events) const noexcept
std::optional< CausalSignal > compute_signal(const CausalHistory &history, std::span< const double > returns, std::size_t bar_idx) const noexcept
Orchestrates the full relativistic signal-processing pipeline.
Definition engine.hpp:88
Core Integration Engine — AGT-06 public API.
Spacetime Market Manifold — AGT-02 public API (implemented by AGT-06).
static constexpr double SPEED_OF_INFORMATION
Definition constants.hpp:37
IntervalType
Causal character of a spacetime interval.
Definition manifold.hpp:61
Performance metrics for a single strategy evaluation.
Definition backtest.hpp:76
double sortino_ratio
(mean_ret − r_f) / σ_down, annualised
Definition backtest.hpp:78
double sharpe_ratio
(mean_ret − r_f) / σ, annualised
Definition backtest.hpp:77
Comparison of CausalSignal-based strategy vs all-bars baseline strategy.
backtest::PerformanceMetrics baseline_metrics
Performance of the all-bars baseline strategy.
double sharpe_improvement() const noexcept
Improvement in Sharpe ratio: causal − baseline.
double mean_causal_fraction
Mean fraction of bars that were causal across the full dataset.
double sortino_improvement() const noexcept
Improvement in Sortino ratio: causal − baseline.
backtest::PerformanceMetrics causal_metrics
Performance of the causal-only signal strategy.
std::string to_string() const
Format a one-line human-readable summary.
Configuration for the causal cone filter.
bool verbose
If true, emit per-bar diagnostics to stderr.
std::size_t look_back
Number of past bars to scan for causal predecessors.
bool include_lightlike
If true, include LIGHTLIKE (ds² ≈ 0) bars in the causal set.
double c_market
Speed of information (same as SPEED_OF_INFORMATION in manifold).
double causal_fraction() const noexcept
Return the fraction of scanned bars that are causal predecessors.
std::vector< std::size_t > predecessor_indices
Indices into the original bar array for each causal predecessor.
std::size_t total_bars_scanned
Number of bars scanned (including SPACELIKE/excluded ones).
manifold::SpacetimeEvent event
The current bar (the "effect" event).
std::vector< manifold::SpacetimeEvent > causal_predecessors
std::size_t n_causal
Number of causal predecessor bars used.
std::size_t n_total
Total bars in the look-back window.
double causal_fraction
Fraction of bars that are causal.
double causal_mean_return
Mean return, causal bars only.
double causal_momentum
Weighted momentum from causal bars.
double causal_vol
Volatility of causal bar returns.
double all_bars_mean_return
Baseline: mean over ALL look-back bars.
Configuration parameters for the core engine.
Definition engine.hpp:56
A point in 4D spacetime (t, x, y, z).