finance-query 3.0.0

A Rust library for querying financial data
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
//! Symbol-specific data access from multiple providers.

use crate::adapters::edgar;
use crate::adapters::yahoo::client::{ClientConfig, YahooClient};
#[cfg(feature = "backtesting")]
use crate::backtesting;
use crate::constants::{Frequency, Interval, Region, StatementType, TimeRange};
use crate::error::{FinanceError, Result};
use crate::format::Both;
#[cfg(any(feature = "backtesting", feature = "indicators"))]
use crate::indicators;
use crate::models::chart::events::ChartEvents;
use crate::models::chart::{CapitalGain, Chart, Dividend, DividendAnalytics, Split};
use crate::models::corporate::news::News;
use crate::models::corporate::recommendation::Recommendation;
use crate::models::filings::{CompanyFacts, EdgarSubmissions, ProviderFilings};
use crate::models::format::Format;
use crate::models::fundamentals::FinancialStatement;
use crate::models::options::Options;
use crate::models::quote::{
    AssetProfile, CalendarEvents, DefaultKeyStatistics, Earnings, EarningsHistory, EarningsTrend,
    EquityPerformance, FinancialData, FundOwnership, FundPerformance, FundProfile, IndexTrend,
    IndustryTrend, InsiderHolders, InsiderTransactions, InstitutionOwnership,
    MajorHoldersBreakdown, NetSharePurchaseActivity, Price, Quote, QuoteSummaryResponse,
    QuoteTypeData, RecommendationTrend, SecFilings, SectorTrend, SummaryDetail, SummaryProfile,
    TopHoldings, UpgradeDowngradeHistory,
};

use super::macros::ticker_fetch;
use crate::providers::types::recommendation_from_similar;
use crate::providers::yahoo::YahooProvider;
use crate::providers::{
    Capability, Fetch, Provider, ProviderAdapter, ProviderSet, Routes, build_providers,
};
#[cfg(feature = "risk")]
use crate::risk;
use crate::utils::{CacheEntry, CacheMode, FetchGuards, filter_by_range};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;

type Cache<T> = Arc<RwLock<Option<CacheEntry<T>>>>;
type MapCache<K, V> = Arc<RwLock<HashMap<K, CacheEntry<V>>>>;

/// Opaque handle to a shared Yahoo Finance client session.
///
/// Allows multiple [`Ticker`] and [`Tickers`](crate::Tickers) instances to share
/// one authenticated session, avoiding redundant auth handshakes.
///
/// Obtain via [`Ticker::client_handle`] or [`Tickers::client_handle`](crate::Tickers::client_handle), then
/// pass to other builders via `.client(handle)`.
///
/// # Example
///
/// ```no_run
/// use finance_query::Ticker;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let aapl = Ticker::new("AAPL").await?;
/// let handle = aapl.client_handle();
///
/// let msft = Ticker::builder("MSFT").client(handle.clone()).build().await?;
/// let googl = Ticker::builder("GOOGL").client(handle).build().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct ClientHandle(pub(crate) Arc<YahooClient>);
/// Builder for constructing a [`Ticker`] with optional configuration.
///
/// Construct via [`Ticker::builder`]. All builder methods are optional;
/// call [`build`](TickerBuilder::build) to finalize.
pub struct TickerBuilder {
    symbol: Arc<str>,
    config: ClientConfig,
    shared_client: Option<ClientHandle>,
    injected_providers: Option<Arc<ProviderSet>>,
    cache_mode: CacheMode,
    include_logo: bool,
}

impl TickerBuilder {
    fn new(symbol: impl Into<String>) -> Self {
        Self {
            symbol: symbol.into().into(),
            config: ClientConfig::default(),
            shared_client: None,
            injected_providers: None,
            cache_mode: CacheMode::default(),
            include_logo: false,
        }
    }
    /// Set the region (automatically sets correct lang and region).
    pub fn region(mut self, region: Region) -> Self {
        self.config.lang = region.lang().to_string();
        self.config.region = region.region().to_string();
        self
    }
    /// Set the language code (e.g., "en-US", "ja-JP").
    pub fn lang(mut self, lang: impl Into<String>) -> Self {
        self.config.lang = lang.into();
        self
    }
    /// Set the region code (e.g., "US", "JP").
    pub fn region_code(mut self, r: impl Into<String>) -> Self {
        self.config.region = r.into();
        self
    }
    /// Set the HTTP request timeout.
    pub fn timeout(mut self, t: Duration) -> Self {
        self.config.timeout = t;
        self
    }
    /// Set the proxy URL.
    pub fn proxy(mut self, p: impl Into<String>) -> Self {
        self.config.proxy = Some(p.into());
        self
    }
    #[allow(dead_code)]
    pub(crate) fn config(mut self, c: ClientConfig) -> Self {
        self.config = c;
        self
    }
    /// Pre-inject a shared provider set (used by [`Providers::ticker`](crate::Providers::ticker)).
    ///
    /// Not part of the stable public API — see [`ProviderAdapter`](crate::ProviderAdapter).
    #[doc(hidden)]
    pub fn with_provider_set(mut self, set: Arc<ProviderSet>) -> Self {
        self.injected_providers = Some(set);
        self
    }
    /// Share an existing authenticated session instead of creating a new one.
    ///
    /// Avoids redundant auth handshakes when creating multiple `Ticker` instances.
    /// Obtain a handle from any existing `Ticker` via [`Ticker::client_handle`].
    ///
    /// When set, the builder's `config`, `timeout`, `proxy`, `lang`, and `region`
    /// settings are ignored — the shared session's configuration is used instead.
    pub fn client(mut self, handle: ClientHandle) -> Self {
        self.shared_client = Some(handle);
        self
    }
    /// Cache responses for `ttl` instead of the default 60 seconds.
    pub fn cache(mut self, ttl: Duration) -> Self {
        self.cache_mode = CacheMode::Ttl(ttl);
        self
    }
    /// Cache responses for the handle's lifetime instead of the default 60
    /// seconds.
    pub fn cache_forever(mut self) -> Self {
        self.cache_mode = CacheMode::Lifetime;
        self
    }
    /// Disable caching — every call fetches fresh data.
    ///
    /// By default a `Ticker` caches each response for 60 seconds, so
    /// repeated accessor calls within that window reuse one fetch.
    pub fn no_cache(mut self) -> Self {
        self.cache_mode = CacheMode::Off;
        self
    }
    /// Include company logo URLs in quote responses.
    pub fn logo(mut self) -> Self {
        self.include_logo = true;
        self
    }

    /// Build the Ticker instance.
    pub async fn build(self) -> Result<Ticker> {
        #[cfg(feature = "translation")]
        let translate_lang = {
            let lang = crate::translation::Lang::parse(&self.config.lang)?;
            (!lang.is_english()).then_some(lang)
        };
        let providers = if let Some(set) = self.injected_providers {
            set
        } else if let Some(handle) = self.shared_client {
            let yahoo = YahooProvider::from_client(handle.0);
            let client = yahoo.client_arc();
            Arc::new(
                ProviderSet::new(
                    vec![Arc::new(yahoo) as Arc<dyn ProviderAdapter>],
                    Routes::new(Fetch::Sequential),
                )
                .with_yahoo_client(Some(client)),
            )
        } else {
            Arc::new(
                build_providers(
                    &[Provider::Yahoo],
                    Vec::new(),
                    &self.config,
                    Routes::new(Fetch::Sequential),
                )
                .await?,
            )
        };
        Ok(Ticker {
            symbol: self.symbol,
            providers,
            cache_mode: self.cache_mode,
            include_logo: self.include_logo,
            #[cfg(feature = "translation")]
            translate_lang,
            quote_cache: Default::default(),
            quote_fetch: Arc::new(tokio::sync::Mutex::new(())),
            chart_cache: Default::default(),
            chart_guards: Default::default(),
            events_cache: Default::default(),
            events_fetch: Arc::new(tokio::sync::Mutex::new(())),
            news_cache: Default::default(),
            news_fetch: Arc::new(tokio::sync::Mutex::new(())),
            logo_cache: Default::default(),
            options_cache: Default::default(),
            options_guards: Default::default(),
            financials_cache: Default::default(),
            financials_guards: Default::default(),
            #[cfg(feature = "indicators")]
            indicators_cache: Default::default(),
            #[cfg(feature = "indicators")]
            indicators_guards: Default::default(),
            edgar_submissions_cache: Default::default(),
            edgar_submissions_fetch: Arc::new(tokio::sync::Mutex::new(())),
            edgar_facts_cache: Default::default(),
            edgar_facts_fetch: Arc::new(tokio::sync::Mutex::new(())),
        })
    }
}

/// The primary entry point for querying financial data for a single symbol.
///
/// Data is fetched on first access and cached for 60 seconds by default.
/// Use the builder via [`Ticker::builder`] for custom configuration, including
/// [`cache`](TickerBuilder::cache) and [`no_cache`](TickerBuilder::no_cache).
pub struct Ticker {
    symbol: Arc<str>,
    providers: Arc<ProviderSet>,
    cache_mode: CacheMode,
    include_logo: bool,
    #[cfg(feature = "translation")]
    translate_lang: Option<crate::translation::Lang>,
    quote_cache: Cache<QuoteSummaryResponse>,
    quote_fetch: Arc<tokio::sync::Mutex<()>>,
    chart_cache: MapCache<(Interval, TimeRange), Chart>,
    chart_guards: FetchGuards<(Interval, TimeRange)>,
    events_cache: Cache<ChartEvents>,
    events_fetch: Arc<tokio::sync::Mutex<()>>,
    news_cache: Cache<Vec<News>>,
    news_fetch: Arc<tokio::sync::Mutex<()>>,
    logo_cache: Cache<(Option<String>, Option<String>)>,
    options_cache: MapCache<Option<i64>, Options>,
    options_guards: FetchGuards<Option<i64>>,
    financials_cache: MapCache<(StatementType, Frequency), FinancialStatement>,
    financials_guards: FetchGuards<(StatementType, Frequency)>,
    #[cfg(feature = "indicators")]
    indicators_cache: MapCache<(Interval, TimeRange), indicators::IndicatorsSummary>,
    #[cfg(feature = "indicators")]
    indicators_guards: FetchGuards<(Interval, TimeRange)>,
    edgar_submissions_cache: Cache<EdgarSubmissions>,
    edgar_submissions_fetch: Arc<tokio::sync::Mutex<()>>,
    edgar_facts_cache: Cache<CompanyFacts>,
    edgar_facts_fetch: Arc<tokio::sync::Mutex<()>>,
}

impl Ticker {
    /// Creates a new ticker with default configuration.
    pub async fn new(symbol: impl Into<String>) -> Result<Self> {
        Self::builder(symbol).build().await
    }
    /// Creates a new builder for Ticker.
    pub fn builder(symbol: impl Into<String>) -> TickerBuilder {
        TickerBuilder::new(symbol)
    }
    /// Returns the ticker symbol.
    pub fn symbol(&self) -> &str {
        &self.symbol
    }

    /// Returns a handle to the underlying Yahoo Finance session.
    ///
    /// Pass to other builders via `.client(handle)` to share the authenticated
    /// session without a new auth handshake.
    ///
    /// # Panics
    ///
    /// Panics if this ticker was created via [`Providers`](crate::Providers) with
    /// no Yahoo provider configured. For session sharing across multiple tickers,
    /// prefer [`Providers::ticker`](crate::Providers::ticker) instead.
    pub fn client_handle(&self) -> ClientHandle {
        ClientHandle(
            self.providers
                .first_yahoo()
                .expect("client_handle requires a Yahoo session; use Providers::ticker() for multi-provider tickers"),
        )
    }

    #[allow(dead_code)]
    pub(crate) fn provider_set(&self) -> &Arc<ProviderSet> {
        &self.providers
    }

    /// Translate a response value when a non-English language is configured
    /// (no-op otherwise).
    #[cfg(feature = "translation")]
    pub(crate) async fn translate_response<T: crate::translation::Translatable>(
        &self,
        value: &mut T,
    ) -> Result<()> {
        if let Some(lang) = &self.translate_lang {
            crate::translation::translate_with(value, lang).await?;
        }
        Ok(())
    }

    fn is_cache_fresh<T>(&self, entry: Option<&CacheEntry<T>>) -> bool {
        CacheEntry::is_fresh_entry(entry, self.cache_mode)
    }

    fn cache_insert<K: Eq + std::hash::Hash, V>(
        &self,
        map: &mut HashMap<K, CacheEntry<V>>,
        key: K,
        value: V,
    ) {
        crate::utils::cache_insert(
            map,
            key,
            value,
            self.cache_mode,
            crate::utils::EVICTION_THRESHOLD,
        );
    }

    /// Get full quote data, optionally including logo URLs.
    pub async fn quote<F>(&self) -> Result<Quote<F>>
    where
        F: Format,
        Quote<Both>: Into<Quote<F>>,
    {
        let logo_fut = async {
            if !self.include_logo {
                return (None, None);
            }
            if let Some(e) = self.logo_cache.read().await.as_ref()
                && self.is_cache_fresh(Some(e))
            {
                return e.value.clone();
            }
            let fetched = match self.providers.first_yahoo() {
                Ok(y) => y.get_logo_url(&self.symbol).await,
                Err(e) => Err(e),
            };
            // Only a successful lookup is cached. A symbol that genuinely has no
            // logo resolves to `(None, None)` and caches like any other answer;
            // a transport error does not, so one blip can't become permanent for
            // the handle's life.
            match fetched {
                Ok(logos) => {
                    if self.cache_mode.enabled() {
                        *self.logo_cache.write().await = Some(CacheEntry::new(logos.clone()));
                    }
                    logos
                }
                Err(_) => (None, None),
            }
        };

        let (cache, (logo_url, company_logo_url)) = tokio::join!(self.ensure_quote(), logo_fut);
        let cache = cache?;
        let summary = cache.as_ref().ok_or_else(|| {
            FinanceError::ApiError("Quote summary cache was empty after fetch".to_string())
        })?;
        let quote = Quote::from_response(&summary.value, logo_url, company_logo_url);
        #[cfg(feature = "translation")]
        let quote = {
            drop(cache);
            let mut quote = quote;
            self.translate_response(&mut quote).await?;
            quote
        };
        Ok(quote.into())
    }

    fn chart_from_provider_data(
        mut data: Chart,
        interval: Option<Interval>,
        range: Option<TimeRange>,
    ) -> Chart {
        data.interval = interval;
        data.range = range;
        data
    }

    /// Get historical OHLCV chart data.
    pub async fn chart(&self, interval: Interval, range: TimeRange) -> Result<Chart> {
        let key = (interval, range);
        {
            let cache = self.chart_cache.read().await;
            if let Some(entry) = cache.get(&key)
                && self.is_cache_fresh(Some(entry))
            {
                return Ok(entry.value.clone());
            }
        }
        self.chart_guards
            .dedup(key, || async {
                {
                    let cache = self.chart_cache.read().await;
                    if let Some(entry) = cache.get(&key)
                        && self.is_cache_fresh(Some(entry))
                    {
                        return Ok(entry.value.clone());
                    }
                }
                let data =
                    ticker_fetch!(self, CHART, as_chart, Chart, fetch_chart, interval, range)?;
                let chart = Self::chart_from_provider_data(data, Some(interval), Some(range));
                if self.cache_mode.enabled() {
                    let mut cache = self.chart_cache.write().await;
                    self.cache_insert(&mut cache, key, chart.clone());
                }
                Ok(chart)
            })
            .await
    }

    /// Get chart data for a custom start/end timestamp range.
    pub async fn chart_range(&self, interval: Interval, start: i64, end: i64) -> Result<Chart> {
        if start >= end {
            return Err(FinanceError::InvalidParameter {
                param: "end".into(),
                reason: format!("end ({end}) must be > start ({start})"),
            });
        }
        let data = ticker_fetch!(
            self,
            CHART,
            as_chart,
            ChartRange,
            fetch_chart_range,
            interval,
            start,
            end
        )?;
        Ok(Self::chart_from_provider_data(data, Some(interval), None))
    }

    async fn ensure_events(&self) -> Result<()> {
        {
            let cache = self.events_cache.read().await;
            if self.is_cache_fresh(cache.as_ref()) {
                return Ok(());
            }
        }
        let _guard = self.events_fetch.lock().await;
        {
            let cache = self.events_cache.read().await;
            if self.is_cache_fresh(cache.as_ref()) {
                return Ok(());
            }
        }
        let events = ticker_fetch!(self, CORPORATE, as_corporate, Events, fetch_events)?;
        let mut cache = self.events_cache.write().await;
        *cache = Some(CacheEntry::new(events));
        Ok(())
    }

    /// Get dividend history.
    pub async fn dividends(&self, range: TimeRange) -> Result<Vec<Dividend>> {
        self.ensure_events().await?;
        let cache = self.events_cache.read().await;
        let all = cache
            .as_ref()
            .map(|e| e.value.to_dividends())
            .unwrap_or_default();
        Ok(filter_by_range(all, range))
    }
    /// Compute dividend analytics for the requested time range.
    pub async fn dividend_analytics(&self, range: TimeRange) -> Result<DividendAnalytics> {
        let divs = self.dividends(range).await?;
        Ok(DividendAnalytics::from_dividends(&divs))
    }
    /// Get stock split history.
    pub async fn splits(&self, range: TimeRange) -> Result<Vec<Split>> {
        self.ensure_events().await?;
        let cache = self.events_cache.read().await;
        let all = cache
            .as_ref()
            .map(|e| e.value.to_splits())
            .unwrap_or_default();
        Ok(filter_by_range(all, range))
    }
    /// Get capital gains distribution history.
    pub async fn capital_gains(&self, range: TimeRange) -> Result<Vec<CapitalGain>> {
        self.ensure_events().await?;
        let cache = self.events_cache.read().await;
        let all = cache
            .as_ref()
            .map(|e| e.value.to_capital_gains())
            .unwrap_or_default();
        Ok(filter_by_range(all, range))
    }

    /// Get analyst recommendations and similar symbols.
    pub async fn recommendations(&self, limit: u32) -> Result<Recommendation> {
        if limit == 0 {
            return Err(FinanceError::InvalidParameter {
                param: "limit".into(),
                reason: "limit must be > 0".into(),
            });
        }
        let sym = self.symbol.clone();
        let (provider_id, items) = self
            .providers
            .fetch(Capability::CORPORATE, move |p| {
                let sym = sym.clone();
                let p = p.clone();
                async move {
                    let r = p
                        .as_corporate()
                        .ok_or_else(|| {
                            p.not_supported(crate::providers::Operation::Recommendations)
                        })?
                        .fetch_similar_symbols(&sym, limit)
                        .await?;
                    Ok((p.id(), r))
                }
            })
            .await?;
        Ok(recommendation_from_similar(
            self.symbol.to_string(),
            Some(provider_id),
            items,
            Some(limit),
        ))
    }

    /// Get news articles for this symbol.
    pub async fn news(&self) -> Result<Vec<News>> {
        {
            let cache = self.news_cache.read().await;
            if let Some(e) = cache.as_ref()
                && self.is_cache_fresh(Some(e))
            {
                return Ok(e.value.clone());
            }
        }
        let _guard = self.news_fetch.lock().await;
        {
            let cache = self.news_cache.read().await;
            if let Some(e) = cache.as_ref()
                && self.is_cache_fresh(Some(e))
            {
                return Ok(e.value.clone());
            }
        }
        let data = ticker_fetch!(self, CORPORATE, as_corporate, News, fetch_news)?;
        let news = data;
        // Score titles before translation — VADER is English-lexicon based.
        #[cfg(feature = "sentiment")]
        let news = {
            let mut news = news;
            for article in news.iter_mut() {
                article.sentiment = Some(crate::models::sentiment::analyze(&article.title));
            }
            news
        };
        #[cfg(feature = "translation")]
        let news = {
            let mut news = news;
            self.translate_response(&mut news).await?;
            news
        };
        if self.cache_mode.enabled() {
            let mut c = self.news_cache.write().await;
            *c = Some(CacheEntry::new(news.clone()));
        }
        Ok(news)
    }

    /// Average sentiment across recent news headlines for this symbol.
    ///
    /// Positive = net bullish coverage, negative = net bearish. Returns a
    /// neutral, zero-confidence score when there are no headlines.
    ///
    /// Only available when the `sentiment` feature is enabled.
    #[cfg(feature = "sentiment")]
    pub async fn news_sentiment(&self) -> Result<crate::models::sentiment::Sentiment> {
        let news = self.news().await?;
        let scores: Vec<f64> = news
            .iter()
            .filter_map(|n| n.sentiment.as_ref().map(|s| s.score))
            .collect();
        Ok(crate::models::sentiment::aggregate(&scores)
            .unwrap_or_else(crate::models::sentiment::Sentiment::neutral))
    }

    /// Get the options chain.
    pub async fn options(&self, date: Option<i64>) -> Result<Options> {
        {
            let cache = self.options_cache.read().await;
            if let Some(e) = cache.get(&date)
                && self.is_cache_fresh(Some(e))
            {
                return Ok(e.value.clone());
            }
        }
        self.options_guards
            .dedup(date, || async {
                {
                    let cache = self.options_cache.read().await;
                    if let Some(e) = cache.get(&date)
                        && self.is_cache_fresh(Some(e))
                    {
                        return Ok(e.value.clone());
                    }
                }
                let opts = ticker_fetch!(self, OPTIONS, as_options, Options, fetch_options, date)?;
                if self.cache_mode.enabled() {
                    let mut c = self.options_cache.write().await;
                    self.cache_insert(&mut c, date, opts.clone());
                }
                Ok(opts)
            })
            .await
    }

    /// Get financial statements.
    pub async fn financials(
        &self,
        stmt_type: StatementType,
        frequency: Frequency,
    ) -> Result<FinancialStatement> {
        let key = (stmt_type, frequency);
        {
            let cache = self.financials_cache.read().await;
            if let Some(e) = cache.get(&key)
                && self.is_cache_fresh(Some(e))
            {
                return Ok(e.value.clone());
            }
        }
        self.financials_guards
            .dedup(key, || async {
                {
                    let cache = self.financials_cache.read().await;
                    if let Some(e) = cache.get(&key)
                        && self.is_cache_fresh(Some(e))
                    {
                        return Ok(e.value.clone());
                    }
                }
                let stmt = ticker_fetch!(
                    self,
                    FUNDAMENTALS,
                    as_fundamentals,
                    Financials,
                    fetch_financials,
                    stmt_type,
                    frequency
                )?;
                if self.cache_mode.enabled() {
                    let mut c = self.financials_cache.write().await;
                    self.cache_insert(&mut c, key, stmt.clone());
                }
                Ok(stmt)
            })
            .await
    }

    #[cfg(feature = "indicators")]
    /// Calculate all technical indicators from chart data.
    pub async fn indicators(
        &self,
        interval: Interval,
        range: TimeRange,
    ) -> Result<indicators::IndicatorsSummary> {
        let key = (interval, range);
        {
            let cache = self.indicators_cache.read().await;
            if let Some(e) = cache.get(&key)
                && self.is_cache_fresh(Some(e))
            {
                return Ok(e.value.clone());
            }
        }
        self.indicators_guards
            .dedup(key, || async {
                {
                    let cache = self.indicators_cache.read().await;
                    if let Some(e) = cache.get(&key)
                        && self.is_cache_fresh(Some(e))
                    {
                        return Ok(e.value.clone());
                    }
                }
                let chart = self.chart(interval, range).await?;
                let ind = indicators::summary::calculate_indicators(&chart.candles);
                if self.cache_mode.enabled() {
                    let mut c = self.indicators_cache.write().await;
                    self.cache_insert(&mut c, key, ind.clone());
                }
                Ok(ind)
            })
            .await
    }

    /// Get SEC EDGAR filing history for this symbol.
    ///
    /// Always uses EDGAR directly — this is an EDGAR-specific API (CIK-based submission
    /// history and XBRL company facts) that no other provider replicates. For routable
    /// provider-agnostic filing data use [`filings`](Self::filings) instead.
    pub async fn edgar_submissions(&self) -> Result<EdgarSubmissions> {
        {
            let cache = self.edgar_submissions_cache.read().await;
            if let Some(e) = cache.as_ref()
                && self.is_cache_fresh(Some(e))
            {
                return Ok(e.value.clone());
            }
        }
        let _guard = self.edgar_submissions_fetch.lock().await;
        {
            let cache = self.edgar_submissions_cache.read().await;
            if let Some(e) = cache.as_ref()
                && self.is_cache_fresh(Some(e))
            {
                return Ok(e.value.clone());
            }
        }
        let subs = edgar::submissions_for_symbol(&self.symbol).await?;
        if self.cache_mode.enabled() {
            let mut c = self.edgar_submissions_cache.write().await;
            *c = Some(CacheEntry::new(subs.clone()));
        }
        Ok(subs)
    }

    /// Get SEC EDGAR company facts (structured XBRL financial data).
    ///
    /// Always uses EDGAR directly — XBRL `us-gaap`/`ifrs`/`dei` fact data is unique
    /// to the SEC's EDGAR API. For routable filing data use [`filings`](Self::filings).
    pub async fn edgar_company_facts(&self) -> Result<CompanyFacts> {
        {
            let cache = self.edgar_facts_cache.read().await;
            if let Some(e) = cache.as_ref()
                && self.is_cache_fresh(Some(e))
            {
                return Ok(e.value.clone());
            }
        }
        let _guard = self.edgar_facts_fetch.lock().await;
        {
            let cache = self.edgar_facts_cache.read().await;
            if let Some(e) = cache.as_ref()
                && self.is_cache_fresh(Some(e))
            {
                return Ok(e.value.clone());
            }
        }
        let facts = edgar::company_facts_for_symbol(&self.symbol).await?;
        if self.cache_mode.enabled() {
            let mut c = self.edgar_facts_cache.write().await;
            *c = Some(CacheEntry::new(facts.clone()));
        }
        Ok(facts)
    }

    /// Fetch SEC filings via the configured [`Capability::FILINGS`] provider.
    ///
    /// Routes through the provider system; EDGAR is always available as a fallback
    /// (auto-injected when no explicit FILINGS route is set). To prefer Polygon:
    /// `.route(Capability::FILINGS, [Provider::Polygon, Provider::Edgar])`.
    ///
    /// For the full EDGAR submissions response or structured XBRL data, use
    /// [`edgar_submissions`](Self::edgar_submissions) / [`edgar_company_facts`](Self::edgar_company_facts).
    pub async fn filings(&self) -> Result<ProviderFilings> {
        ticker_fetch!(self, FILINGS, as_filings, Filings, fetch_filings)
    }

    /// Fetch short-interest settlement reports via the configured
    /// [`Capability::FUNDAMENTALS`] provider. The default Yahoo route derives
    /// the current and prior-month snapshots from key statistics (keyless);
    /// route to Polygon for the full bi-monthly history:
    /// `.route(Capability::FUNDAMENTALS, [Provider::Polygon, Provider::Yahoo])`.
    pub async fn short_interest(&self) -> Result<Vec<crate::models::fundamentals::ShortInterest>> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            ShortInterest,
            fetch_short_interest
        )
    }

    /// Fetch daily short-volume data via the configured
    /// [`Capability::FUNDAMENTALS`] provider (currently Polygon only).
    pub async fn short_volume(&self) -> Result<Vec<crate::models::fundamentals::ShortVolume>> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            ShortVolume,
            fetch_short_volume
        )
    }

    /// Fetch share float and shares outstanding via the configured
    /// [`Capability::FUNDAMENTALS`] provider (Yahoo-derived on the default
    /// route; Polygon serves it too).
    pub async fn share_float(&self) -> Result<crate::models::fundamentals::ShareFloat> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            ShareFloat,
            fetch_share_float
        )
    }

    /// Fetch the company's own press releases via the configured
    /// [`Capability::CORPORATE`] provider (currently FMP only). Distinct from
    /// [`news`](Self::news), which returns press coverage.
    pub async fn press_releases(
        &self,
        limit: u32,
    ) -> Result<Vec<crate::models::corporate::press_release::PressRelease>> {
        ticker_fetch!(
            self,
            CORPORATE,
            as_corporate,
            PressReleases,
            fetch_press_releases,
            limit
        )
    }

    /// Fetch the aggregated analyst price-target consensus (high/low/mean/median)
    /// via the configured [`Capability::FUNDAMENTALS`] provider (currently FMP
    /// only). Route with
    /// `.route(Capability::FUNDAMENTALS, [Provider::Fmp, Provider::Yahoo])`.
    pub async fn price_target_consensus(
        &self,
    ) -> Result<crate::models::fundamentals::PriceTargetConsensus> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            PriceTargetConsensus,
            fetch_price_target_consensus
        )
    }

    /// Fetch price-target publication activity over trailing windows (last
    /// month/quarter/year/all time) via the configured
    /// [`Capability::FUNDAMENTALS`] provider (currently FMP only).
    pub async fn price_target_summary(
        &self,
    ) -> Result<crate::models::fundamentals::PriceTargetSummary> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            PriceTargetSummary,
            fetch_price_target_summary
        )
    }

    /// Fetch the aggregated analyst rating consensus (grade distribution plus a
    /// headline label) via the configured [`Capability::FUNDAMENTALS`] provider
    /// (currently FMP only). Distinct from
    /// [`recommendations`](Self::recommendations), which returns similar symbols.
    pub async fn rating_consensus(&self) -> Result<crate::models::fundamentals::RatingConsensus> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            RatingConsensus,
            fetch_rating_consensus
        )
    }

    /// Fetch the trailing-twelve-month key-metrics snapshot via the configured
    /// [`Capability::FUNDAMENTALS`] provider (currently FMP only).
    ///
    /// A TTM snapshot is a single always-current rollup, so callers do not need
    /// to fetch the latest fiscal period and reason about whether it is still
    /// current — see [`financials`](Self::financials) for the period series.
    pub async fn key_metrics_ttm(&self) -> Result<crate::models::fundamentals::KeyMetricsTtm> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            KeyMetricsTtm,
            fetch_key_metrics_ttm
        )
    }

    /// Fetch the trailing-twelve-month financial-ratios snapshot via the
    /// configured [`Capability::FUNDAMENTALS`] provider (currently FMP only).
    pub async fn ratios_ttm(&self) -> Result<crate::models::fundamentals::FinancialRatiosTtm> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            RatiosTtm,
            fetch_ratios_ttm
        )
    }

    /// Fetch reported executive compensation (most recent fiscal year first)
    /// via the configured [`Capability::CORPORATE`] provider (currently FMP
    /// only). Extracted from DEF 14A proxy statements, so it lags the filing.
    pub async fn executive_compensation(
        &self,
    ) -> Result<Vec<crate::models::corporate::governance::ExecutiveCompensation>> {
        ticker_fetch!(
            self,
            CORPORATE,
            as_corporate,
            ExecutiveCompensation,
            fetch_executive_compensation
        )
    }

    /// Fetch reported employee headcount history (most recent period first) via
    /// the configured [`Capability::CORPORATE`] provider (currently FMP only).
    /// Taken from 10-K cover pages, so it is annual.
    pub async fn employee_count(
        &self,
    ) -> Result<Vec<crate::models::corporate::governance::EmployeeCount>> {
        ticker_fetch!(
            self,
            CORPORATE,
            as_corporate,
            EmployeeCount,
            fetch_employee_count
        )
    }

    /// Fetch this fund's profile and portfolio holdings via the configured
    /// [`Capability::FUNDAMENTALS`] provider (currently Alpha Vantage only,
    /// and the only wired source of ETF holdings at all).
    ///
    /// Holdings come back heaviest-first. Errors for a symbol that is not a
    /// fund.
    pub async fn etf_profile(&self) -> Result<crate::models::fundamentals::EtfProfile> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            EtfProfile,
            fetch_etf_profile
        )
    }

    /// Fetch earnings-surprise history (most recent first) via the configured
    /// [`Capability::FUNDAMENTALS`] provider (FMP or Alpha Vantage).
    pub async fn earnings_surprises(
        &self,
    ) -> Result<Vec<crate::models::fundamentals::EarningsSurprise>> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            EarningsSurprises,
            fetch_earnings_surprises
        )
    }

    /// Fetch the raw per-analyst grade-action history via the configured
    /// [`Capability::FUNDAMENTALS`] provider (currently FMP only). Distinct
    /// from [`rating_consensus`](Self::rating_consensus), which returns the
    /// aggregated rollup over this same history.
    pub async fn grading_actions(&self) -> Result<Vec<crate::models::fundamentals::GradingAction>> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            GradingHistory,
            fetch_grading_history
        )
    }

    /// Fetch the company's identity/classification profile via the
    /// configured [`Capability::FUNDAMENTALS`] provider (currently Alpha
    /// Vantage only).
    pub async fn company_profile(&self) -> Result<crate::models::fundamentals::CompanyProfile> {
        ticker_fetch!(
            self,
            FUNDAMENTALS,
            as_fundamentals,
            CompanyProfile,
            fetch_company_profile
        )
    }

    /// Fetch an earnings call transcript, provider-neutral shape, via the
    /// configured [`Capability::CORPORATE`] provider (Yahoo or Alpha
    /// Vantage). `quarter` and `year` narrow to a specific call; Alpha
    /// Vantage requires both, Yahoo defaults to the latest when omitted.
    /// Distinct from the Yahoo-only, richer
    /// [`finance::earnings_transcript`](crate::finance::earnings_transcript).
    pub async fn earnings_transcript(
        &self,
        quarter: Option<&str>,
        year: Option<i32>,
    ) -> Result<crate::models::corporate::earnings_transcript::EarningsTranscript> {
        ticker_fetch!(
            self,
            CORPORATE,
            as_corporate,
            EarningsTranscript,
            fetch_earnings_transcript,
            quarter,
            year
        )
    }

    #[cfg(feature = "indicators")]
    /// Calculate a specific technical indicator over a time range.
    pub async fn indicator(
        &self,
        indicator: indicators::Indicator,
        interval: Interval,
        range: TimeRange,
    ) -> Result<indicators::IndicatorResult> {
        let chart = self.chart(interval, range).await?;
        Ok(indicators::compute_indicator(indicator, &chart)?)
    }

    #[cfg(feature = "backtesting")]
    /// Run a backtest with the given strategy and configuration.
    pub async fn backtest<S: backtesting::Strategy>(
        &self,
        strategy: S,
        interval: Interval,
        range: TimeRange,
        config: Option<backtesting::BacktestConfig>,
    ) -> backtesting::Result<backtesting::BacktestResult> {
        let config = config.unwrap_or_default();
        config.validate()?;
        // Chart and dividends hit disjoint caches and disjoint capabilities
        // (CHART vs CORPORATE), so neither warms the other.
        let (chart, dividends) = tokio::join!(self.chart(interval, range), self.dividends(range));
        let chart = chart.map_err(|e| backtesting::BacktestError::ChartError(e.to_string()))?;
        let dividends = dividends.unwrap_or_default();
        backtesting::BacktestEngine::new(config).run_with_dividends(
            &self.symbol,
            &chart.candles,
            strategy,
            &dividends,
        )
    }

    #[cfg(feature = "backtesting")]
    /// Run a backtest and compare performance against a benchmark symbol.
    pub async fn backtest_with_benchmark<S: backtesting::Strategy>(
        &self,
        strategy: S,
        interval: Interval,
        range: TimeRange,
        config: Option<backtesting::BacktestConfig>,
        benchmark: &str,
    ) -> backtesting::Result<backtesting::BacktestResult> {
        let config = config.unwrap_or_default();
        config.validate()?;
        let bench_fut = async {
            let bench_ticker = Ticker::new(benchmark).await?;
            bench_ticker.chart(interval, range).await
        };
        // `join!`, not `try_join!`: both charts are awaited to completion and the
        // errors resolved in a fixed order, so the surfaced error is always the
        // primary symbol's rather than whichever future happened to fail first.
        let (chart, bench_chart, dividends) = tokio::join!(
            self.chart(interval, range),
            bench_fut,
            self.dividends(range)
        );
        let chart = chart.map_err(|e| backtesting::BacktestError::ChartError(e.to_string()))?;
        let bench_chart =
            bench_chart.map_err(|e| backtesting::BacktestError::ChartError(e.to_string()))?;
        let dividends = dividends.unwrap_or_default();
        backtesting::BacktestEngine::new(config).run_with_benchmark(
            &self.symbol,
            &chart.candles,
            strategy,
            &dividends,
            benchmark,
            &bench_chart.candles,
        )
    }

    #[cfg(feature = "risk")]
    /// Compute a risk summary for this symbol.
    pub async fn risk(
        &self,
        interval: Interval,
        range: TimeRange,
        benchmark: Option<&str>,
    ) -> Result<risk::RiskSummary> {
        let bench_fut = async {
            let Some(sym) = benchmark else {
                return Result::Ok(None);
            };
            let bt = Ticker::new(sym).await?;
            let bench_chart = bt.chart(interval, range).await?;
            Result::Ok(Some(risk::candles_to_returns(&bench_chart.candles)))
        };
        // `join!`, not `try_join!`: resolving in a fixed order keeps the primary
        // symbol's error as the surfaced one, matching the previous sequential
        // `self.chart(..).await?` ordering.
        let (chart, bench_returns) = tokio::join!(self.chart(interval, range), bench_fut);
        let chart = chart?;
        let bench_returns = bench_returns?;
        Ok(risk::compute_risk_summary(
            &chart.candles,
            bench_returns.as_deref(),
        ))
    }

    /// Aggregate upcoming financial events for this ticker into a single
    /// time-sorted list.
    ///
    /// Combines earnings, ex-dividend and dividend-payment dates with standard
    /// monthly options expirations, plus — when the `fred` feature is enabled —
    /// a curated set of major economic releases (CPI, NFP, GDP, …). Limited to
    /// the forward window `[now, now + range]` and sorted ascending by
    /// timestamp.
    ///
    /// Options are best-effort: a symbol with no listed options contributes no
    /// expiration events rather than failing the call.
    pub async fn calendar(
        &self,
        range: TimeRange,
    ) -> Result<Vec<crate::models::calendar::CalendarEvent>> {
        let now = chrono::Utc::now().timestamp();
        let window = (now, now + range.approx_duration_secs());

        // The FRED economic-release fetch is independent of the per-symbol
        // quote/options work, so run all three concurrently.
        #[cfg(feature = "fred")]
        let (calendar_events, options, releases) = tokio::join!(
            self.calendar_events(),
            self.options(None),
            crate::adapters::fred::release_dates(),
        );
        #[cfg(not(feature = "fred"))]
        let (calendar_events, options) = tokio::join!(self.calendar_events(), self.options(None));

        let calendar_events = calendar_events?;
        let options = options.ok();

        let mut events = crate::models::calendar::build_symbol_events(
            &self.symbol,
            calendar_events.as_ref(),
            options.as_ref(),
            window,
        );

        #[cfg(feature = "fred")]
        if let Ok(releases) = releases {
            events.extend(crate::models::calendar::build_economic_events(
                releases, window,
            ));
        }

        crate::models::calendar::sort_events(&mut events);
        Ok(events)
    }

    async fn ensure_quote(
        &self,
    ) -> Result<tokio::sync::RwLockReadGuard<'_, Option<CacheEntry<QuoteSummaryResponse>>>> {
        {
            let cache = self.quote_cache.read().await;
            if self.is_cache_fresh(cache.as_ref()) {
                return Ok(cache);
            }
        }
        let _guard = self.quote_fetch.lock().await;
        {
            let cache = self.quote_cache.read().await;
            if self.is_cache_fresh(cache.as_ref()) {
                return Ok(cache);
            }
        }
        let summary = ticker_fetch!(self, QUOTE, as_quote, Quote, fetch_quote)?;
        {
            let mut cache = self.quote_cache.write().await;
            *cache = Some(CacheEntry::new(summary));
        }
        Ok(self.quote_cache.read().await)
    }
}

super::macros::define_quote_accessors! {
    /// Regular, pre- and post-market price, plus the day's range and volume.
    price -> Price, price,
    summary_detail -> SummaryDetail, summary_detail,
    financial_data -> FinancialData, financial_data,
    key_stats -> DefaultKeyStatistics, default_key_statistics,
    asset_profile -> AssetProfile, asset_profile,
    calendar_events -> CalendarEvents, calendar_events,
    earnings -> Earnings, earnings,
    earnings_trend -> EarningsTrend, earnings_trend,
    earnings_history -> EarningsHistory, earnings_history,
    recommendation_trend -> RecommendationTrend, recommendation_trend,
    insider_holders -> InsiderHolders, insider_holders,
    insider_transactions -> InsiderTransactions, insider_transactions,
    institution_ownership -> InstitutionOwnership, institution_ownership,
    fund_ownership -> FundOwnership, fund_ownership,
    major_holders -> MajorHoldersBreakdown, major_holders_breakdown,
    share_purchase_activity -> NetSharePurchaseActivity, net_share_purchase_activity,
    quote_type -> QuoteTypeData, quote_type,
    summary_profile -> SummaryProfile, summary_profile,
    sec_filings -> SecFilings, sec_filings,
    grading_history -> UpgradeDowngradeHistory, upgrade_downgrade_history,
    fund_performance -> FundPerformance, fund_performance,
    fund_profile -> FundProfile, fund_profile,
    top_holdings -> TopHoldings, top_holdings,
    index_trend -> IndexTrend, index_trend,
    industry_trend -> IndustryTrend, industry_trend,
    sector_trend -> SectorTrend, sector_trend,
    equity_performance -> EquityPerformance, equity_performance,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::providers::mock::{CountingProvider, provider_set};

    #[tokio::test]
    async fn default_caches_quote_across_accessors() {
        let provider = CountingProvider::new();
        let ticker = Ticker::builder("AAPL")
            .with_provider_set(provider_set(Arc::clone(&provider)))
            .build()
            .await
            .unwrap();

        let _ = ticker.price().await.unwrap();
        let _ = ticker.summary_detail().await.unwrap();
        let _ = ticker.asset_profile().await.unwrap();

        assert_eq!(provider.quotes(), 1);
    }

    #[tokio::test]
    async fn no_cache_refetches_every_accessor() {
        let provider = CountingProvider::new();
        let ticker = Ticker::builder("AAPL")
            .with_provider_set(provider_set(Arc::clone(&provider)))
            .no_cache()
            .build()
            .await
            .unwrap();

        let _ = ticker.price().await.unwrap();
        let _ = ticker.summary_detail().await.unwrap();
        let _ = ticker.asset_profile().await.unwrap();

        assert_eq!(provider.quotes(), 3);
    }

    #[tokio::test]
    async fn charts_cache_per_interval_and_range() {
        let provider = CountingProvider::new();
        let ticker = Ticker::builder("AAPL")
            .with_provider_set(provider_set(Arc::clone(&provider)))
            .build()
            .await
            .unwrap();

        let _ = ticker
            .chart(Interval::OneDay, TimeRange::OneMonth)
            .await
            .unwrap();
        let _ = ticker
            .chart(Interval::OneDay, TimeRange::OneMonth)
            .await
            .unwrap();
        assert_eq!(provider.charts(), 1);

        let _ = ticker
            .chart(Interval::OneDay, TimeRange::OneYear)
            .await
            .unwrap();
        assert_eq!(provider.charts(), 2);
    }

    #[tokio::test]
    async fn unresolved_logo_is_not_cached() {
        let provider = CountingProvider::new();
        let ticker = Ticker::builder("AAPL")
            .with_provider_set(provider_set(Arc::clone(&provider)))
            .logo()
            .build()
            .await
            .unwrap();

        let _: Quote<crate::format::Raw> = ticker.quote().await.unwrap();
        assert!(
            ticker.logo_cache.read().await.is_none(),
            "an unresolved logo must not be cached, or one blip is permanent"
        );
    }

    #[tokio::test]
    async fn concurrent_chart_misses_dedup_to_one_fetch() {
        let provider = CountingProvider::new();
        let ticker = Arc::new(
            Ticker::builder("AAPL")
                .with_provider_set(provider_set(Arc::clone(&provider)))
                .build()
                .await
                .unwrap(),
        );

        let mut handles = Vec::new();
        for _ in 0..8 {
            let ticker = Arc::clone(&ticker);
            handles.push(tokio::spawn(async move {
                ticker
                    .chart(Interval::OneDay, TimeRange::OneMonth)
                    .await
                    .unwrap()
            }));
        }
        for h in handles {
            h.await.unwrap();
        }

        assert_eq!(provider.charts(), 1);
    }

    #[tokio::test]
    async fn concurrent_news_misses_dedup_to_one_fetch() {
        let provider = CountingProvider::new();
        let ticker = Arc::new(
            Ticker::builder("AAPL")
                .with_provider_set(provider_set(Arc::clone(&provider)))
                .build()
                .await
                .unwrap(),
        );

        let mut handles = Vec::new();
        for _ in 0..8 {
            let ticker = Arc::clone(&ticker);
            handles.push(tokio::spawn(async move { ticker.news().await.unwrap() }));
        }
        for h in handles {
            h.await.unwrap();
        }

        assert_eq!(provider.news(), 1);
    }

    #[tokio::test(start_paused = true)]
    async fn ttl_expires() {
        let provider = CountingProvider::new();
        let ticker = Ticker::builder("AAPL")
            .with_provider_set(provider_set(Arc::clone(&provider)))
            .cache(Duration::from_secs(60))
            .build()
            .await
            .unwrap();

        let _ = ticker
            .chart(Interval::OneDay, TimeRange::OneMonth)
            .await
            .unwrap();
        tokio::time::advance(Duration::from_secs(120)).await;
        let _ = ticker
            .chart(Interval::OneDay, TimeRange::OneMonth)
            .await
            .unwrap();

        assert_eq!(provider.charts(), 2);
    }
}