Special Relativity in Financial Modeling 1.0.0
Lorentz transforms, spacetime classification, and geodesic price paths for quantitative finance
Loading...
Searching...
No Matches
n_asset_engine.hpp
Go to the documentation of this file.
1#pragma once
2/**
3 * @file n_asset_engine.hpp
4 * @brief Full pipeline engine: N-asset OHLCV → relativistic momentum signals.
5 *
6 * Module: include/srfm/engine/
7 * Stage: 4 — N-Asset Manifold
8 *
9 * ## Responsibility
10 * Orchestrate the full SRFM pipeline for N assets:
11 * 1. Accumulate OHLCV bars in a ring buffer.
12 * 2. Estimate the N×N covariance matrix from log-returns.
13 * 3. Construct an NAssetManifold from the covariance estimate.
14 * 4. Compute per-asset relativistic momenta:
15 * β_i = |Δprice_i / (c_market × prev_close_i)|
16 * γ_i = 1 / sqrt(1 - β_i²)
17 * m_eff_i = volume_i / adv_baseline
18 * p_rel_i = γ_i × m_eff_i × close_i
19 * 5. Compute the portfolio spacetime interval.
20 * 6. Classify each asset and the portfolio into TIMELIKE/SPACELIKE/LIGHTLIKE.
21 *
22 * ## Guarantees
23 * - All public methods are noexcept.
24 * - All fallible operations return std::optional.
25 * - No raw pointers.
26 *
27 * ## NOT Responsible For
28 * - Fetching market data.
29 * - Persistence of history.
30 * - Cross-process coordination.
31 */
32
33#include "../manifold/n_asset_interval.hpp"
34#include "../tensor/n_asset_manifold.hpp"
35
36#include <deque>
37#include <optional>
38#include <span>
39#include <string>
40#include <variant>
41#include <vector>
42
43namespace srfm::engine {
44
49
50// ── Constants ─────────────────────────────────────────────────────────────────
51
52/// Maximum safe beta value (mirrors BETA_MAX_SAFE from momentum.hpp).
53inline constexpr double ENGINE_BETA_MAX_SAFE = 0.9999;
54
55// ── Input types ───────────────────────────────────────────────────────────────
56
57/**
58 * @brief A single OHLCV bar for one asset.
59 */
60struct OHLCVBar {
61 double open; ///< Opening price.
62 double high; ///< Highest price.
63 double low; ///< Lowest price.
64 double close; ///< Closing price.
65 double volume; ///< Volume traded.
66 double timestamp; ///< Bar timestamp (seconds since epoch or bar index).
67};
68
69/**
70 * @brief The universe of assets processed by the engine.
71 */
73 std::vector<std::string> names; ///< Asset names in order.
74
75 /**
76 * @brief Return the number of assets.
77 *
78 * @return static_cast<int>(names.size()).
79 */
80 [[nodiscard]] int n() const noexcept {
81 return static_cast<int>(names.size());
82 }
83};
84
85// ── Configuration ─────────────────────────────────────────────────────────────
86
87/**
88 * @brief Engine configuration parameters.
89 */
91 double c_market{1.0}; ///< Market speed of light.
92 double adv_baseline{1'000'000.0}; ///< ADV baseline for effective mass.
93 int lookback_bars{20}; ///< Bars required before covariance is valid.
94 double lightlike_threshold{1e-10}; ///< ds² threshold for LIGHTLIKE classification.
95};
96
97// ── Output types ──────────────────────────────────────────────────────────────
98
99/**
100 * @brief Relativistic momentum result for a single asset.
101 */
103 std::string asset_name; ///< Name of the asset.
104 double beta; ///< Lorentz beta (normalised velocity).
105 double gamma; ///< Lorentz gamma factor.
106 double m_eff; ///< Effective mass (volume / ADV_baseline).
107 double relativistic_momentum; ///< p_rel = γ × m_eff × close.
108 IntervalType regime; ///< Interval type for this asset.
109};
110
111/**
112 * @brief Aggregated engine output for one process() call.
113 */
115 std::vector<AssetMomentumResult> assets; ///< Per-asset results.
116 IntervalType portfolio_regime; ///< Portfolio-level regime.
117 double portfolio_interval_sq; ///< Portfolio ds².
118 double timestamp; ///< Timestamp of latest bar.
119};
120
121// ── Engine ────────────────────────────────────────────────────────────────────
122
123/**
124 * @brief Full SRFM pipeline engine for N assets.
125 *
126 * Accumulates OHLCV bars, estimates covariance, builds an NAssetManifold,
127 * computes relativistic momenta, and classifies market regimes.
128 */
130public:
131 // ── Construction ─────────────────────────────────────────────────────────
132
133 /**
134 * @brief Construct an engine for the given asset universe.
135 *
136 * @param universe The set of assets (names must be non-empty).
137 * @param cfg Engine configuration.
138 */
139 explicit NAssetEngine(AssetUniverse universe,
140 EngineConfig cfg = {}) noexcept;
141
142 // ── Data ingestion ────────────────────────────────────────────────────────
143
144 /**
145 * @brief Ingest one bar for every asset in the universe.
146 *
147 * Bars must be provided in the same order as universe.names.
148 * The bar is appended to the history ring buffer; if history exceeds
149 * lookback_bars * 2 the oldest entry is dropped.
150 *
151 * @param bars Span of bars, one per asset (must have length n_assets()).
152 * @return std::monostate on success, std::nullopt if bar count mismatches.
153 */
154 [[nodiscard]] std::optional<std::monostate>
155 ingest(std::span<const OHLCVBar> bars) noexcept;
156
157 // ── Processing ────────────────────────────────────────────────────────────
158
159 /**
160 * @brief Run the full pipeline on accumulated history.
161 *
162 * Requires ready() == true (at least lookback_bars entries in history).
163 *
164 * Steps:
165 * 1. Estimate covariance from log-returns.
166 * 2. Build NAssetManifold.
167 * 3. Compute per-asset β, γ, m_eff, p_rel, regime.
168 * 4. Compute portfolio interval and regime.
169 *
170 * @return EngineOutput, or std::nullopt if not ready or covariance fails.
171 */
172 [[nodiscard]] std::optional<EngineOutput> process() const noexcept;
173
174 /**
175 * @brief Ingest bars then immediately process.
176 *
177 * Convenience wrapper: ingest(bars) followed by process().
178 *
179 * @param bars Bars to ingest.
180 * @return EngineOutput or std::nullopt.
181 */
182 [[nodiscard]] std::optional<EngineOutput>
183 ingest_and_process(std::span<const OHLCVBar> bars) noexcept;
184
185 // ── Status ────────────────────────────────────────────────────────────────
186
187 /**
188 * @brief Return the number of assets.
189 *
190 * @return universe_.n().
191 */
192 [[nodiscard]] int n_assets() const noexcept;
193
194 /**
195 * @brief Return true if enough bars have been accumulated.
196 *
197 * @return history_.size() >= static_cast<size_t>(cfg_.lookback_bars).
198 */
199 [[nodiscard]] bool ready() const noexcept;
200
201private:
202 // ── Internal pipeline stages ──────────────────────────────────────────────
203
204 /**
205 * @brief Compute the N×N empirical covariance from accumulated log-returns.
206 *
207 * Uses the last lookback_bars bars. Log-return for bar t, asset i:
208 * r_ti = log(close[t][i] / close[t-1][i])
209 * Covariance: Cov_ij = (1/(T-1)) Σ_t (r_ti - r̄_i)(r_tj - r̄_j)
210 *
211 * @return N×N covariance matrix, or std::nullopt if history too short or
212 * any close price is non-positive.
213 */
214 [[nodiscard]] std::optional<Eigen::MatrixXd>
215 estimate_covariance() const noexcept;
216
217 /**
218 * @brief Compute beta for one asset from two consecutive bars.
219 *
220 * beta = |Δprice / (c_market * prev_close)|, clamped to
221 * [0, ENGINE_BETA_MAX_SAFE - 1e-9].
222 *
223 * @param prev_close Previous closing price (must be > 0).
224 * @param curr_close Current closing price.
225 * @return Beta value, or std::nullopt if prev_close <= 0.
226 */
227 [[nodiscard]] std::optional<double>
228 compute_beta(double prev_close, double curr_close) const noexcept;
229
230 /**
231 * @brief Compute the portfolio spacetime interval from two consecutive events.
232 *
233 * Builds NAssetEvents from the last two bar snapshots and calls
234 * NAssetInterval::compute.
235 *
236 * @param manifold The manifold to use for the metric.
237 * @return ds² and type, or std::nullopt on failure.
238 */
239 [[nodiscard]] std::optional<std::pair<double, IntervalType>>
240 compute_portfolio_interval(const NAssetManifold& manifold) const noexcept;
241
242 // ── Data members ──────────────────────────────────────────────────────────
243
244 AssetUniverse universe_; ///< Asset universe.
245 EngineConfig cfg_; ///< Engine configuration.
246
247 /// Ring buffer: each entry is a snapshot of N bars (one per asset).
248 std::deque<std::vector<OHLCVBar>> history_;
249};
250
251// ── Inline trivial accessors ──────────────────────────────────────────────────
252
253inline int NAssetEngine::n_assets() const noexcept {
254 return universe_.n();
255}
256
257inline bool NAssetEngine::ready() const noexcept {
258 return static_cast<int>(history_.size()) >= cfg_.lookback_bars;
259}
260
261} // namespace srfm::engine
Full SRFM pipeline engine for N assets.
std::optional< std::monostate > ingest(std::span< const OHLCVBar > bars) noexcept
Ingest one bar for every asset in the universe.
std::optional< EngineOutput > ingest_and_process(std::span< const OHLCVBar > bars) noexcept
Ingest bars then immediately process.
bool ready() const noexcept
Return true if enough bars have been accumulated.
int n_assets() const noexcept
Return the number of assets.
std::optional< EngineOutput > process() const noexcept
Run the full pipeline on accumulated history.
Computes spacetime intervals between N-asset events.
(N+1)-dimensional Lorentzian manifold for N financial assets.
constexpr double ENGINE_BETA_MAX_SAFE
Maximum safe beta value (mirrors BETA_MAX_SAFE from momentum.hpp).
IntervalType
Causal character of a spacetime interval.
Definition manifold.hpp:61
Relativistic momentum result for a single asset.
double relativistic_momentum
p_rel = γ × m_eff × close.
double m_eff
Effective mass (volume / ADV_baseline).
std::string asset_name
Name of the asset.
double gamma
Lorentz gamma factor.
IntervalType regime
Interval type for this asset.
double beta
Lorentz beta (normalised velocity).
The universe of assets processed by the engine.
int n() const noexcept
Return the number of assets.
std::vector< std::string > names
Asset names in order.
Engine configuration parameters.
int lookback_bars
Bars required before covariance is valid.
double lightlike_threshold
ds² threshold for LIGHTLIKE classification.
double adv_baseline
ADV baseline for effective mass.
double c_market
Market speed of light.
Aggregated engine output for one process() call.
double portfolio_interval_sq
Portfolio ds².
double timestamp
Timestamp of latest bar.
std::vector< AssetMomentumResult > assets
Per-asset results.
IntervalType portfolio_regime
Portfolio-level regime.
A single OHLCV bar for one asset.
double open
Opening price.
double volume
Volume traded.
double close
Closing price.
double timestamp
Bar timestamp (seconds since epoch or bar index).
double low
Lowest price.
double high
Highest price.
A spacetime event: a moment in time with N asset prices.