tickerforge 0.1.15

Generate and parse derivatives tickers from tickerforge-spec (Rust).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Pydantic-aligned models for futures contracts and exchanges.

use serde::{Deserialize, Deserializer, Serialize};
use std::collections::HashMap;
use std::sync::OnceLock;

use crate::options_models::OptionRule;
use crate::pattern_index::{build_pattern_index, PatternIndex};
use crate::schedule::ExchangeSchedule;

/// One clock-time trading window; YAML uses the map key as `name`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionSegment {
    pub name: String,
    pub start: String,
    pub end: String,
}

fn mapping_to_segments(m: serde_yaml::Mapping) -> Result<Vec<SessionSegment>, String> {
    let mut segments = Vec::new();
    for (k, val) in m {
        let name = k
            .as_str()
            .ok_or_else(|| "session key must be a string".to_string())?
            .to_string();
        let inner = match val {
            serde_yaml::Value::Mapping(m) => m,
            _ => return Err(format!("session '{name}' must be a mapping with start/end")),
        };
        let start = inner
            .get(serde_yaml::Value::String("start".into()))
            .and_then(|v| v.as_str())
            .ok_or_else(|| format!("session '{name}' missing start"))?
            .to_string();
        let end = inner
            .get(serde_yaml::Value::String("end".into()))
            .and_then(|v| v.as_str())
            .ok_or_else(|| format!("session '{name}' missing end"))?
            .to_string();
        segments.push(SessionSegment { name, start, end });
    }
    Ok(segments)
}

fn validate_sessions(segments: &[SessionSegment]) -> Result<(), String> {
    if segments.is_empty() {
        return Ok(());
    }
    if !segments[0].name.eq_ignore_ascii_case("regular") {
        return Err("first session segment must be 'regular' (case-insensitive)".to_string());
    }
    Ok(())
}

fn deserialize_asset_sessions<'de, D>(deserializer: D) -> Result<Vec<SessionSegment>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    let v = serde_yaml::Value::deserialize(deserializer)?;
    match v {
        serde_yaml::Value::Mapping(m) => {
            if m.is_empty() {
                return Err(Error::custom("sessions must not be empty"));
            }
            let segments = mapping_to_segments(m).map_err(Error::custom)?;
            validate_sessions(&segments).map_err(Error::custom)?;
            Ok(segments)
        }
        _ => Err(Error::custom("sessions must be a YAML mapping")),
    }
}

fn deserialize_contract_sessions<'de, D>(deserializer: D) -> Result<Vec<SessionSegment>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    let v = serde_yaml::Value::deserialize(deserializer)?;
    match v {
        serde_yaml::Value::Null => Ok(Vec::new()),
        serde_yaml::Value::Mapping(m) => {
            if m.is_empty() {
                return Ok(Vec::new());
            }
            let segments = mapping_to_segments(m).map_err(Error::custom)?;
            validate_sessions(&segments).map_err(Error::custom)?;
            Ok(segments)
        }
        _ => Err(Error::custom("sessions must be a YAML mapping")),
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct Asset {
    pub symbol: String,
    #[serde(default)]
    pub r#type: Option<String>,
    #[serde(default)]
    pub category: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(deserialize_with = "deserialize_asset_sessions")]
    pub sessions: Vec<SessionSegment>,
}

impl Asset {
    /// True if there is exactly one trading band (no implicit pauses between segments).
    pub fn is_unique_session(&self) -> bool {
        self.sessions.len() == 1
    }

    /// The sole session when [`Self::is_unique_session`]; otherwise `None`.
    pub fn default_session(&self) -> Option<&SessionSegment> {
        if self.sessions.len() == 1 {
            self.sessions.first()
        } else {
            None
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct EquitySpec {
    pub symbol: String,
    pub exchange: String,
    #[serde(default)]
    pub r#type: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub currency: Option<String>,
    #[serde(default)]
    pub tick_size: Option<f64>,
    #[serde(default, rename = "contract_standard")]
    pub ctr_std: Option<u32>,
    #[serde(default, rename = "contract_size")]
    pub ctr_size: Option<f64>,
    #[serde(default)]
    pub aliases: Vec<String>,
    #[serde(default, deserialize_with = "deserialize_asset_sessions")]
    pub sessions: Vec<SessionSegment>,
    #[serde(default)]
    pub exchange_timezone: Option<String>,
}

impl EquitySpec {
    pub fn regular_session(&self) -> Option<&SessionSegment> {
        self.sessions.first()
    }
    pub fn is_unique_session(&self) -> bool {
        self.sessions.len() == 1
    }
    pub fn default_session(&self) -> Option<&SessionSegment> {
        if self.sessions.len() == 1 {
            self.sessions.first()
        } else {
            None
        }
    }
    pub fn regular_session_start_end(&self) -> Option<(&str, &str)> {
        let seg = self.regular_session()?;
        Some((seg.start.as_str(), seg.end.as_str()))
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct Exchange {
    pub code: String,
    #[serde(default)]
    pub mic: Option<String>,
    #[serde(default)]
    pub full_name: Option<String>,
    #[serde(default)]
    pub country: Option<String>,
    #[serde(default)]
    pub timezone: Option<String>,
    #[serde(default)]
    pub assets: HashMap<String, Asset>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ContractCycle {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub months: Vec<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ExpirationRule {
    #[serde(default)]
    pub name: String,
    pub r#type: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub weekday: Option<String>,
    #[serde(default)]
    pub day: Option<i32>,
    #[serde(default)]
    pub n: Option<i32>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub last_trading_day: Option<String>,
    #[serde(default)]
    pub last_trading_day_offset: Option<i32>,
    #[serde(default)]
    pub roll_on_last_trading_day: Option<bool>,
}

impl ExpirationRule {
    pub fn effective_last_trading_day_offset(&self) -> i32 {
        if let Some(offset) = self.last_trading_day_offset {
            return offset;
        }
        match self.last_trading_day.as_deref() {
            Some("prior_business_day") | Some("previous_business_day") => -1,
            Some("same_day") => 0,
            _ => {
                if self.r#type == "first_business_day" {
                    -1
                } else {
                    0
                }
            }
        }
    }

    pub fn should_roll_on_last_trading_day(&self) -> bool {
        if let Some(roll) = self.roll_on_last_trading_day {
            return roll;
        }
        self.effective_last_trading_day_offset() < 0
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct ContractSpec {
    pub symbol: String,
    pub exchange: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default = "default_ticker_format")]
    pub ticker_format: String,
    pub contract_cycle: String,
    pub expiration_rule: String,
    #[serde(default, rename = "contract_standard")]
    pub ctr_std: Option<u32>,
    #[serde(default, rename = "contract_size")]
    pub ctr_size: Option<f64>,
    #[serde(default)]
    pub tick_size: Option<f64>,
    #[serde(default)]
    pub currency: Option<String>,
    #[serde(default)]
    pub aliases: Vec<String>,
    /// Copied at load time from `exchanges/*.yaml` for this symbol (not in contract YAML).
    #[serde(default, deserialize_with = "deserialize_contract_sessions")]
    pub sessions: Vec<SessionSegment>,
    #[serde(default)]
    pub exchange_timezone: Option<String>,
}

impl ContractSpec {
    /// The regular band (first segment; clock times in [`Self::exchange_timezone`]).
    pub fn regular_session(&self) -> Option<&SessionSegment> {
        self.sessions.first()
    }

    /// True if there is exactly one trading band (no implicit pauses between segments).
    pub fn is_unique_session(&self) -> bool {
        self.sessions.len() == 1
    }

    /// The sole session when there is only one band; `None` if zero or multiple segments.
    pub fn default_session(&self) -> Option<&SessionSegment> {
        if self.sessions.len() == 1 {
            self.sessions.first()
        } else {
            None
        }
    }

    /// Start and end clock times for the regular session, e.g. `("09:00", "18:30")`.
    pub fn regular_session_start_end(&self) -> Option<(&str, &str)> {
        let seg = self.regular_session()?;
        Some((seg.start.as_str(), seg.end.as_str()))
    }
}

fn default_ticker_format() -> String {
    "{symbol}{month_code}{yy}".to_string()
}

/// Loaded spec repository (futures + options + shared cycles/rules).
#[derive(Debug, Clone)]
pub struct SpecRepository {
    pub exchanges: HashMap<String, Exchange>,
    pub contracts: HashMap<String, ContractSpec>,
    /// Option rules loaded from all `options:` blocks in `contracts/**/*.yaml`.
    pub options: Vec<OptionRule>,
    pub equities: HashMap<String, EquitySpec>,
    pub contract_cycles: HashMap<String, ContractCycle>,
    pub expiration_rules: HashMap<String, ExpirationRule>,
    pub schedules: HashMap<String, ExchangeSchedule>,
    /// Lazy-filled by classify/parse; not part of load identity.
    #[doc(hidden)]
    pub pattern_index: OnceLock<PatternIndex>,
}

impl SpecRepository {
    pub fn get_exchange(&self, code: &str) -> Result<&Exchange, String> {
        let key = code.to_uppercase();
        self.exchanges
            .get(&key)
            .ok_or_else(|| format!("Unknown exchange: {code}"))
    }

    pub fn get_contract(&self, symbol: &str) -> Result<&ContractSpec, String> {
        let key = symbol.to_uppercase();
        self.contracts
            .get(&key)
            .ok_or_else(|| format!("Unknown contract: {symbol}"))
    }

    pub fn get_equity(&self, symbol: &str) -> Result<&EquitySpec, String> {
        let key = symbol.to_uppercase();
        self.equities
            .get(&key)
            .ok_or_else(|| format!("Unknown equity: {symbol}"))
    }

    /// Precompiled futures/options regexes (built once per repository instance).
    pub fn pattern_index(&self) -> &PatternIndex {
        self.pattern_index.get_or_init(|| build_pattern_index(self))
    }
}

/// Parsed futures ticker.
#[derive(Debug, Clone)]
pub struct ParsedFuturesTicker {
    pub symbol: String,
    pub year: i32,
    pub month: u32,
    pub tick_size: Option<f64>,
    pub ctr_std: Option<u32>,
    pub ctr_size: Option<f64>,
    pub contract: ContractSpec,
    /// The date used for root-symbol resolution.  `None` when a full ticker
    /// was parsed (no date context).
    pub reference_date: Option<chrono::NaiveDate>,
    /// Whether [`reference_date`] is an actual exchange trading session.
    /// `None` when a full ticker was parsed.
    pub is_trading_session: Option<bool>,
    pub contract_offset: Option<isize>,
    /// Whether the contract is tradeable/valid on the reference date.
    pub is_valid: Option<bool>,
}

impl ParsedFuturesTicker {
    /// Full trading symbol string (e.g. `DOLN26`, `INDM26`).
    pub fn format_ticker(&self) -> Result<String, String> {
        crate::ticker_generator::format_contract_ticker(&self.contract, self.year, self.month)
    }

    /// Alias for [`Self::format_ticker`].
    pub fn ticker(&self) -> Result<String, String> {
        self.format_ticker()
    }
}

/// Parsed equity ticker.
#[derive(Debug, Clone)]
pub struct ParsedEquityTicker {
    pub symbol: String,
    pub equity: EquitySpec,
}

impl ParsedEquityTicker {
    /// Full trading symbol string (same as [`Self::symbol`] for cash equities).
    pub fn format_ticker(&self) -> String {
        self.symbol.clone()
    }

    /// Alias for [`Self::format_ticker`].
    pub fn ticker(&self) -> String {
        self.format_ticker()
    }
}

/// Parsed option ticker.
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedOptionTicker {
    /// `"equity"`, `"index"`, `"dollar"`, or `"interest_rate"`.
    pub kind: String,
    /// Full underlying symbol (`"PETR4"`) for equity; root symbol (`"IBOV"`, `"DOL"`, `"IDI"`)
    /// for other types.
    pub underlying_or_symbol: String,
    /// Contract year (`2000 + yy`).  `None` for equity options (no year in ticker).
    pub year: Option<i32>,
    /// Contract month (1–12).
    pub month: u32,
    /// `true` = call, `false` = put.
    pub is_call: bool,
    /// Raw strike string as it appears in the ticker (e.g. `"5000"`, `"120000"`).
    pub strike: String,
    /// Exchange code (e.g. `"B3"`).
    pub exchange: String,
    /// Minimum price increment from the option rule.
    pub tick_size: Option<f64>,
    pub ctr_std: Option<u32>,
    pub ctr_size: Option<f64>,
}

impl ParsedOptionTicker {
    /// Rebuild the exchange option ticker string from this parsed result.
    pub fn format_ticker(&self, spec: &SpecRepository) -> Result<String, String> {
        crate::options_ticker::format_parsed_option_ticker(self, spec)
    }

    /// Alias for [`Self::format_ticker`].
    pub fn ticker(&self, spec: &SpecRepository) -> Result<String, String> {
        self.format_ticker(spec)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_contract_spec(sessions: Vec<SessionSegment>) -> ContractSpec {
        ContractSpec {
            symbol: "Y".into(),
            exchange: "B3".into(),
            description: None,
            ticker_format: default_ticker_format(),
            contract_cycle: "m".into(),
            expiration_rule: "r".into(),
            ctr_std: None,
            ctr_size: None,
            tick_size: None,
            currency: None,
            aliases: vec![],
            sessions,
            exchange_timezone: None,
        }
    }

    #[test]
    fn default_session_is_some_only_for_single_segment() {
        let one = sample_contract_spec(vec![SessionSegment {
            name: "regular".into(),
            start: "09:00".into(),
            end: "18:00".into(),
        }]);
        assert!(one.is_unique_session());
        assert_eq!(
            one.default_session().map(|s| s.name.as_str()),
            Some("regular")
        );

        let multi = sample_contract_spec(vec![
            SessionSegment {
                name: "regular".into(),
                start: "09:00".into(),
                end: "12:00".into(),
            },
            SessionSegment {
                name: "afternoon".into(),
                start: "13:00".into(),
                end: "18:00".into(),
            },
        ]);
        assert!(!multi.is_unique_session());
        assert!(multi.default_session().is_none());
    }

    #[test]
    fn empty_contract_spec_sessions_no_default() {
        let empty = sample_contract_spec(vec![]);
        assert!(!empty.is_unique_session());
        assert!(empty.default_session().is_none());
    }
}