Skip to main content

qualia_core_db/specialized_libs/financial_modeling/
pricing.rs

1use super::*;
2
3/// Pricing engine
4pub struct PricingEngine {
5    pricing_models: HashMap<String, PricingModel>,
6    market_data: MarketData,
7    valuation_engine: ValuationEngine,
8}
9
10/// Pricing models
11#[derive(Debug, Clone)]
12pub struct PricingModel {
13    pub model_id: String,
14    pub model_type: PricingModelType,
15    pub parameters: PricingModelParameters,
16}
17
18/// Pricing model types
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20pub enum PricingModelType {
21    BlackScholes,
22    Binomial,
23    MonteCarlo,
24    FiniteDifference,
25    Analytical,
26}
27
28/// Pricing model parameters
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct PricingModelParameters {
31    pub risk_free_rate: f64,
32    pub volatility: f64,
33    pub dividend_yield: f64,
34    pub time_to_maturity: f64,
35}
36
37/// Valuation engine
38pub struct ValuationEngine {
39    valuation_methods: HashMap<String, ValuationMethod>,
40    discount_rates: HashMap<String, f64>,
41    cash_flow_projections: HashMap<String, CashFlowProjection>,
42}
43
44/// Valuation methods
45#[derive(Debug, Clone)]
46pub struct ValuationMethod {
47    pub method_id: String,
48    pub method_type: ValuationMethodType,
49    pub parameters: ValuationMethodParameters,
50}
51
52/// Valuation method types
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54pub enum ValuationMethodType {
55    DCF,
56    DDM,
57    Multiples,
58    AssetBased,
59    OptionPricing,
60}
61
62/// Valuation method parameters
63#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct ValuationMethodParameters {
65    pub discount_rate: f64,
66    pub growth_rate: f64,
67    pub terminal_growth: f64,
68    pub multiples: HashMap<String, f64>,
69}
70
71/// Cash flow projections
72#[derive(Debug, Clone)]
73pub struct CashFlowProjection {
74    pub projection_id: String,
75    pub cash_flows: Vec<CashFlow>,
76    pub assumptions: Vec<Assumption>,
77}
78
79/// Cash flows
80#[derive(Debug, Clone)]
81pub struct CashFlow {
82    pub period: u32,
83    pub amount: f64,
84    pub cash_flow_type: CashFlowType,
85}
86
87/// Cash flow types
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89pub enum CashFlowType {
90    Operating,
91    Investing,
92    Financing,
93    Free,
94}
95
96/// Assumptions
97#[derive(Debug, Clone)]
98pub struct Assumption {
99    pub assumption_id: String,
100    pub assumption_name: String,
101    pub assumption_value: f64,
102    pub justification: String,
103}
104
105impl PricingEngine {
106    /// Creates a `PricingEngine` with empty registries / default configuration.
107    pub fn new() -> Self {
108        Self {
109            pricing_models: HashMap::new(),
110            market_data: MarketData::new(),
111            valuation_engine: ValuationEngine::new(),
112        }
113    }
114
115    /// Readies the `PricingEngine` sub-components; registers/populates any built-in defaults.
116    pub fn initialize(&mut self) -> Result<(), FinancialError> {
117        self.valuation_engine.initialize()?;
118        Ok(())
119    }
120
121    /// Validates option parameters (positive strike, nonnegative
122    /// volatility/time) before pricing; errors with `ValidationError`.
123    pub fn validate_option_parameters(
124        &self,
125        params: &OptionParameters,
126    ) -> Result<(), FinancialError> {
127        if params.underlying_price <= 0.0 {
128            return Err(FinancialError::ValidationError(
129                "Underlying price must be positive".to_string(),
130            ));
131        }
132        if params.strike <= 0.0 {
133            return Err(FinancialError::ValidationError(
134                "Strike price must be positive".to_string(),
135            ));
136        }
137        if params.time_to_maturity < 0.0 {
138            return Err(FinancialError::ValidationError(
139                "Time to maturity must be non-negative".to_string(),
140            ));
141        }
142        if params.volatility < 0.0 {
143            return Err(FinancialError::ValidationError(
144                "Volatility must be non-negative".to_string(),
145            ));
146        }
147        Ok(())
148    }
149
150    /// Prices a European option via Black-Scholes (see
151    /// [`Self::black_scholes_price`]); returns the full `OptionPrice` with
152    /// Greeks.
153    pub fn price_option(&self, params: &OptionParameters) -> Result<OptionPrice, FinancialError> {
154        // Price option using Black-Scholes
155        let option_price = self.black_scholes_price(params)?;
156        Ok(option_price)
157    }
158
159    /// Black-Scholes price + Greeks (delta, gamma, theta, vega, rho) for a
160    /// European option. Handles the degenerate edges analytically: `t<=0`
161    /// returns intrinsic value, `sigma<=0` returns the deterministic discounted
162    /// payoff, `s<=0` returns the worthless-call/discounted-put boundary.
163    fn black_scholes_price(
164        &self,
165        params: &OptionParameters,
166    ) -> Result<OptionPrice, FinancialError> {
167        let s = params.underlying_price;
168        let k = params.strike;
169        let r = params.risk_free_rate;
170        let sigma = params.volatility;
171        let t = params.time_to_maturity;
172
173        // Edge case: zero time to expiry -> option is worth its intrinsic value
174        // (no time value remains). Greeks collapse to their intrinsic boundary.
175        if t <= 0.0 {
176            return Ok(self.intrinsic_price(params));
177        }
178
179        // Edge case: zero volatility -> payoff is deterministic. The terminal
180        // price is S*exp(rT), so the discounted call payoff is max(S - K*exp(-rT), 0)
181        // and the put payoff is max(K*exp(-rT) - S, 0). Greeks are zero except
182        // delta, which is the step function at the strike.
183        if sigma <= 0.0 {
184            let disc = (-r * t).exp();
185            let fwd = s - k * disc;
186            let (price, delta) = match params.option_type {
187                OptionType::Call => (fwd.max(0.0), if fwd > 0.0 { 1.0 } else { 0.0 }),
188                OptionType::Put => ((-fwd).max(0.0), if fwd < 0.0 { -1.0 } else { 0.0 }),
189            };
190            return Ok(OptionPrice {
191                price,
192                delta,
193                gamma: 0.0,
194                theta: 0.0,
195                vega: 0.0,
196                rho: 0.0,
197            });
198        }
199
200        // Edge case: zero underlying price -> call is worthless, put is the
201        // discounted strike.
202        if s <= 0.0 {
203            let disc = (-r * t).exp();
204            return Ok(match params.option_type {
205                OptionType::Call => OptionPrice {
206                    price: 0.0,
207                    delta: 0.0,
208                    gamma: 0.0,
209                    theta: 0.0,
210                    vega: 0.0,
211                    rho: 0.0,
212                },
213                OptionType::Put => OptionPrice {
214                    price: k * disc,
215                    delta: -1.0,
216                    gamma: 0.0,
217                    theta: r * k * disc,
218                    vega: 0.0,
219                    rho: -t * k * disc,
220                },
221            });
222        }
223
224        // Standard Black-Scholes formula.
225        let sqrt_t = t.sqrt();
226        let d1 = ((s / k).ln() + (r + 0.5 * sigma * sigma) * t) / (sigma * sqrt_t);
227        let d2 = d1 - sigma * sqrt_t;
228        let disc = (-r * t).exp();
229        let pdf_d1 = self.normal_pdf(d1);
230
231        let (price, delta) = match params.option_type {
232            OptionType::Call => {
233                let p = s * self.normal_cdf(d1) - k * disc * self.normal_cdf(d2);
234                (p, self.normal_cdf(d1))
235            }
236            OptionType::Put => {
237                let p = k * disc * self.normal_cdf(-d2) - s * self.normal_cdf(-d1);
238                (p, self.normal_cdf(d1) - 1.0)
239            }
240        };
241
242        // Gamma and Vega are identical for calls and puts.
243        let gamma = pdf_d1 / (s * sigma * sqrt_t);
244        let vega = s * pdf_d1 * sqrt_t;
245
246        let theta = self.calculate_theta(params, d1, d2, pdf_d1);
247        let rho = self.calculate_rho(params, d2, disc);
248
249        Ok(OptionPrice {
250            price,
251            delta,
252            gamma,
253            theta,
254            vega,
255            rho,
256        })
257    }
258
259    /// Intrinsic value at expiry (T=0): call = max(S-K, 0), put = max(K-S, 0).
260    /// Delta is the step at the strike; other Greeks are zero.
261    fn intrinsic_price(&self, params: &OptionParameters) -> OptionPrice {
262        let intrinsic = match params.option_type {
263            OptionType::Call => (params.underlying_price - params.strike).max(0.0),
264            OptionType::Put => (params.strike - params.underlying_price).max(0.0),
265        };
266        let delta = match params.option_type {
267            OptionType::Call => {
268                if params.underlying_price > params.strike {
269                    1.0
270                } else {
271                    0.0
272                }
273            }
274            OptionType::Put => {
275                if params.underlying_price < params.strike {
276                    -1.0
277                } else {
278                    0.0
279                }
280            }
281        };
282        OptionPrice {
283            price: intrinsic,
284            delta,
285            gamma: 0.0,
286            theta: 0.0,
287            vega: 0.0,
288            rho: 0.0,
289        }
290    }
291
292    /// Standard normal CDF via the Abramowitz–Stegun rational approximation
293    /// (max abs error ~7.5e-8).
294    fn normal_cdf(&self, x: f64) -> f64 {
295        // Abramowitz and Stegun approximation for normal CDF (max error 7.5e-8)
296        let t = 1.0 / (1.0 + 0.2316419 * x.abs());
297        let d = 0.3989422819 * (-x * x / 2.0).exp();
298        let p = d
299            * t
300            * (0.3193815306
301                + t * (-0.3565637813
302                    + t * (1.7814779372 + t * (-1.8212559978 + t * 1.3302744929))));
303        if x >= 0.0 {
304            1.0 - p
305        } else {
306            p
307        }
308    }
309
310    /// Standard normal PDF `exp(-x²/2)/√(2π)`.
311    fn normal_pdf(&self, x: f64) -> f64 {
312        (-0.5 * x * x).exp() / (2.0 * std::f64::consts::PI).sqrt()
313    }
314
315    /// Black-Scholes theta returned **per calendar day** (annualized
316    /// expression divided by 365), as conventionally quoted.
317    fn calculate_theta(&self, params: &OptionParameters, _d1: f64, d2: f64, pdf_d1: f64) -> f64 {
318        // Theta per calendar day (divided by 365). The annualized theta is the
319        // standard Black-Scholes expression; reporting per-day matches how the
320        // Greek is conventionally quoted.
321        let sqrt_t = params.time_to_maturity.sqrt();
322        let disc = (-params.risk_free_rate * params.time_to_maturity).exp();
323        let annualized = match params.option_type {
324            OptionType::Call => {
325                -(params.underlying_price * pdf_d1 * params.volatility) / (2.0 * sqrt_t)
326                    - params.risk_free_rate * params.strike * disc * self.normal_cdf(d2)
327            }
328            OptionType::Put => {
329                -(params.underlying_price * pdf_d1 * params.volatility) / (2.0 * sqrt_t)
330                    + params.risk_free_rate * params.strike * disc * self.normal_cdf(-d2)
331            }
332        };
333        annualized / 365.0
334    }
335
336    /// Black-Scholes rho: `K·T·disc·N(d2)` for calls, negative for puts.
337    /// `disc` is the caller-computed `exp(-rT)`.
338    fn calculate_rho(&self, params: &OptionParameters, d2: f64, disc: f64) -> f64 {
339        match params.option_type {
340            OptionType::Call => {
341                params.strike * params.time_to_maturity * disc * self.normal_cdf(d2)
342            }
343            OptionType::Put => {
344                -params.strike * params.time_to_maturity * disc * self.normal_cdf(-d2)
345            }
346        }
347    }
348
349    /// Registers `pricing model` in the registry (keyed by its id).
350    pub fn add_pricing_model(&mut self, model: PricingModel) {
351        self.pricing_models.insert(model.model_id.clone(), model);
352    }
353
354    /// Looks up `pricing model` by id; `None` if not registered.
355    pub fn get_pricing_model(&self, model_id: &str) -> Option<&PricingModel> {
356        self.pricing_models.get(model_id)
357    }
358
359    /// Iterates over all registered `pricing models` entries.
360    pub fn list_pricing_models(&self) -> Vec<String> {
361        self.pricing_models.keys().cloned().collect()
362    }
363
364    /// Returns a reference to the inner `market_data` sub-component.
365    pub fn market_data(&self) -> &MarketData {
366        &self.market_data
367    }
368
369    /// Mutable access to the inner `market_data` sub-component.
370    pub fn market_data_mut(&mut self) -> &mut MarketData {
371        &mut self.market_data
372    }
373}
374
375impl ValuationEngine {
376    /// Creates a `ValuationEngine` with empty registries / default configuration.
377    pub fn new() -> Self {
378        Self {
379            valuation_methods: HashMap::new(),
380            discount_rates: HashMap::new(),
381            cash_flow_projections: HashMap::new(),
382        }
383    }
384
385    /// Readies the `ValuationEngine` sub-components; registers/populates any built-in defaults.
386    pub fn initialize(&mut self) -> Result<(), FinancialError> {
387        Ok(())
388    }
389
390    /// Registers `valuation method` in the registry (keyed by its id).
391    pub fn add_valuation_method(&mut self, method: ValuationMethod) {
392        self.valuation_methods
393            .insert(method.method_id.clone(), method);
394    }
395
396    /// Looks up `valuation method` by id; `None` if not registered.
397    pub fn get_valuation_method(&self, method_id: &str) -> Option<&ValuationMethod> {
398        self.valuation_methods.get(method_id)
399    }
400
401    /// Iterates over all registered `valuation methods` entries.
402    pub fn list_valuation_methods(&self) -> Vec<String> {
403        self.valuation_methods.keys().cloned().collect()
404    }
405
406    /// Sets the discount rate used for cash-flow valuation.
407    pub fn set_discount_rate(&mut self, name: &str, rate: f64) {
408        self.discount_rates.insert(name.to_string(), rate);
409    }
410
411    /// Looks up `discount rate` by id; `None` if not registered.
412    pub fn get_discount_rate(&self, name: &str) -> Option<&f64> {
413        self.discount_rates.get(name)
414    }
415
416    /// Registers `cash flow projection` in the registry (keyed by its id).
417    pub fn add_cash_flow_projection(&mut self, projection: CashFlowProjection) {
418        self.cash_flow_projections
419            .insert(projection.projection_id.clone(), projection);
420    }
421
422    /// Looks up `cash flow projection` by id; `None` if not registered.
423    pub fn get_cash_flow_projection(&self, projection_id: &str) -> Option<&CashFlowProjection> {
424        self.cash_flow_projections.get(projection_id)
425    }
426}