yfinance-rs 0.9.1

Ergonomic Rust client for Yahoo Finance, supporting historical prices, real-time streaming, options, fundamentals, and more.
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
// src/core/quotes.rs
use std::{borrow::Cow, fmt::Write as _};

use futures::{StreamExt, stream};
use serde::Deserialize;
use serde_json::Value;
use url::Url;

use crate::{
    YfClient, YfError,
    core::{
        CallOptions, DataQuality, ProjectionContext, ProjectionIssue,
        client::{CacheEndpoint, normalize_symbols},
        conversions::{i64_to_date, i64_to_datetime, quantity_from_u64},
        currency_resolver::{CurrencyHints, ResolvedCurrencyUnit},
        diagnostics::{WireProjection, optional_decimal_f64},
        models::{FastInfo, MovingAverages},
        net, quotesummary,
        wire::{
            JsonDecimal, JsonU64, RawDate, RawDecimal, RawNum, RawNumU64, WireField, WireValue,
        },
        yahoo_vocab::{first_parsed_yahoo_exchange, parse_yahoo_exchange, parse_yahoo_quote_type},
    },
};
use paft::Decimal;
use paft::aggregates::Snapshot;
use paft::domain::{Exchange, Instrument, MarketState};
use paft::fundamentals::statements::Calendar;
use paft::fundamentals::statistics::KeyStatistics;
use paft::market::orderbook::BookLevel;
use paft::market::quote::Quote;
use paft::money::{Currency, PriceAmount};

const KEY_STATISTICS_MODULES: &str = "summaryDetail,defaultKeyStatistics";
const MAX_V7_QUOTE_SYMBOLS_PER_REQUEST: usize = 100;
const MAX_V7_QUOTE_URL_BYTES: usize = 1_800;
// Live probes plateaued at 12 concurrent quote chunks; 16 added burst without improving latency.
const MAX_V7_QUOTE_CONCURRENT_REQUESTS: usize = 12;

// Centralized wire model for the v7 quote API
#[derive(Deserialize)]
pub struct V7Envelope {
    #[serde(rename = "quoteResponse")]
    pub(crate) quote_response: Option<V7QuoteResponse>,
}

#[derive(Deserialize)]
pub struct V7QuoteResponse {
    pub(crate) result: Option<Vec<Value>>,
    pub(crate) error: Option<V7Error>,
}

#[derive(Deserialize)]
pub struct V7Error {
    pub(crate) description: String,
}

#[derive(Deserialize, Clone)]
pub struct V7QuoteNode {
    #[serde(default)]
    pub(crate) symbol: WireValue<String>,
    #[serde(rename = "quoteType")]
    #[serde(default)]
    pub(crate) quote_type: WireValue<String>,
    #[serde(rename = "shortName")]
    #[serde(default)]
    pub(crate) short_name: WireValue<String>,
    #[serde(rename = "longName")]
    #[serde(default)]
    pub(crate) long_name: WireValue<String>,
    #[serde(rename = "regularMarketPrice")]
    #[serde(default)]
    pub(crate) regular_market_price: WireValue<f64>,
    #[serde(rename = "regularMarketOpen")]
    #[serde(default)]
    pub(crate) regular_market_open: WireValue<f64>,
    #[serde(rename = "regularMarketDayHigh")]
    #[serde(default)]
    pub(crate) regular_market_day_high: WireValue<f64>,
    #[serde(rename = "regularMarketDayLow")]
    #[serde(default)]
    pub(crate) regular_market_day_low: WireValue<f64>,
    #[serde(rename = "regularMarketPreviousClose")]
    #[serde(default)]
    pub(crate) regular_market_previous_close: WireValue<f64>,
    #[serde(rename = "regularMarketVolume")]
    #[serde(default)]
    pub(crate) regular_market_volume: WireValue<JsonU64>,
    #[serde(default)]
    pub(crate) bid: WireValue<f64>,
    #[serde(rename = "bidSize")]
    #[serde(default)]
    pub(crate) bid_size: WireValue<JsonU64>,
    #[serde(default)]
    pub(crate) ask: WireValue<f64>,
    #[serde(rename = "askSize")]
    #[serde(default)]
    pub(crate) ask_size: WireValue<JsonU64>,
    #[serde(rename = "regularMarketTime")]
    #[serde(default)]
    pub(crate) regular_market_time: WireValue<i64>,
    #[serde(rename = "averageDailyVolume3Month")]
    #[serde(default)]
    pub(crate) average_daily_volume_3_month: WireValue<JsonU64>,
    #[serde(rename = "fiftyDayAverage")]
    #[serde(default)]
    pub(crate) fifty_day_average: WireValue<f64>,
    #[serde(rename = "twoHundredDayAverage")]
    #[serde(default)]
    pub(crate) two_hundred_day_average: WireValue<f64>,
    #[serde(rename = "fiftyTwoWeekHigh")]
    #[serde(default)]
    pub(crate) fifty_two_week_high: WireValue<f64>,
    #[serde(rename = "fiftyTwoWeekLow")]
    #[serde(default)]
    pub(crate) fifty_two_week_low: WireValue<f64>,
    #[serde(rename = "marketCap")]
    #[serde(default)]
    pub(crate) market_cap: WireValue<JsonDecimal>,
    #[serde(rename = "sharesOutstanding")]
    #[serde(default)]
    pub(crate) shares_outstanding: WireValue<JsonU64>,
    #[serde(rename = "epsTrailingTwelveMonths")]
    #[serde(default)]
    pub(crate) eps_trailing_twelve_months: WireValue<f64>,
    #[serde(rename = "trailingPE")]
    #[serde(default)]
    pub(crate) trailing_pe: WireValue<f64>,
    #[serde(rename = "trailingAnnualDividendYield")]
    #[serde(default)]
    pub(crate) trailing_annual_dividend_yield: WireValue<f64>,
    #[serde(rename = "dividendRate")]
    #[serde(default)]
    pub(crate) dividend_rate: WireValue<f64>,
    #[serde(rename = "dividendYield")]
    #[serde(default)]
    pub(crate) dividend_yield: WireValue<f64>,
    #[serde(default)]
    pub(crate) beta: WireValue<f64>,
    #[serde(rename = "dividendDate")]
    #[serde(default)]
    pub(crate) dividend_date: WireValue<i64>,
    #[serde(default)]
    pub(crate) currency: WireValue<String>,
    #[serde(rename = "financialCurrency")]
    #[serde(default)]
    pub(crate) financial_currency: WireValue<String>,
    #[serde(rename = "fullExchangeName")]
    #[serde(default)]
    pub(crate) full_exchange_name: WireValue<String>,
    #[serde(default)]
    pub(crate) exchange: WireValue<String>,
    #[serde(default)]
    pub(crate) market: WireValue<String>,
    #[serde(rename = "marketCapFigureExchange")]
    #[serde(default)]
    pub(crate) market_cap_figure_exchange: WireValue<String>,
    #[serde(rename = "marketState")]
    #[serde(default)]
    pub(crate) market_state: WireValue<String>,
}

fn required_wire_str_projection<'a>(
    value: &'a WireValue<String>,
    field: &'static str,
) -> Result<&'a str, ProjectionIssue> {
    match value {
        WireValue::Valid(value) => {
            nonempty(value).ok_or(ProjectionIssue::MissingRequiredField { field })
        }
        WireValue::Missing => Err(ProjectionIssue::MissingRequiredField { field }),
        WireValue::Invalid(details) => Err(ProjectionIssue::InvalidField {
            field,
            details: details.to_string(),
        }),
    }
}

struct V7KeyStatisticsFields {
    market_cap: Option<Decimal>,
    shares_outstanding: Option<u64>,
    eps_trailing_twelve_months: Option<f64>,
    trailing_pe: Option<f64>,
    dividend_rate: Option<f64>,
    trailing_annual_dividend_yield: Option<f64>,
    dividend_yield: Option<f64>,
    fifty_two_week_high: Option<f64>,
    fifty_two_week_low: Option<f64>,
    average_daily_volume_3m: Option<u64>,
    beta: Option<f64>,
}

impl V7QuoteNode {
    fn symbol_key(&self) -> Option<String> {
        self.symbol.as_ref().cloned()
    }

    fn currency_units(&self) -> QuoteCurrencyUnits {
        QuoteCurrencyUnits::from_quote_node(self)
    }

    fn exchange_candidates(&self) -> [(&'static str, Option<&str>); 4] {
        [
            ("fullExchangeName", self.full_exchange_name.as_str()),
            ("exchange", self.exchange.as_str()),
            ("market", self.market.as_str()),
            (
                "marketCapFigureExchange",
                self.market_cap_figure_exchange.as_str(),
            ),
        ]
    }

    fn exchange(&self) -> Option<Exchange> {
        first_parsed_yahoo_exchange(
            self.exchange_candidates()
                .into_iter()
                .map(|(_, value)| value),
        )
    }

    fn exchange_with_context(
        &self,
        ctx: &mut ProjectionContext,
        key: Option<&str>,
    ) -> Result<Option<Exchange>, YfError> {
        let candidates = [
            (
                "fullExchangeName",
                self.full_exchange_name
                    .optional_cloned(ctx, "fullExchangeName", key)?,
            ),
            (
                "exchange",
                self.exchange.optional_cloned(ctx, "exchange", key)?,
            ),
            ("market", self.market.optional_cloned(ctx, "market", key)?),
            (
                "marketCapFigureExchange",
                self.market_cap_figure_exchange.optional_cloned(
                    ctx,
                    "marketCapFigureExchange",
                    key,
                )?,
            ),
        ];
        let mut failures = Vec::new();
        for (path, value) in candidates {
            let Some(value) = value.as_deref().and_then(nonempty) else {
                continue;
            };
            match parse_yahoo_exchange(value) {
                Ok(parsed) => return Ok(Some(parsed)),
                Err(err) => failures.push(ExchangeCandidateFailure {
                    path,
                    value: value.to_string(),
                    reason: err.to_string(),
                }),
            }
        }

        if let Some(first) = failures.first() {
            ctx.omitted_present_field(
                first.path,
                key,
                ProjectionIssue::InvalidField {
                    field: first.path,
                    details: exchange_candidate_failure_details(&failures),
                },
            )?;
        }
        Ok(None)
    }

    fn instrument_projection(
        &self,
        exchange: Option<paft::domain::Exchange>,
    ) -> Result<Instrument, ProjectionIssue> {
        let sym = required_wire_str_projection(&self.symbol, "symbol")?;
        let quote_type = required_wire_str_projection(&self.quote_type, "quoteType")?;
        let kind =
            parse_yahoo_quote_type(quote_type).map_err(|err| ProjectionIssue::InvalidField {
                field: "quoteType",
                details: err.to_string(),
            })?;

        let instrument = match exchange {
            Some(ex) => Instrument::from_symbol_and_exchange(sym, ex, kind),
            None => Instrument::from_symbol(sym, kind),
        };

        instrument.map_err(|err| ProjectionIssue::InvalidField {
            field: "symbol",
            details: err.to_string(),
        })
    }

    fn instrument(&self, exchange: Option<paft::domain::Exchange>) -> Result<Instrument, YfError> {
        self.instrument_projection(exchange)
            .map_err(|issue| self.instrument_error(issue))
    }

    fn instrument_error(&self, issue: ProjectionIssue) -> YfError {
        match issue {
            ProjectionIssue::MissingRequiredField { field } => {
                YfError::MissingData(format!("v7 quote node missing {field}"))
            }
            ProjectionIssue::InvalidField {
                field: "symbol",
                details,
            } => YfError::InvalidData(format!(
                "invalid v7 quote symbol {:?}: {details}",
                self.symbol.as_str().unwrap_or_default()
            )),
            ProjectionIssue::InvalidField { field, details } => {
                YfError::InvalidData(format!("invalid v7 quote {field}: {details}"))
            }
            other => YfError::InvalidData(format!("invalid v7 quote instrument: {other}")),
        }
    }

    fn positive_book_level(
        &self,
        ctx: &mut ProjectionContext,
        path: &'static str,
        key: Option<&str>,
        price: Option<f64>,
        size: Option<u64>,
    ) -> Result<Option<BookLevel>, YfError> {
        let Some(price) = price.filter(|p| p.is_finite() && *p > 0.0) else {
            return Ok(None);
        };
        let price = self.currency_units().quote_price_amount(
            ctx,
            path,
            key,
            Some(price),
            "quote book level price",
        )?;
        Ok(price.map(|price| BookLevel::new(price, size.and_then(quantity_from_u64))))
    }

    fn market_state_with_context(
        &self,
        ctx: &mut ProjectionContext,
        key: Option<&str>,
    ) -> Result<Option<MarketState>, YfError> {
        let Some(value) = self
            .market_state
            .optional_cloned(ctx, "marketState", key)?
            .and_then(|value| nonempty(&value).map(str::to_owned))
        else {
            return Ok(None);
        };
        match value.as_str().parse() {
            Ok(state) => Ok(Some(state)),
            Err(err) => {
                ctx.omitted_present_field(
                    "marketState",
                    key,
                    ProjectionIssue::InvalidField {
                        field: "marketState",
                        details: err.to_string(),
                    },
                )?;
                Ok(None)
            }
        }
    }

    fn as_of_with_context(
        &self,
        ctx: &mut ProjectionContext,
        key: Option<&str>,
    ) -> Result<Option<chrono::DateTime<chrono::Utc>>, YfError> {
        let Some(timestamp) =
            self.regular_market_time
                .optional_copied(ctx, "regularMarketTime", key)?
        else {
            return Ok(None);
        };
        match i64_to_datetime(timestamp) {
            Ok(timestamp) => Ok(Some(timestamp)),
            Err(err) => {
                ctx.omitted_present_field(
                    "regularMarketTime",
                    key,
                    ProjectionIssue::InvalidField {
                        field: "regularMarketTime",
                        details: err.to_string(),
                    },
                )?;
                Ok(None)
            }
        }
    }

    pub(crate) fn to_snapshot_with_context(
        &self,
        ctx: &mut ProjectionContext,
    ) -> Result<Snapshot, YfError> {
        let key = self.symbol_key();
        let exchange = self.exchange_with_context(ctx, key.as_deref())?;
        let currencies = self.currency_units();
        let currency = currencies
            .quote_currency()
            .map_err(|issue| YfError::InvalidData(format!("invalid snapshot currency: {issue}")))?;
        let name = self
            .long_name
            .optional_cloned(ctx, "longName", key.as_deref())?
            .or(self
                .short_name
                .optional_cloned(ctx, "shortName", key.as_deref())?);
        let regular_market_price =
            self.regular_market_price
                .optional_copied(ctx, "regularMarketPrice", key.as_deref())?;
        let regular_market_previous_close = self.regular_market_previous_close.optional_copied(
            ctx,
            "regularMarketPreviousClose",
            key.as_deref(),
        )?;
        let regular_market_open =
            self.regular_market_open
                .optional_copied(ctx, "regularMarketOpen", key.as_deref())?;
        let regular_market_day_high = self.regular_market_day_high.optional_copied(
            ctx,
            "regularMarketDayHigh",
            key.as_deref(),
        )?;
        let regular_market_day_low = self.regular_market_day_low.optional_copied(
            ctx,
            "regularMarketDayLow",
            key.as_deref(),
        )?;
        let regular_market_volume = self.regular_market_volume.optional_copied_map(
            ctx,
            "regularMarketVolume",
            key.as_deref(),
            JsonU64::into_u64,
        )?;

        Ok(Snapshot {
            instrument: self.instrument(exchange)?,
            name,
            market_state: self.market_state_with_context(ctx, key.as_deref())?,
            as_of: self.as_of_with_context(ctx, key.as_deref())?,
            currency,
            last: currencies.quote_price_amount(
                ctx,
                "regularMarketPrice",
                key.as_deref(),
                regular_market_price,
                "snapshot last price",
            )?,
            previous_close: currencies.quote_price_amount(
                ctx,
                "regularMarketPreviousClose",
                key.as_deref(),
                regular_market_previous_close,
                "snapshot previous close",
            )?,
            open: currencies.quote_price_amount(
                ctx,
                "regularMarketOpen",
                key.as_deref(),
                regular_market_open,
                "snapshot open",
            )?,
            day_high: currencies.quote_price_amount(
                ctx,
                "regularMarketDayHigh",
                key.as_deref(),
                regular_market_day_high,
                "snapshot day high",
            )?,
            day_low: currencies.quote_price_amount(
                ctx,
                "regularMarketDayLow",
                key.as_deref(),
                regular_market_day_low,
                "snapshot day low",
            )?,
            volume: regular_market_volume.and_then(quantity_from_u64),
            provider: (),
        })
    }

    pub(crate) fn to_fast_info_with_context(
        &self,
        ctx: &mut ProjectionContext,
    ) -> Result<FastInfo, YfError> {
        Ok(FastInfo {
            snapshot: self.to_snapshot_with_context(ctx)?,
            moving_averages: self.to_moving_averages_with_context(ctx)?,
        })
    }

    pub(crate) fn to_moving_averages_with_context(
        &self,
        ctx: &mut ProjectionContext,
    ) -> Result<MovingAverages, YfError> {
        let key = self.symbol_key();
        let currencies = self.currency_units();
        let fifty_day =
            self.fifty_day_average
                .optional_copied(ctx, "fiftyDayAverage", key.as_deref())?;
        let two_hundred_day = self.two_hundred_day_average.optional_copied(
            ctx,
            "twoHundredDayAverage",
            key.as_deref(),
        )?;

        Ok(MovingAverages {
            fifty_day: currencies.quote_price(
                ctx,
                "fiftyDayAverage",
                key.as_deref(),
                fifty_day,
                "50-day moving average",
            )?,
            two_hundred_day: currencies.quote_price(
                ctx,
                "twoHundredDayAverage",
                key.as_deref(),
                two_hundred_day,
                "200-day moving average",
            )?,
        })
    }

    pub(crate) fn to_key_statistics_with_context(
        &self,
        ctx: &mut ProjectionContext,
    ) -> Result<KeyStatistics, YfError> {
        let currencies = self.currency_units();
        let key = self.symbol_key();
        let fields = self.key_statistics_fields(ctx, key.as_deref())?;

        Ok(KeyStatistics {
            as_of: self.as_of_with_context(ctx, key.as_deref())?,
            market_cap: currencies.quote_money(
                ctx,
                "marketCap",
                key.as_deref(),
                fields.market_cap,
                "market cap",
            )?,
            shares_outstanding: fields.shares_outstanding,
            eps_trailing_twelve_months: currencies.financial_price(
                ctx,
                "epsTrailingTwelveMonths",
                key.as_deref(),
                fields.eps_trailing_twelve_months,
                "trailing EPS",
            )?,
            pe_trailing_twelve_months: optional_decimal_f64(
                ctx,
                "trailingPE",
                key.as_deref(),
                fields.trailing_pe,
                "trailing PE",
            )?,
            dividend_per_share_forward: currencies.quote_major_price(
                ctx,
                "dividendRate",
                key.as_deref(),
                fields.dividend_rate,
                "forward dividend per share",
            )?,
            dividend_yield_trailing: optional_decimal_f64(
                ctx,
                "trailingAnnualDividendYield",
                key.as_deref(),
                fields.trailing_annual_dividend_yield,
                "trailing dividend yield",
            )?,
            // Yahoo v7 returns trailingAnnualDividendYield as a decimal fraction,
            // but dividendYield as percent points. Keep this asymmetry fixture-locked.
            dividend_yield_forward: optional_decimal_f64(
                ctx,
                "dividendYield",
                key.as_deref(),
                fields.dividend_yield,
                "forward dividend yield",
            )?
            .map(|value| value / Decimal::from(100)),
            ex_dividend_date: None,
            fifty_two_week_high: currencies.quote_price(
                ctx,
                "fiftyTwoWeekHigh",
                key.as_deref(),
                fields.fifty_two_week_high,
                "52-week high",
            )?,
            fifty_two_week_low: currencies.quote_price(
                ctx,
                "fiftyTwoWeekLow",
                key.as_deref(),
                fields.fifty_two_week_low,
                "52-week low",
            )?,
            average_daily_volume_3m: fields.average_daily_volume_3m,
            beta: optional_decimal_f64(ctx, "beta", key.as_deref(), fields.beta, "beta")?,
        })
    }

    fn key_statistics_fields(
        &self,
        ctx: &mut ProjectionContext,
        key: Option<&str>,
    ) -> Result<V7KeyStatisticsFields, YfError> {
        Ok(V7KeyStatisticsFields {
            market_cap: self.market_cap.optional_copied_map(
                ctx,
                "marketCap",
                key,
                JsonDecimal::into_decimal,
            )?,
            shares_outstanding: self.shares_outstanding.optional_copied_map(
                ctx,
                "sharesOutstanding",
                key,
                JsonU64::into_u64,
            )?,
            eps_trailing_twelve_months: self.eps_trailing_twelve_months.optional_copied(
                ctx,
                "epsTrailingTwelveMonths",
                key,
            )?,
            trailing_pe: self.trailing_pe.optional_copied(ctx, "trailingPE", key)?,
            dividend_rate: self
                .dividend_rate
                .optional_copied(ctx, "dividendRate", key)?,
            trailing_annual_dividend_yield: self.trailing_annual_dividend_yield.optional_copied(
                ctx,
                "trailingAnnualDividendYield",
                key,
            )?,
            dividend_yield: self
                .dividend_yield
                .optional_copied(ctx, "dividendYield", key)?,
            fifty_two_week_high: self.fifty_two_week_high.optional_copied(
                ctx,
                "fiftyTwoWeekHigh",
                key,
            )?,
            fifty_two_week_low: self.fifty_two_week_low.optional_copied(
                ctx,
                "fiftyTwoWeekLow",
                key,
            )?,
            average_daily_volume_3m: self.average_daily_volume_3_month.optional_copied_map(
                ctx,
                "averageDailyVolume3Month",
                key,
                JsonU64::into_u64,
            )?,
            beta: self.beta.optional_copied(ctx, "beta", key)?,
        })
    }

    pub(crate) fn calendar_fallback_with_context(
        &self,
        ctx: &mut ProjectionContext,
    ) -> Result<Option<Calendar>, YfError> {
        let key = self.symbol_key();
        let Some(timestamp) =
            self.dividend_date
                .optional_copied(ctx, "dividendDate", key.as_deref())?
        else {
            return Ok(None);
        };
        match i64_to_date(timestamp) {
            Ok(date) => Ok(Some(Calendar {
                earnings_dates: Vec::new(),
                ex_dividend_date: None,
                dividend_payment_date: Some(date),
            })),
            Err(err) => {
                ctx.omitted_present_field(
                    "dividendDate",
                    key.as_deref(),
                    ProjectionIssue::InvalidField {
                        field: "dividendDate",
                        details: err.to_string(),
                    },
                )?;
                Ok(None)
            }
        }
    }
}

struct ExchangeCandidateFailure {
    path: &'static str,
    value: String,
    reason: String,
}

fn exchange_candidate_failure_details(failures: &[ExchangeCandidateFailure]) -> String {
    let mut details = String::from("no exchange candidate parsed");
    for failure in failures {
        let _ = write!(
            details,
            "; {}={:?}: {}",
            failure.path, failure.value, failure.reason
        );
    }
    details
}

#[derive(Clone)]
struct QuoteCurrencyUnits {
    quote: Option<ResolvedCurrencyUnit>,
    quote_issue: Option<ProjectionIssue>,
    quote_major: Option<ResolvedCurrencyUnit>,
    financial: Option<ResolvedCurrencyUnit>,
    financial_issue: Option<ProjectionIssue>,
}

impl QuoteCurrencyUnits {
    fn from_quote_node(node: &V7QuoteNode) -> Self {
        let (quote, quote_issue) = parse_currency_unit(
            node.currency.as_str(),
            node.currency.invalid_details(),
            "currency",
            false,
        );
        let quote_major = quote.as_ref().map(ResolvedCurrencyUnit::major_unit);
        let (financial, financial_issue) = node.financial_currency.invalid_details().map_or_else(
            || {
                node.financial_currency
                    .as_str()
                    .and_then(nonempty)
                    .map_or_else(
                        || (quote_major.clone(), quote_issue.clone()),
                        |code| parse_currency_unit(Some(code), None, "financialCurrency", true),
                    )
            },
            |details| parse_currency_unit(None, Some(details), "financialCurrency", true),
        );

        Self {
            quote,
            quote_issue,
            quote_major,
            financial,
            financial_issue,
        }
    }

    fn from_quote_summary_currency(currency: Option<&str>) -> Self {
        let (quote, quote_issue) = parse_currency_unit(currency, None, "currency", false);
        let quote_major = quote.as_ref().map(ResolvedCurrencyUnit::major_unit);
        let financial = quote_major.clone();

        Self {
            quote,
            quote_issue: quote_issue.clone(),
            quote_major,
            financial,
            financial_issue: quote_issue,
        }
    }

    fn quote_price(
        &self,
        ctx: &mut ProjectionContext,
        path: &'static str,
        key: Option<&str>,
        value: Option<f64>,
        target: &'static str,
    ) -> Result<Option<paft::money::Price>, YfError> {
        optional_with_unit(
            ctx,
            path,
            key,
            self.quote_unit(),
            value,
            target,
            ResolvedCurrencyUnit::price_from_f64,
        )
    }

    fn quote_price_amount(
        &self,
        ctx: &mut ProjectionContext,
        path: &'static str,
        key: Option<&str>,
        value: Option<f64>,
        target: &'static str,
    ) -> Result<Option<PriceAmount>, YfError> {
        optional_with_unit(
            ctx,
            path,
            key,
            self.quote_unit(),
            value,
            target,
            ResolvedCurrencyUnit::price_amount_from_f64,
        )
    }

    fn quote_money(
        &self,
        ctx: &mut ProjectionContext,
        path: &'static str,
        key: Option<&str>,
        value: Option<Decimal>,
        target: &'static str,
    ) -> Result<Option<paft::money::Money>, YfError> {
        optional_with_unit(
            ctx,
            path,
            key,
            self.quote_major_unit(),
            value,
            target,
            |unit, value| unit.money_from_decimal(value).ok(),
        )
    }

    fn quote_major_price(
        &self,
        ctx: &mut ProjectionContext,
        path: &'static str,
        key: Option<&str>,
        value: Option<f64>,
        target: &'static str,
    ) -> Result<Option<paft::money::Price>, YfError> {
        optional_with_unit(
            ctx,
            path,
            key,
            self.quote_major_unit(),
            value,
            target,
            ResolvedCurrencyUnit::price_from_f64,
        )
    }

    fn financial_price(
        &self,
        ctx: &mut ProjectionContext,
        path: &'static str,
        key: Option<&str>,
        value: Option<f64>,
        target: &'static str,
    ) -> Result<Option<paft::money::Price>, YfError> {
        optional_with_unit(
            ctx,
            path,
            key,
            self.financial_unit(),
            value,
            target,
            ResolvedCurrencyUnit::price_from_f64,
        )
    }

    fn quote_unit(&self) -> Result<&ResolvedCurrencyUnit, ProjectionIssue> {
        self.quote.as_ref().ok_or_else(|| self.quote_issue())
    }

    fn quote_currency(&self) -> Result<Currency, ProjectionIssue> {
        self.quote_unit().map(|unit| unit.currency().clone())
    }

    fn quote_major_unit(&self) -> Result<&ResolvedCurrencyUnit, ProjectionIssue> {
        self.quote_major.as_ref().ok_or_else(|| self.quote_issue())
    }

    fn financial_unit(&self) -> Result<&ResolvedCurrencyUnit, ProjectionIssue> {
        self.financial.as_ref().ok_or_else(|| {
            self.financial_issue
                .clone()
                .unwrap_or(ProjectionIssue::CurrencyUnresolved)
        })
    }

    fn quote_issue(&self) -> ProjectionIssue {
        self.quote_issue
            .clone()
            .unwrap_or(ProjectionIssue::CurrencyUnresolved)
    }
}

fn nonempty(value: &str) -> Option<&str> {
    let value = value.trim();
    (!value.is_empty()).then_some(value)
}

fn parse_currency_unit(
    code: Option<&str>,
    invalid_details: Option<Cow<'_, str>>,
    field: &'static str,
    major: bool,
) -> (Option<ResolvedCurrencyUnit>, Option<ProjectionIssue>) {
    if let Some(details) = invalid_details {
        return (
            None,
            Some(ProjectionIssue::InvalidField {
                field,
                details: details.to_string(),
            }),
        );
    }

    let Some(code) = code.and_then(nonempty) else {
        return (None, None);
    };
    let unit = if major {
        ResolvedCurrencyUnit::major_from_code(code)
    } else {
        ResolvedCurrencyUnit::from_code(code)
    };
    unit.map_or_else(
        || {
            (
                None,
                Some(ProjectionIssue::InvalidCurrency {
                    code: code.to_string(),
                }),
            )
        },
        |unit| (Some(unit), None),
    )
}

fn optional_with_unit<T, U>(
    ctx: &mut ProjectionContext,
    path: &'static str,
    key: Option<&str>,
    unit: Result<&ResolvedCurrencyUnit, ProjectionIssue>,
    value: Option<T>,
    target: &'static str,
    convert: impl FnOnce(&ResolvedCurrencyUnit, T) -> Option<U>,
) -> Result<Option<U>, YfError> {
    let Some(value) = value else {
        return Ok(None);
    };
    let unit = match unit {
        Ok(unit) => unit,
        Err(issue) => {
            ctx.omitted_present_field(path, key, issue)?;
            return Ok(None);
        }
    };
    let Some(converted) = convert(unit, value) else {
        ctx.omitted_present_field(path, key, ProjectionIssue::ConversionFailed { target })?;
        return Ok(None);
    };
    Ok(Some(converted))
}

#[derive(Deserialize)]
pub struct QuoteSummaryKeyStatistics {
    #[serde(rename = "summaryDetail")]
    summary_detail: Option<SummaryDetailNode>,
    #[serde(rename = "defaultKeyStatistics")]
    default_key_statistics: Option<DefaultKeyStatisticsNode>,
}

#[derive(Default, Deserialize)]
struct SummaryDetailNode {
    #[serde(default)]
    currency: WireValue<String>,
    #[serde(default)]
    beta: WireValue<RawNum<f64>>,
    #[serde(rename = "marketCap")]
    #[serde(default)]
    market_cap: WireValue<RawDecimal>,
    #[serde(rename = "trailingPE")]
    #[serde(default)]
    trailing_pe: WireValue<RawNum<f64>>,
    #[serde(rename = "dividendRate")]
    #[serde(default)]
    dividend_rate: WireValue<RawNum<f64>>,
    #[serde(rename = "dividendYield")]
    #[serde(default)]
    dividend_yield: WireValue<RawNum<f64>>,
    #[serde(rename = "trailingAnnualDividendYield")]
    #[serde(default)]
    trailing_annual_dividend_yield: WireValue<RawNum<f64>>,
    #[serde(rename = "exDividendDate")]
    #[serde(default)]
    ex_dividend_date: WireValue<RawDate>,
    #[serde(rename = "fiftyDayAverage")]
    #[serde(default)]
    fifty_day_average: WireValue<RawNum<f64>>,
    #[serde(rename = "twoHundredDayAverage")]
    #[serde(default)]
    two_hundred_day_average: WireValue<RawNum<f64>>,
    #[serde(rename = "fiftyTwoWeekHigh")]
    #[serde(default)]
    fifty_two_week_high: WireValue<RawNum<f64>>,
    #[serde(rename = "fiftyTwoWeekLow")]
    #[serde(default)]
    fifty_two_week_low: WireValue<RawNum<f64>>,
    #[serde(rename = "averageVolume")]
    #[serde(default)]
    average_volume: WireValue<RawNumU64>,
}

#[derive(Default, Deserialize)]
struct DefaultKeyStatisticsNode {
    #[serde(default)]
    beta: WireValue<RawNum<f64>>,
    #[serde(rename = "sharesOutstanding")]
    #[serde(default)]
    shares_outstanding: WireValue<RawNumU64>,
    #[serde(rename = "trailingEps")]
    #[serde(default)]
    trailing_eps: WireValue<RawNum<f64>>,
}

struct QuoteSummaryKeyStatisticsFields {
    summary_currency: Option<String>,
    beta: Option<f64>,
    fifty_day_average: Option<f64>,
    two_hundred_day_average: Option<f64>,
    market_cap: Option<Decimal>,
    shares_outstanding: Option<u64>,
    trailing_eps: Option<f64>,
    trailing_pe: Option<f64>,
    dividend_rate: Option<f64>,
    trailing_annual_dividend_yield: Option<f64>,
    dividend_yield: Option<f64>,
    ex_dividend_date: Option<i64>,
    fifty_two_week_high: Option<f64>,
    fifty_two_week_low: Option<f64>,
    average_volume: Option<u64>,
}

fn quote_summary_key_statistics_fields(
    ctx: &mut ProjectionContext,
    key: Option<&str>,
    summary_detail: &SummaryDetailNode,
    default_key_statistics: &DefaultKeyStatisticsNode,
) -> Result<QuoteSummaryKeyStatisticsFields, YfError> {
    let summary_beta =
        summary_detail
            .beta
            .optional_copied_and_then(ctx, "summaryDetail.beta", key, |raw| raw.raw)?;
    let default_beta = default_key_statistics.beta.optional_copied_and_then(
        ctx,
        "defaultKeyStatistics.beta",
        key,
        |raw| raw.raw,
    )?;

    Ok(QuoteSummaryKeyStatisticsFields {
        summary_currency: summary_detail.currency.optional_cloned(
            ctx,
            "summaryDetail.currency",
            key,
        )?,
        beta: summary_beta.or(default_beta),
        fifty_day_average: summary_detail.fifty_day_average.optional_copied_and_then(
            ctx,
            "summaryDetail.fiftyDayAverage",
            key,
            |raw| raw.raw,
        )?,
        two_hundred_day_average: summary_detail
            .two_hundred_day_average
            .optional_copied_and_then(ctx, "summaryDetail.twoHundredDayAverage", key, |raw| {
                raw.raw
            })?,
        market_cap: summary_detail.market_cap.optional_copied_and_then(
            ctx,
            "summaryDetail.marketCap",
            key,
            |raw| raw.raw,
        )?,
        shares_outstanding: default_key_statistics
            .shares_outstanding
            .optional_copied_and_then(
                ctx,
                "defaultKeyStatistics.sharesOutstanding",
                key,
                |raw| raw.raw,
            )?,
        trailing_eps: default_key_statistics
            .trailing_eps
            .optional_copied_and_then(ctx, "defaultKeyStatistics.trailingEps", key, |raw| {
                raw.raw
            })?,
        trailing_pe: summary_detail.trailing_pe.optional_copied_and_then(
            ctx,
            "summaryDetail.trailingPE",
            key,
            |raw| raw.raw,
        )?,
        dividend_rate: summary_detail.dividend_rate.optional_copied_and_then(
            ctx,
            "summaryDetail.dividendRate",
            key,
            |raw| raw.raw,
        )?,
        trailing_annual_dividend_yield: summary_detail
            .trailing_annual_dividend_yield
            .optional_copied_and_then(
                ctx,
                "summaryDetail.trailingAnnualDividendYield",
                key,
                |raw| raw.raw,
            )?,
        dividend_yield: summary_detail.dividend_yield.optional_copied_and_then(
            ctx,
            "summaryDetail.dividendYield",
            key,
            |raw| raw.raw,
        )?,
        ex_dividend_date: summary_detail.ex_dividend_date.optional_copied_and_then(
            ctx,
            "summaryDetail.exDividendDate",
            key,
            |raw| raw.raw,
        )?,
        fifty_two_week_high: summary_detail
            .fifty_two_week_high
            .optional_copied_and_then(ctx, "summaryDetail.fiftyTwoWeekHigh", key, |raw| raw.raw)?,
        fifty_two_week_low: summary_detail.fifty_two_week_low.optional_copied_and_then(
            ctx,
            "summaryDetail.fiftyTwoWeekLow",
            key,
            |raw| raw.raw,
        )?,
        average_volume: summary_detail.average_volume.optional_copied_and_then(
            ctx,
            "summaryDetail.averageVolume",
            key,
            |raw| raw.raw,
        )?,
    })
}

impl QuoteSummaryKeyStatistics {
    pub fn into_key_statistics_and_moving_averages_with_context(
        self,
        ctx: &mut ProjectionContext,
        symbol: &str,
    ) -> Result<(KeyStatistics, MovingAverages), YfError> {
        let key = Some(symbol);
        let summary_detail = self.summary_detail.unwrap_or_default();
        let default_key_statistics = self.default_key_statistics.unwrap_or_default();
        let fields = quote_summary_key_statistics_fields(
            ctx,
            key,
            &summary_detail,
            &default_key_statistics,
        )?;
        let currencies =
            QuoteCurrencyUnits::from_quote_summary_currency(fields.summary_currency.as_deref());
        let moving_averages = MovingAverages {
            fifty_day: currencies.quote_price(
                ctx,
                "summaryDetail.fiftyDayAverage",
                key,
                fields.fifty_day_average,
                "50-day moving average",
            )?,
            two_hundred_day: currencies.quote_price(
                ctx,
                "summaryDetail.twoHundredDayAverage",
                key,
                fields.two_hundred_day_average,
                "200-day moving average",
            )?,
        };

        let key_statistics = KeyStatistics {
            market_cap: currencies.quote_money(
                ctx,
                "summaryDetail.marketCap",
                key,
                fields.market_cap,
                "market cap",
            )?,
            shares_outstanding: fields.shares_outstanding,
            eps_trailing_twelve_months: currencies.financial_price(
                ctx,
                "defaultKeyStatistics.trailingEps",
                key,
                fields.trailing_eps,
                "trailing EPS",
            )?,
            pe_trailing_twelve_months: optional_decimal_f64(
                ctx,
                "summaryDetail.trailingPE",
                key,
                fields.trailing_pe,
                "trailing PE",
            )?,
            dividend_per_share_forward: currencies.quote_major_price(
                ctx,
                "summaryDetail.dividendRate",
                key,
                fields.dividend_rate,
                "forward dividend per share",
            )?,
            dividend_yield_trailing: optional_decimal_f64(
                ctx,
                "summaryDetail.trailingAnnualDividendYield",
                key,
                fields.trailing_annual_dividend_yield,
                "trailing dividend yield",
            )?,
            dividend_yield_forward: optional_decimal_f64(
                ctx,
                "summaryDetail.dividendYield",
                key,
                fields.dividend_yield,
                "forward dividend yield",
            )?,
            ex_dividend_date: optional_date(
                ctx,
                "summaryDetail.exDividendDate",
                key,
                fields.ex_dividend_date,
            )?,
            fifty_two_week_high: currencies.quote_price(
                ctx,
                "summaryDetail.fiftyTwoWeekHigh",
                key,
                fields.fifty_two_week_high,
                "52-week high",
            )?,
            fifty_two_week_low: currencies.quote_price(
                ctx,
                "summaryDetail.fiftyTwoWeekLow",
                key,
                fields.fifty_two_week_low,
                "52-week low",
            )?,
            average_daily_volume_3m: fields.average_volume,
            beta: optional_decimal_f64(ctx, "beta", Some(symbol), fields.beta, "beta")?,
            as_of: None,
        };

        Ok((key_statistics, moving_averages))
    }

    pub fn into_key_statistics_with_context(
        self,
        ctx: &mut ProjectionContext,
        symbol: &str,
    ) -> Result<KeyStatistics, YfError> {
        Ok(self
            .into_key_statistics_and_moving_averages_with_context(ctx, symbol)?
            .0)
    }
}

fn optional_date(
    ctx: &mut ProjectionContext,
    path: &'static str,
    key: Option<&str>,
    timestamp: Option<i64>,
) -> Result<Option<chrono::NaiveDate>, YfError> {
    let Some(timestamp) = timestamp else {
        return Ok(None);
    };

    match i64_to_date(timestamp) {
        Ok(date) => Ok(Some(date)),
        Err(err) => {
            ctx.omitted_present_field(
                path,
                key,
                ProjectionIssue::InvalidField {
                    field: path,
                    details: err.to_string(),
                },
            )?;
            Ok(None)
        }
    }
}

pub fn quote_summary_key_statistics_from_raw(
    raw: &serde_json::value::RawValue,
) -> Result<QuoteSummaryKeyStatistics, YfError> {
    serde_json::from_str(raw.get()).map_err(YfError::json)
}

pub fn merge_key_statistics(
    mut base: KeyStatistics,
    quote_summary: &KeyStatistics,
) -> KeyStatistics {
    if base.market_cap.is_none() {
        base.market_cap.clone_from(&quote_summary.market_cap);
    }
    if base.shares_outstanding.is_none() {
        base.shares_outstanding = quote_summary.shares_outstanding;
    }
    if base.eps_trailing_twelve_months.is_none() {
        base.eps_trailing_twelve_months
            .clone_from(&quote_summary.eps_trailing_twelve_months);
    }
    if base.pe_trailing_twelve_months.is_none() {
        base.pe_trailing_twelve_months = quote_summary.pe_trailing_twelve_months;
    }
    if base.dividend_per_share_forward.is_none() {
        base.dividend_per_share_forward
            .clone_from(&quote_summary.dividend_per_share_forward);
    }
    if base.dividend_yield_trailing.is_none() {
        base.dividend_yield_trailing = quote_summary.dividend_yield_trailing;
    }
    if base.dividend_yield_forward.is_none() {
        base.dividend_yield_forward = quote_summary.dividend_yield_forward;
    }
    if base.ex_dividend_date.is_none() {
        base.ex_dividend_date = quote_summary.ex_dividend_date;
    }
    if base.fifty_two_week_high.is_none() {
        base.fifty_two_week_high
            .clone_from(&quote_summary.fifty_two_week_high);
    }
    if base.fifty_two_week_low.is_none() {
        base.fifty_two_week_low
            .clone_from(&quote_summary.fifty_two_week_low);
    }
    if base.average_daily_volume_3m.is_none() {
        base.average_daily_volume_3m = quote_summary.average_daily_volume_3m;
    }
    if base.beta.is_none() {
        base.beta = quote_summary.beta;
    }
    base
}

pub fn merge_moving_averages(
    mut base: MovingAverages,
    quote_summary: &MovingAverages,
) -> MovingAverages {
    if base.fifty_day.is_none() {
        base.fifty_day.clone_from(&quote_summary.fifty_day);
    }
    if base.two_hundred_day.is_none() {
        base.two_hundred_day
            .clone_from(&quote_summary.two_hundred_day);
    }
    base
}

pub async fn fetch_quote_summary_key_statistics(
    client: &YfClient,
    symbol: &str,
    options: &CallOptions,
) -> Result<QuoteSummaryKeyStatistics, YfError> {
    let body = quotesummary::fetch_body(
        client,
        symbol,
        KEY_STATISTICS_MODULES,
        "key_statistics",
        options,
    )
    .await?;

    quotesummary::parse_module_result(&body)
}

/// Centralized function to fetch one or more quotes from the v7 API.
/// It handles caching, retries, and authentication (crumb).
pub async fn fetch_v7_quotes(
    client: &YfClient,
    symbols: &[&str],
    options: &CallOptions,
) -> Result<Vec<V7QuoteNode>, YfError> {
    let values = fetch_v7_quote_values(client, symbols, options).await?;
    let mut ctx = ProjectionContext::new("quote_v7", options.data_quality());
    report_missing_requested_quote_values(symbols, &values, &mut ctx)?;
    quote_nodes_from_values_with_context(client, symbols, values, &mut ctx)
}

pub fn report_missing_requested_quote_values(
    requested_symbols: &[&str],
    values: &[Value],
    ctx: &mut ProjectionContext,
) -> Result<(), YfError> {
    let normalized_symbols = normalize_symbols(requested_symbols.iter().copied())?;
    let requested_symbols = normalized_symbols
        .iter()
        .map(String::as_str)
        .collect::<Vec<_>>();
    let mut resolved_requests = vec![false; requested_symbols.len()];

    for value in values {
        let provider_symbol = value
            .get("symbol")
            .and_then(serde_json::Value::as_str)
            .and_then(|symbol| nonempty_symbol(Some(symbol)));
        mark_resolved_requested_symbol(&requested_symbols, &mut resolved_requests, provider_symbol);
    }

    for (symbol, resolved) in requested_symbols.iter().zip(resolved_requests) {
        if !resolved {
            ctx.dropped_item(
                "quote",
                Some(*symbol),
                ProjectionIssue::ProviderUnavailable { feature: "quote" },
            )?;
        }
    }

    Ok(())
}

/// Centralized function to fetch raw quote values from the v7 API.
/// Projection callers can then choose strict or best-effort node conversion.
pub async fn fetch_v7_quote_values(
    client: &YfClient,
    symbols: &[&str],
    options: &CallOptions,
) -> Result<Vec<Value>, YfError> {
    if symbols.is_empty() {
        return Err(YfError::InvalidParams(
            "symbols list cannot be empty".into(),
        ));
    }

    let normalized_symbols = normalize_symbols(symbols.iter().copied())?;
    let chunks = chunk_v7_quote_symbols(client.base_quote_v7(), normalized_symbols)?;

    let mut chunk_values: Vec<_> = stream::iter(chunks.into_iter().enumerate())
        .map(|(index, symbols)| async move {
            let values = fetch_v7_quote_chunk(client, &symbols, options).await?;
            Ok::<_, YfError>((index, values))
        })
        .buffer_unordered(MAX_V7_QUOTE_CONCURRENT_REQUESTS)
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .collect::<Result<_, _>>()?;

    chunk_values.sort_unstable_by_key(|(index, _)| *index);
    let total_len = chunk_values.iter().map(|(_, values)| values.len()).sum();
    let mut values = Vec::with_capacity(total_len);
    for (_, mut chunk) in chunk_values {
        values.append(&mut chunk);
    }

    Ok(values)
}

fn chunk_v7_quote_symbols(
    base_url: &Url,
    normalized_symbols: Vec<String>,
) -> Result<Vec<Vec<String>>, YfError> {
    let mut chunks = Vec::new();
    let mut current = Vec::new();

    for symbol in normalized_symbols {
        let mut candidate = current.clone();
        candidate.push(symbol.clone());

        if candidate.len() > MAX_V7_QUOTE_SYMBOLS_PER_REQUEST
            || v7_quote_url(&candidate, base_url).as_str().len() > MAX_V7_QUOTE_URL_BYTES
        {
            if current.is_empty() {
                return Err(YfError::InvalidParams(format!(
                    "symbol {symbol:?} makes v7 quote URL exceed {MAX_V7_QUOTE_URL_BYTES} bytes"
                )));
            }

            chunks.push(std::mem::take(&mut current));
            current.push(symbol);
        } else {
            current = candidate;
        }
    }

    if !current.is_empty() {
        chunks.push(current);
    }

    Ok(chunks)
}

async fn fetch_v7_quote_chunk(
    client: &YfClient,
    normalized_symbols: &[String],
    options: &CallOptions,
) -> Result<Vec<Value>, YfError> {
    let url = v7_quote_url(normalized_symbols, client.base_quote_v7());
    let fixture_key = normalized_symbols.join("-");

    let (body_to_parse, _) = net::fetch_text_with_auth_retry(
        client,
        url,
        net::AuthFetchConfig {
            auth_mode: net::AuthMode::OptionalCrumb,
            cache_endpoint: CacheEndpoint::Quote,
            options,
            cache_body: None,
            endpoint: "quote_v7",
            fixture_key: &fixture_key,
            ext: "json",
            retry_on_invalid_crumb_body: true,
            cache_validator: Some(validate_v7_quote_body),
        },
        |url| client.http().get(url).header("accept", "application/json"),
    )
    .await?;

    let env: V7Envelope = serde_json::from_str(&body_to_parse).map_err(YfError::json)?;
    let quote_response = env
        .quote_response
        .ok_or_else(|| YfError::MissingData("v7 quoteResponse missing".into()))?;
    reject_v7_quote_error(&quote_response)?;

    let nodes = quote_response
        .result
        .ok_or_else(|| YfError::MissingData("v7 quoteResponse.result missing".into()))?;

    Ok(nodes)
}

fn v7_quote_url(normalized_symbols: &[String], base_url: &Url) -> Url {
    let mut url = base_url.clone();
    url.query_pairs_mut()
        .append_pair("symbols", &normalized_symbols.join(","));
    url
}

fn validate_v7_quote_body(body: &str) -> Result<(), YfError> {
    let env: V7Envelope = serde_json::from_str(body).map_err(YfError::json)?;
    let quote_response = env
        .quote_response
        .ok_or_else(|| YfError::MissingData("v7 quoteResponse missing".into()))?;
    reject_v7_quote_error(&quote_response)
}

fn reject_v7_quote_error(quote_response: &V7QuoteResponse) -> Result<(), YfError> {
    if let Some(error) = quote_response.error.as_ref() {
        crate::core::logging::trace_error!(
            description = %error.description,
            "quoteResponse error"
        );
        return Err(YfError::Api(format!("yahoo error: {}", error.description)));
    }

    Ok(())
}

pub fn quote_nodes_from_values_with_context(
    client: &YfClient,
    requested_symbols: &[&str],
    values: Vec<Value>,
    ctx: &mut ProjectionContext,
) -> Result<Vec<V7QuoteNode>, YfError> {
    let mut nodes = Vec::with_capacity(values.len());
    for (idx, value) in values.into_iter().enumerate() {
        if let Some(node) = quote_node_from_value_with_context(value, idx, ctx)? {
            nodes.push(node);
        }
    }
    store_v7_quote_side_effects(client, requested_symbols, &nodes);
    Ok(nodes)
}

fn quote_node_from_value_with_context(
    value: Value,
    idx: usize,
    ctx: &mut ProjectionContext,
) -> Result<Option<V7QuoteNode>, YfError> {
    let key = Some(quote_node_diag_key_from_value(&value, idx));
    match serde_json::from_value(value) {
        Ok(node) => Ok(Some(node)),
        Err(err) => {
            ctx.dropped_item(
                "quote",
                key.as_deref(),
                ProjectionIssue::InvalidField {
                    field: "quote",
                    details: err.to_string(),
                },
            )?;
            Ok(None)
        }
    }
}

pub fn first_quote_node_from_nodes(nodes: Vec<V7QuoteNode>) -> Option<V7QuoteNode> {
    nodes.into_iter().next()
}

pub fn required_quote_node_from_nodes(
    nodes: Vec<V7QuoteNode>,
    symbol: &str,
) -> Result<V7QuoteNode, YfError> {
    first_quote_node_from_nodes(nodes).ok_or_else(|| {
        YfError::MissingData(format!("no valid quote result found for symbol {symbol}"))
    })
}

fn quote_node_diag_key_from_value(value: &Value, idx: usize) -> String {
    value
        .get("symbol")
        .and_then(serde_json::Value::as_str)
        .map(str::trim)
        .filter(|symbol| !symbol.is_empty())
        .map_or_else(|| format!("result[{idx}]"), ToString::to_string)
}

fn store_v7_quote_side_effects(
    client: &YfClient,
    requested_symbols: &[&str],
    nodes: &[V7QuoteNode],
) {
    let mut resolved_requests = vec![false; requested_symbols.len()];

    for node in nodes {
        let provider_symbol = nonempty_symbol(node.symbol.as_str());
        if let Some(symbol) = provider_symbol {
            store_quote_node_hints(client, symbol, node);
            store_requested_alias_hints(client, requested_symbols, symbol, node);
            store_quote_node_instrument(client, symbol, node);
        }

        mark_resolved_requested_symbol(requested_symbols, &mut resolved_requests, provider_symbol);

        if requested_symbols.len() == 1
            && provider_symbol.is_none_or(|symbol| !same_symbol(symbol, requested_symbols[0]))
        {
            store_quote_node_hints(client, requested_symbols[0], node);
        }
    }

    for (symbol, resolved) in requested_symbols.iter().zip(resolved_requests) {
        if !resolved {
            client.store_currency_hints(
                symbol,
                CurrencyHints::from_quote(None, None, None, None, None),
            );
        }
    }
}

fn store_quote_node_hints(client: &YfClient, symbol: &str, node: &V7QuoteNode) {
    client.store_currency_hints(
        symbol,
        CurrencyHints::from_quote(
            node.currency.as_str(),
            node.financial_currency.as_str(),
            node.exchange.as_str(),
            node.full_exchange_name.as_str(),
            node.quote_type.as_str(),
        ),
    );
}

fn store_quote_node_instrument(client: &YfClient, symbol: &str, node: &V7QuoteNode) {
    let exch = node.exchange();
    let Some(kind) = node
        .quote_type
        .as_str()
        .and_then(|s| parse_yahoo_quote_type(s).ok())
    else {
        return;
    };

    let inst = match exch {
        Some(ex) => Instrument::from_symbol_and_exchange(symbol, ex, kind),
        None => Instrument::from_symbol(symbol, kind),
    };
    if let Ok(inst) = inst {
        client.store_instrument(symbol.to_string(), inst);
    }
}

fn store_requested_alias_hints(
    client: &YfClient,
    requested_symbols: &[&str],
    provider_symbol: &str,
    node: &V7QuoteNode,
) {
    for requested in requested_symbols {
        if same_symbol(provider_symbol, requested) && !same_cache_key(provider_symbol, requested) {
            store_quote_node_hints(client, requested, node);
        }
    }
}

fn mark_resolved_requested_symbol(
    requested_symbols: &[&str],
    resolved: &mut [bool],
    provider_symbol: Option<&str>,
) {
    if let Some(symbol) = provider_symbol {
        for (idx, requested) in requested_symbols.iter().enumerate() {
            if same_symbol(symbol, requested) {
                resolved[idx] = true;
            }
        }
    }

    if requested_symbols.len() == 1
        && provider_symbol.is_none_or(|symbol| !same_symbol(symbol, requested_symbols[0]))
    {
        resolved[0] = true;
    }
}

fn nonempty_symbol(symbol: Option<&str>) -> Option<&str> {
    symbol.map(str::trim).filter(|symbol| !symbol.is_empty())
}

fn same_symbol(left: &str, right: &str) -> bool {
    left.trim().eq_ignore_ascii_case(right.trim())
}

fn same_cache_key(left: &str, right: &str) -> bool {
    left.trim() == right.trim()
}

impl TryFrom<V7QuoteNode> for Quote {
    type Error = YfError;

    fn try_from(n: V7QuoteNode) -> Result<Self, Self::Error> {
        let mut ctx = ProjectionContext::new("quote_v7", DataQuality::BestEffort);
        n.to_quote_with_context(&mut ctx)
    }
}

impl V7QuoteNode {
    pub(crate) fn to_quote_item_with_context(
        &self,
        ctx: &mut ProjectionContext,
    ) -> Result<Option<Quote>, YfError> {
        let key = self.symbol_key();
        let exchange = self.exchange_with_context(ctx, key.as_deref())?;
        let instrument = match self.instrument_projection(exchange) {
            Ok(instrument) => instrument,
            Err(reason) => {
                ctx.dropped_item("quote", key.as_deref(), reason)?;
                return Ok(None);
            }
        };
        let currencies = self.currency_units();
        let currency = match currencies.quote_currency() {
            Ok(currency) => currency,
            Err(reason) => {
                ctx.dropped_item("quote", key.as_deref(), reason)?;
                return Ok(None);
            }
        };

        self.quote_from_instrument_with_context(ctx, key.as_deref(), instrument, currency)
            .map(Some)
    }

    pub(crate) fn to_quote_with_context(
        &self,
        ctx: &mut ProjectionContext,
    ) -> Result<Quote, YfError> {
        let key = self.symbol_key();
        let exchange = self.exchange_with_context(ctx, key.as_deref())?;
        let instrument = self.instrument(exchange)?;
        let currency = self
            .currency_units()
            .quote_currency()
            .map_err(|issue| YfError::InvalidData(format!("invalid quote currency: {issue}")))?;

        self.quote_from_instrument_with_context(ctx, key.as_deref(), instrument, currency)
    }

    fn quote_from_instrument_with_context(
        &self,
        ctx: &mut ProjectionContext,
        key: Option<&str>,
        instrument: Instrument,
        currency: Currency,
    ) -> Result<Quote, YfError> {
        let currencies = self.currency_units();
        let name = self
            .long_name
            .optional_cloned(ctx, "longName", key)?
            .or(self.short_name.optional_cloned(ctx, "shortName", key)?);
        let regular_market_price =
            self.regular_market_price
                .optional_copied(ctx, "regularMarketPrice", key)?;
        let bid = self.bid.optional_copied(ctx, "bid", key)?;
        let bid_size = self
            .bid_size
            .optional_copied_map(ctx, "bidSize", key, JsonU64::into_u64)?;
        let ask = self.ask.optional_copied(ctx, "ask", key)?;
        let ask_size = self
            .ask_size
            .optional_copied_map(ctx, "askSize", key, JsonU64::into_u64)?;
        let regular_market_previous_close = self.regular_market_previous_close.optional_copied(
            ctx,
            "regularMarketPreviousClose",
            key,
        )?;
        let regular_market_volume = self.regular_market_volume.optional_copied_map(
            ctx,
            "regularMarketVolume",
            key,
            JsonU64::into_u64,
        )?;

        Ok(Quote {
            instrument,
            name,
            currency,
            price: currencies.quote_price_amount(
                ctx,
                "regularMarketPrice",
                key,
                regular_market_price,
                "quote price",
            )?,
            bid: self.positive_book_level(ctx, "bid", key, bid, bid_size)?,
            ask: self.positive_book_level(ctx, "ask", key, ask, ask_size)?,
            previous_close: currencies.quote_price_amount(
                ctx,
                "regularMarketPreviousClose",
                key,
                regular_market_previous_close,
                "quote previous close",
            )?,
            day_volume: regular_market_volume.and_then(quantity_from_u64),
            market_state: self.market_state_with_context(ctx, key)?,
            as_of: self.as_of_with_context(ctx, key)?,
            provider: (),
        })
    }
}

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

    fn test_base_url() -> Url {
        Url::parse("https://query1.finance.yahoo.com/v7/finance/quote").unwrap()
    }

    #[test]
    fn quote_symbol_chunks_respect_max_symbol_count() {
        let symbols = (0..=MAX_V7_QUOTE_SYMBOLS_PER_REQUEST)
            .map(|idx| format!("SYM{idx}"))
            .collect::<Vec<_>>();

        let chunks = chunk_v7_quote_symbols(&test_base_url(), symbols).unwrap();

        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0].len(), MAX_V7_QUOTE_SYMBOLS_PER_REQUEST);
        assert_eq!(chunks[1].len(), 1);
    }

    #[test]
    fn quote_symbol_chunks_respect_encoded_url_byte_limit() {
        let symbols = (0..40)
            .map(|idx| format!("SYM{idx:03}{}", "X".repeat(70)))
            .collect::<Vec<_>>();

        let chunks = chunk_v7_quote_symbols(&test_base_url(), symbols).unwrap();

        assert!(chunks.len() > 1);
        assert!(chunks.iter().all(|chunk| {
            v7_quote_url(chunk, &test_base_url()).as_str().len() <= MAX_V7_QUOTE_URL_BYTES
        }));
    }
}