qualia_core_db/specialized_libs/financial_modeling/
pricing.rs1use super::*;
2
3pub struct PricingEngine {
5 pricing_models: HashMap<String, PricingModel>,
6 market_data: MarketData,
7 valuation_engine: ValuationEngine,
8}
9
10#[derive(Debug, Clone)]
12pub struct PricingModel {
13 pub model_id: String,
14 pub model_type: PricingModelType,
15 pub parameters: PricingModelParameters,
16}
17
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20pub enum PricingModelType {
21 BlackScholes,
22 Binomial,
23 MonteCarlo,
24 FiniteDifference,
25 Analytical,
26}
27
28#[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
37pub struct ValuationEngine {
39 valuation_methods: HashMap<String, ValuationMethod>,
40 discount_rates: HashMap<String, f64>,
41 cash_flow_projections: HashMap<String, CashFlowProjection>,
42}
43
44#[derive(Debug, Clone)]
46pub struct ValuationMethod {
47 pub method_id: String,
48 pub method_type: ValuationMethodType,
49 pub parameters: ValuationMethodParameters,
50}
51
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54pub enum ValuationMethodType {
55 DCF,
56 DDM,
57 Multiples,
58 AssetBased,
59 OptionPricing,
60}
61
62#[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#[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#[derive(Debug, Clone)]
81pub struct CashFlow {
82 pub period: u32,
83 pub amount: f64,
84 pub cash_flow_type: CashFlowType,
85}
86
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89pub enum CashFlowType {
90 Operating,
91 Investing,
92 Financing,
93 Free,
94}
95
96#[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 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 pub fn initialize(&mut self) -> Result<(), FinancialError> {
117 self.valuation_engine.initialize()?;
118 Ok(())
119 }
120
121 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 pub fn price_option(&self, params: &OptionParameters) -> Result<OptionPrice, FinancialError> {
154 let option_price = self.black_scholes_price(params)?;
156 Ok(option_price)
157 }
158
159 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 if t <= 0.0 {
176 return Ok(self.intrinsic_price(params));
177 }
178
179 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 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 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 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 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 fn normal_cdf(&self, x: f64) -> f64 {
295 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 fn normal_pdf(&self, x: f64) -> f64 {
312 (-0.5 * x * x).exp() / (2.0 * std::f64::consts::PI).sqrt()
313 }
314
315 fn calculate_theta(&self, params: &OptionParameters, _d1: f64, d2: f64, pdf_d1: f64) -> f64 {
318 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 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 pub fn add_pricing_model(&mut self, model: PricingModel) {
351 self.pricing_models.insert(model.model_id.clone(), model);
352 }
353
354 pub fn get_pricing_model(&self, model_id: &str) -> Option<&PricingModel> {
356 self.pricing_models.get(model_id)
357 }
358
359 pub fn list_pricing_models(&self) -> Vec<String> {
361 self.pricing_models.keys().cloned().collect()
362 }
363
364 pub fn market_data(&self) -> &MarketData {
366 &self.market_data
367 }
368
369 pub fn market_data_mut(&mut self) -> &mut MarketData {
371 &mut self.market_data
372 }
373}
374
375impl ValuationEngine {
376 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 pub fn initialize(&mut self) -> Result<(), FinancialError> {
387 Ok(())
388 }
389
390 pub fn add_valuation_method(&mut self, method: ValuationMethod) {
392 self.valuation_methods
393 .insert(method.method_id.clone(), method);
394 }
395
396 pub fn get_valuation_method(&self, method_id: &str) -> Option<&ValuationMethod> {
398 self.valuation_methods.get(method_id)
399 }
400
401 pub fn list_valuation_methods(&self) -> Vec<String> {
403 self.valuation_methods.keys().cloned().collect()
404 }
405
406 pub fn set_discount_rate(&mut self, name: &str, rate: f64) {
408 self.discount_rates.insert(name.to_string(), rate);
409 }
410
411 pub fn get_discount_rate(&self, name: &str) -> Option<&f64> {
413 self.discount_rates.get(name)
414 }
415
416 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 pub fn get_cash_flow_projection(&self, projection_id: &str) -> Option<&CashFlowProjection> {
424 self.cash_flow_projections.get(projection_id)
425 }
426}