Special Relativity in Financial Modeling 1.0.0
Lorentz transforms, spacetime classification, and geodesic price paths for quantitative finance
Loading...
Searching...
No Matches
hawking.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file include/srfm/hawking.hpp
4/// @brief Hawking Radiation Analogy — event-horizon detection for price series.
5///
6/// # Module: Hawking Radiation Signal
7///
8/// ## Conceptual Basis
9/// Stephen Hawking showed that black holes emit thermal radiation due to
10/// quantum effects near the event horizon. As a black hole loses mass, its
11/// temperature rises — an accelerating approach to its own end state.
12///
13/// In financial markets, an analogous "event horizon" occurs when a price
14/// series approaches an extreme: a 3σ Bollinger Band exceedance. Near this
15/// horizon:
16///
17/// - **Information leaks** from the system: the price can no longer sustain
18/// the extreme trend and must reverse or consolidate.
19/// - **Hawking Temperature** T_H measures how close the price is to the
20/// event horizon, scaled by the rate of approach.
21/// - High T_H → high informational entropy → trend exhaustion / reversal.
22/// - Low T_H → low entropy → trend continuation likely.
23///
24/// ## Hawking Temperature Formula
25///
26/// T_H(t) = |P(t) − μ(t)| / σ(t) × (dP/dt) / σ(t)
27///
28/// where μ and σ are the rolling Bollinger Band mean and standard deviation.
29/// The first factor measures how far into the band we are (proximity to
30/// horizon) and the second measures the velocity of approach.
31///
32/// Equivalently, using z-score:
33///
34/// T_H(t) = z(t) × Δz(t)
35///
36/// where z = (P − μ) / σ and Δz is the bar-to-bar change in z-score.
37///
38/// ## Trading Signal
39/// - T_H > HAWKING_HOT_THRESHOLD → expect reversal (trade against trend)
40/// - T_H < HAWKING_COLD_THRESHOLD → expect continuation (trade with trend)
41/// - Between thresholds → neutral / no position
42///
43/// ## Guarantees
44/// - All public methods are noexcept (return std::optional on failure)
45/// - No dynamic dispatch; all types are concrete
46/// - Thread-safe reads: const methods safe for concurrent access
47
48#include "srfm/backtest.hpp"
49#include "srfm/engine.hpp"
50
51#include <optional>
52#include <span>
53#include <string>
54#include <vector>
55
56namespace srfm::hawking {
57
58// ─── Constants ────────────────────────────────────────────────────────────────
59
60/// Default Bollinger Band window (bars).
61inline constexpr std::size_t DEFAULT_BB_WINDOW = 20;
62
63/// Default Bollinger Band multiplier for outer band (σ-multiple).
64inline constexpr double DEFAULT_BB_SIGMA = 3.0;
65
66/// T_H above this → "hot" → reversal signal.
67inline constexpr double HAWKING_HOT_THRESHOLD = 2.0;
68
69/// T_H below this → "cold" → continuation signal.
70inline constexpr double HAWKING_COLD_THRESHOLD = -2.0;
71
72// ─── HawkingTemperature ───────────────────────────────────────────────────────
73
74/// Per-bar Hawking temperature measurement.
75///
76/// Attributes:
77/// temperature Dimensionless T_H = z × Δz.
78/// z_score Current Bollinger Band z-score: (P − μ) / σ.
79/// delta_z Bar-to-bar change in z-score (velocity of approach).
80/// bollinger_mean Rolling mean μ over the BB window.
81/// bollinger_std Rolling standard deviation σ over the BB window.
82/// near_horizon True iff |z_score| >= bb_sigma (outside the outer band).
84 double temperature{0.0}; ///< T_H = z × Δz
85 double z_score{0.0}; ///< (P − μ) / σ
86 double delta_z{0.0}; ///< Change in z-score from previous bar
87 double bollinger_mean{0.0}; ///< Rolling μ
88 double bollinger_std{0.0}; ///< Rolling σ
89 bool near_horizon{false}; ///< |z_score| ≥ bb_sigma
90
91 /// Format a compact one-liner for logging.
92 [[nodiscard]] std::string to_string() const;
93};
94
95// ─── HawkingSignal ────────────────────────────────────────────────────────────
96
97/// Trading signal derived from Hawking temperature.
98enum class HawkingDirection {
99 Reversal, ///< T_H high → trend exhaustion → fade the move
100 Continuation, ///< T_H low → healthy trend → follow the trend
101 Neutral, ///< Temperature in the normal range → no signal
102};
103
104/// Return a human-readable string for a HawkingDirection value.
105[[nodiscard]] const char* to_string(HawkingDirection d) noexcept;
106
107/// A single bar's Hawking-derived trading signal.
109 HawkingTemperature temperature; ///< Full temperature measurement.
110 HawkingDirection direction; ///< Trading implication.
111 double strength; ///< |T_H| normalized to [0, 1].
112 int action; ///< +1 (buy), -1 (sell), 0 (neutral).
113
114 /// Format a compact one-liner for logging.
115 [[nodiscard]] std::string to_string() const;
116};
117
118// ─── BollingerState ───────────────────────────────────────────────────────────
119
120/// Internal rolling state for Bollinger Band computation.
122 std::vector<double> window; ///< Rolling price window (oldest first).
123 double sum{0.0}; ///< Running sum for fast mean.
124 double sum_sq{0.0}; ///< Running sum of squares for fast σ.
126
127 /// Push a new price and pop the oldest if window is full.
128 void push(double price) noexcept;
129
130 /// Return the rolling mean (NaN-safe).
131 [[nodiscard]] double mean() const noexcept;
132
133 /// Return the rolling standard deviation (population σ).
134 [[nodiscard]] double stddev() const noexcept;
135
136 /// True iff window has reached its maximum size.
137 [[nodiscard]] bool full() const noexcept { return window.size() == max_size; }
138};
139
140// ─── PriceEventHorizon ────────────────────────────────────────────────────────
141
142/// Detects when a price series approaches its "event horizon" —
143/// the Bollinger Band boundary at which the current trend cannot continue.
144///
145/// Usage:
146/// ```cpp
147/// PriceEventHorizon peh(bb_window=20, bb_sigma=3.0);
148/// for (auto& bar : bars) {
149/// auto temp = peh.update(bar.close);
150/// if (temp) fmt::print("{}\n", temp->to_string());
151/// }
152/// ```
154public:
155 /// Configuration for the Bollinger Band event horizon detector.
156 struct Config {
157 /// Rolling window size for Bollinger Band mean and std dev.
159
160 /// Band multiplier: outer band = μ ± bb_sigma × σ.
162
163 /// T_H threshold above which "near horizon" is signalled.
165
166 /// T_H threshold below which "cold" (continuation) is signalled.
168 };
169
170 explicit PriceEventHorizon(Config config = Config{}) noexcept;
171
172 /// Update state with a new closing price and compute T_H.
173 ///
174 /// @param close Closing price of the current bar.
175 /// @returns HawkingTemperature or nullopt during warm-up
176 /// (until ``bb_window`` bars have been seen).
177 [[nodiscard]] std::optional<HawkingTemperature>
178 update(double close) noexcept;
179
180 /// Reset the internal rolling state (e.g. at session boundaries).
181 void reset() noexcept;
182
183 /// Return current window fill level (0 → full).
184 [[nodiscard]] std::size_t window_fill() const noexcept {
185 return state_.window.size();
186 }
187
188private:
189 Config config_;
190 BollingerState state_;
191 double prev_z_{0.0}; ///< Previous bar's z-score (for Δz)
192 bool has_prev_z_{false};
193};
194
195// ─── HawkingSignalGenerator ───────────────────────────────────────────────────
196
197/// Wraps PriceEventHorizon and converts temperatures to actionable signals.
198///
199/// Usage:
200/// ```cpp
201/// HawkingSignalGenerator gen;
202/// for (auto& bar : bars) {
203/// auto sig = gen.update(bar.close);
204/// if (sig) {
205/// // sig->action is +1, -1, or 0
206/// }
207/// }
208/// ```
210public:
211 explicit HawkingSignalGenerator(
213 ) noexcept;
214
215 /// Update with a new closing price and generate a HawkingSignal.
216 ///
217 /// @param close Closing price of the current bar.
218 /// @returns HawkingSignal or nullopt during warm-up.
219 [[nodiscard]] std::optional<HawkingSignal>
220 update(double close) noexcept;
221
222 /// Reset internal state.
223 void reset() noexcept;
224
225private:
226 PriceEventHorizon horizon_;
227 const PriceEventHorizon::Config config_;
228
229 /// Map a temperature to a direction.
230 [[nodiscard]] HawkingDirection classify(double temperature) const noexcept;
231
232 /// Map a temperature to a normalised strength in [0, 1].
233 [[nodiscard]] static double strength(double temperature) noexcept;
234
235 /// Map direction to a discrete action.
236 [[nodiscard]] static int direction_to_action(HawkingDirection d) noexcept;
237};
238
239// ─── HawkingBacktestResult ────────────────────────────────────────────────────
240
241/// Comparison of Hawking-signal strategy vs the existing TIMELIKE classifier.
243 /// Performance of the Hawking temperature signal strategy.
245
246 /// Performance of the TIMELIKE (standard relativistic) strategy.
248
249 /// Mean |T_H| across all bars with a non-neutral signal.
250 double mean_temperature{0.0};
251
252 /// Fraction of bars where the Hawking signal was non-neutral.
253 double signal_coverage{0.0};
254
255 /// Improvement in Sharpe: hawking − timelike.
256 [[nodiscard]] double sharpe_improvement() const noexcept {
258 }
259
260 /// Format a one-line human-readable summary.
261 [[nodiscard]] std::string to_string() const;
262};
263
264// ─── HawkingBacktest ──────────────────────────────────────────────────────────
265
266/// Runs a backtest comparing the Hawking signal against the TIMELIKE classifier.
267///
268/// Usage:
269/// ```cpp
270/// HawkingBacktest hb;
271/// auto result = hb.run(bars);
272/// if (result) fmt::print("{}\n", result->to_string());
273/// ```
275public:
276 explicit HawkingBacktest(
279 ) noexcept;
280
281 /// Run the comparison backtest on a sequence of OHLCV bars.
282 ///
283 /// Pipeline:
284 /// 1. Compute Hawking signals for every bar via HawkingSignalGenerator.
285 /// 2. Compute TIMELIKE signals via the standard Engine pipeline.
286 /// 3. Evaluate both strategies using backtest::Backtester.
287 ///
288 /// @param bars Input OHLCV sequence (minimum bb_window + 30 bars).
289 /// @returns HawkingBacktestResult or nullopt on insufficient data.
290 [[nodiscard]] std::optional<HawkingBacktestResult>
291 run(std::span<const core::OHLCV> bars) const noexcept;
292
293private:
294 HawkingSignalGenerator signal_gen_;
295 core::Engine engine_;
296 PriceEventHorizon::Config hawking_cfg_;
297};
298
299} // namespace srfm::hawking
Relativistic Backtester — AGT-05 public API.
Orchestrates the full relativistic signal-processing pipeline.
Definition engine.hpp:88
std::optional< HawkingBacktestResult > run(std::span< const core::OHLCV > bars) const noexcept
Definition hawking.cpp:232
void reset() noexcept
Reset internal state.
Definition hawking.cpp:143
std::optional< HawkingSignal > update(double close) noexcept
Definition hawking.cpp:177
void reset() noexcept
Reset the internal rolling state (e.g. at session boundaries).
Definition hawking.cpp:88
std::optional< HawkingTemperature > update(double close) noexcept
Definition hawking.cpp:96
std::size_t window_fill() const noexcept
Return current window fill level (0 → full).
Definition hawking.hpp:184
Core Integration Engine — AGT-06 public API.
constexpr std::size_t DEFAULT_BB_WINDOW
Default Bollinger Band window (bars).
Definition hawking.hpp:61
const char * to_string(HawkingDirection d) noexcept
Return a human-readable string for a HawkingDirection value.
Definition hawking.cpp:32
constexpr double HAWKING_HOT_THRESHOLD
T_H above this → "hot" → reversal signal.
Definition hawking.hpp:67
constexpr double HAWKING_COLD_THRESHOLD
T_H below this → "cold" → continuation signal.
Definition hawking.hpp:70
HawkingDirection
Trading signal derived from Hawking temperature.
Definition hawking.hpp:98
@ Reversal
T_H high → trend exhaustion → fade the move.
@ Neutral
Temperature in the normal range → no signal.
@ Continuation
T_H low → healthy trend → follow the trend.
constexpr double DEFAULT_BB_SIGMA
Default Bollinger Band multiplier for outer band (σ-multiple).
Definition hawking.hpp:64
Performance metrics for a single strategy evaluation.
Definition backtest.hpp:76
double sharpe_ratio
(mean_ret − r_f) / σ, annualised
Definition backtest.hpp:77
Configuration parameters for the core engine.
Definition engine.hpp:56
Internal rolling state for Bollinger Band computation.
Definition hawking.hpp:121
std::vector< double > window
Rolling price window (oldest first).
Definition hawking.hpp:122
double stddev() const noexcept
Return the rolling standard deviation (population σ).
Definition hawking.cpp:71
double sum
Running sum for fast mean.
Definition hawking.hpp:123
double sum_sq
Running sum of squares for fast σ.
Definition hawking.hpp:124
void push(double price) noexcept
Push a new price and pop the oldest if window is full.
Definition hawking.cpp:53
double mean() const noexcept
Return the rolling mean (NaN-safe).
Definition hawking.cpp:66
bool full() const noexcept
True iff window has reached its maximum size.
Definition hawking.hpp:137
Comparison of Hawking-signal strategy vs the existing TIMELIKE classifier.
Definition hawking.hpp:242
backtest::PerformanceMetrics hawking_metrics
Performance of the Hawking temperature signal strategy.
Definition hawking.hpp:244
double sharpe_improvement() const noexcept
Improvement in Sharpe: hawking − timelike.
Definition hawking.hpp:256
std::string to_string() const
Format a one-line human-readable summary.
Definition hawking.cpp:206
double signal_coverage
Fraction of bars where the Hawking signal was non-neutral.
Definition hawking.hpp:253
double mean_temperature
Mean |T_H| across all bars with a non-neutral signal.
Definition hawking.hpp:250
backtest::PerformanceMetrics timelike_metrics
Performance of the TIMELIKE (standard relativistic) strategy.
Definition hawking.hpp:247
A single bar's Hawking-derived trading signal.
Definition hawking.hpp:108
std::string to_string() const
Format a compact one-liner for logging.
Definition hawking.cpp:41
int action
+1 (buy), -1 (sell), 0 (neutral).
Definition hawking.hpp:112
HawkingDirection direction
Trading implication.
Definition hawking.hpp:110
HawkingTemperature temperature
Full temperature measurement.
Definition hawking.hpp:109
double strength
|T_H| normalized to [0, 1].
Definition hawking.hpp:111
double delta_z
Change in z-score from previous bar.
Definition hawking.hpp:86
double temperature
T_H = z × Δz.
Definition hawking.hpp:84
double bollinger_mean
Rolling μ
Definition hawking.hpp:87
std::string to_string() const
Format a compact one-liner for logging.
Definition hawking.cpp:20
bool near_horizon
|z_score| ≥ bb_sigma
Definition hawking.hpp:89
double z_score
(P − μ) / σ
Definition hawking.hpp:85
Configuration for the Bollinger Band event horizon detector.
Definition hawking.hpp:156
double bb_sigma
Band multiplier: outer band = μ ± bb_sigma × σ.
Definition hawking.hpp:161
std::size_t bb_window
Rolling window size for Bollinger Band mean and std dev.
Definition hawking.hpp:158
double hot_threshold
T_H threshold above which "near horizon" is signalled.
Definition hawking.hpp:164
double cold_threshold
T_H threshold below which "cold" (continuation) is signalled.
Definition hawking.hpp:167