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
mod actions;
mod adjust;
mod assemble;
mod fetch;

use crate::core::yahoo_vocab::{first_parsed_yahoo_exchange, parse_yahoo_quote_type};
use crate::core::{
    CallOptions, DataQuality, ProjectionContext, ProjectionIssue, YfClient, YfError, YfResponse,
};
use crate::core::{
    client::normalize_symbol,
    currency_resolver::{
        CorporateActionCurrencyEvidence, CurrencyHints, CurrencyPurpose, ResolvedCurrencyUnit,
        TradingCurrencyEvidence, project_currency_resolution,
    },
};
use crate::history::YahooHistoryResponse;
use crate::history::wire::MetaNode;
use chrono_tz::Tz;
use paft::domain::Instrument;
use paft::market::action::Action;
use paft::market::requests::history::{Interval, Range};
use paft::market::responses::history::{
    Candle, HistoryMeta, HistoryResponse, OhlcPriceBasis, PriceBasis,
};

use actions::extract_actions;
use adjust::{AdjustmentBasis, AdjustmentPlan, cumulative_split_after};
use assemble::{adjustment_plan_for_series, assemble_candles};
use fetch::{ChartFetchRequest, fetch_chart};

/// A builder for fetching historical price data for a single symbol.
///
/// This builder provides fine-grained control over the parameters for a historical
/// data request, including the time range, interval, and data adjustments.
#[derive(Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct HistoryBuilder {
    #[doc(hidden)]
    pub(crate) client: YfClient,
    #[doc(hidden)]
    pub(crate) symbol: String,
    #[doc(hidden)]
    pub(crate) range: Option<Range>,
    #[doc(hidden)]
    pub(crate) period: Option<(i64, i64)>,
    #[doc(hidden)]
    pub(crate) interval: Interval,
    #[doc(hidden)]
    pub(crate) auto_adjust: bool,
    #[doc(hidden)]
    pub(crate) include_prepost: bool,
    #[doc(hidden)]
    pub(crate) include_actions: bool,
    #[doc(hidden)]
    options: CallOptions,
}

impl HistoryBuilder {
    /// Creates a new `HistoryBuilder` for a given symbol.
    pub fn new(client: &YfClient, symbol: impl Into<String>) -> Self {
        Self {
            client: client.clone(),
            symbol: symbol.into(),
            range: Some(Range::M6),
            period: None,
            interval: Interval::D1,
            auto_adjust: true,
            include_prepost: false,
            include_actions: true,
            options: CallOptions::default(),
        }
    }

    crate::core::impl_call_option_setters!();

    /// Sets a relative time range for the request (e.g., `1y`, `6mo`).
    ///
    /// This will override any previously set period using `between()`.
    #[must_use]
    pub const fn range(mut self, range: Range) -> Self {
        self.period = None;
        self.range = Some(range);
        self
    }

    /// Sets an absolute time period for the request using start and end timestamps.
    ///
    /// This will override any previously set range using `range()`.
    #[must_use]
    pub const fn between(
        mut self,
        start: chrono::DateTime<chrono::Utc>,
        end: chrono::DateTime<chrono::Utc>,
    ) -> Self {
        self.range = None;
        self.period = Some((start.timestamp(), end.timestamp()));
        self
    }

    /// Sets the time interval for each data point (candle).
    #[must_use]
    pub const fn interval(mut self, interval: Interval) -> Self {
        self.interval = interval;
        self
    }

    /// Sets whether to automatically adjust prices for splits and dividends. (Default: `true`)
    #[must_use]
    pub const fn auto_adjust(mut self, yes: bool) -> Self {
        self.auto_adjust = yes;
        self
    }

    /// Sets whether to include pre-market and post-market data for intraday intervals. (Default: `false`)
    #[must_use]
    pub const fn prepost(mut self, yes: bool) -> Self {
        self.include_prepost = yes;
        self
    }

    /// Sets whether to include corporate actions (dividends and splits) in the response. (Default: `true`)
    #[must_use]
    pub const fn actions(mut self, yes: bool) -> Self {
        self.include_actions = yes;
        self
    }

    /// Executes the request and returns only the price candles.
    ///
    /// # Errors
    ///
    /// Returns a `YfError` if the network request fails or the API response cannot be parsed.
    pub async fn fetch(&self) -> Result<Vec<Candle>, YfError> {
        Ok(self.fetch_with_diagnostics().await?.into_data())
    }

    /// Executes the request and returns candles with projection diagnostics.
    ///
    /// # Errors
    ///
    /// Returns a `YfError` if the network request fails, the API returns an error,
    /// or strict data-quality mode rejects a projection issue.
    pub async fn fetch_with_diagnostics(&self) -> Result<YfResponse<Vec<Candle>>, YfError> {
        Ok(self
            .fetch_full_with_diagnostics()
            .await?
            .map(|resp| resp.candles))
    }

    /// Executes the request and returns the full response, including candles, actions, and metadata.
    ///
    /// # Errors
    ///
    /// Returns a `YfError` if the network request fails, the API returns an error,
    /// or the response cannot be parsed.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(
            skip(self),
            err,
            fields(
                symbol = %self.symbol,
                interval = %format!("{:?}", self.interval),
                range = %self
                    .range
                    .as_ref()
                    .map_or_else(|| "period".into(), |r| format!("{r:?}"))
            )
        )
    )]
    pub async fn fetch_full(&self) -> Result<HistoryResponse, YfError> {
        Ok(self.fetch_full_with_diagnostics().await?.into_data())
    }

    /// Executes the request and returns the full response with projection diagnostics.
    ///
    /// # Errors
    ///
    /// Returns a `YfError` if the network request fails, the API returns an error,
    /// or strict data-quality mode rejects a projection issue.
    pub async fn fetch_full_with_diagnostics(
        &self,
    ) -> Result<YfResponse<HistoryResponse>, YfError> {
        Ok(self
            .fetch_full_yahoo_with_diagnostics()
            .await?
            .map(|history| history.response))
    }

    pub(crate) async fn fetch_full_yahoo_with_diagnostics(
        &self,
    ) -> Result<YfResponse<YahooHistoryResponse>, YfError> {
        let mut ctx = ProjectionContext::new("history_chart", self.options.data_quality());
        let symbol = normalize_symbol(&self.symbol)?;

        // 1) Fetch and parse the /chart payload into owned blocks
        let fetched = fetch_chart(
            &self.client,
            &symbol,
            ChartFetchRequest {
                range: self.range,
                period: self.period,
                interval: self.interval,
                include_actions: self.include_actions,
                include_prepost: self.include_prepost,
            },
            &self.options,
        )
        .await?;

        let instrument = store_history_side_effects(&self.client, &symbol, fetched.meta.as_ref());

        // 2) Corporate actions & split ratios
        let chart_currency = fetched.meta.as_ref().and_then(|m| m.currency.as_deref());
        let has_complete_candle = has_complete_ohlc_row(&fetched.quote, fetched.ts.len());
        let currency = if has_complete_candle {
            history_trading_currency(
                &self.client,
                &symbol,
                chart_currency,
                &self.options,
                &mut ctx,
            )
            .await?
        } else {
            None
        };
        let action_currency = action_default_currency(
            &self.client,
            &symbol,
            fetched.events.as_ref(),
            chart_currency,
            currency.as_ref(),
            &self.options,
            &mut ctx,
        )
        .await?;

        let (mut actions_out, split_events) =
            extract_actions(fetched.events.as_ref(), action_currency.as_ref(), &mut ctx)?;

        // 3) Cumulative split factors after each bar
        let cum_split_after = cumulative_split_after(&fetched.ts, &split_events);

        // 4) Assemble candles (+ raw close) with/without adjustments
        let mut adjustment_basis = None;
        let candles = if let Some(currency) = currency.as_ref() {
            let adjustment_plan = history_adjustment_plan(
                self.auto_adjust,
                &fetched.quote,
                &fetched.adjclose,
                fetched.ts.len(),
                &mut ctx,
            )?;
            adjustment_basis = adjustment_plan.as_ref().map(AdjustmentPlan::basis);
            assemble_candles(
                &fetched.ts,
                &fetched.quote,
                adjustment_plan.as_ref(),
                &cum_split_after,
                currency,
                &mut ctx,
            )?
        } else {
            if !has_complete_candle && has_any_ohlc_value(&fetched.quote, fetched.ts.len()) {
                ctx.dropped_item(
                    "candle",
                    None,
                    ProjectionIssue::MissingRequiredFields {
                        fields: vec!["open", "high", "low", "close"],
                    },
                )?;
            }
            Vec::new()
        };

        // ensure actions sorted (extract_actions already sorts, keep consistent)
        actions_out.sort_by_key(action_sort_key);

        // 5) Map metadata
        let meta_out = map_meta(fetched.meta.as_ref(), &mut ctx)?;
        let price_hint = fetched
            .meta
            .as_ref()
            .and_then(|meta| u32::try_from(meta.price_hint?).ok());
        let price_basis = history_price_basis(adjustment_basis, &cum_split_after);

        Ok(ctx.finish(YahooHistoryResponse {
            response: HistoryResponse {
                candles,
                actions: actions_out,
                price_basis,
                meta: meta_out,
                provider: (),
            },
            price_hint,
            currency_unit: currency,
            instrument,
        }))
    }
}

/* --- tiny private helper --- */

fn has_complete_ohlc_row(quote: &crate::history::wire::QuoteBlock, len: usize) -> bool {
    (0..len).any(|idx| {
        quote.open.get(idx).and_then(|value| *value).is_some()
            && quote.high.get(idx).and_then(|value| *value).is_some()
            && quote.low.get(idx).and_then(|value| *value).is_some()
            && quote.close.get(idx).and_then(|value| *value).is_some()
    })
}

fn has_any_ohlc_value(quote: &crate::history::wire::QuoteBlock, len: usize) -> bool {
    (0..len).any(|idx| {
        quote.open.get(idx).and_then(|value| *value).is_some()
            || quote.high.get(idx).and_then(|value| *value).is_some()
            || quote.low.get(idx).and_then(|value| *value).is_some()
            || quote.close.get(idx).and_then(|value| *value).is_some()
    })
}

const fn action_sort_key(action: &Action) -> (bool, chrono::NaiveDate) {
    match action {
        Action::Dividend { date, .. }
        | Action::Split { date, .. }
        | Action::CapitalGain { date, .. } => (false, *date),
        _ => (true, chrono::NaiveDate::MAX),
    }
}

fn history_price_basis(
    adjustment_basis: Option<AdjustmentBasis>,
    cum_split_after: &[f64],
) -> OhlcPriceBasis {
    match adjustment_basis {
        Some(AdjustmentBasis::ProviderAdjusted) => {
            OhlcPriceBasis::uniform(PriceBasis::provider_latest_adjusted())
        }
        Some(AdjustmentBasis::SplitAdjusted)
            if cum_split_after
                .iter()
                .any(|factor| (*factor - 1.0).abs() > f64::EPSILON) =>
        {
            OhlcPriceBasis::uniform(PriceBasis::split_adjusted_latest())
        }
        None | Some(AdjustmentBasis::SplitAdjusted) => OhlcPriceBasis::raw(),
    }
}

fn store_history_side_effects(
    client: &YfClient,
    symbol: &str,
    meta: Option<&MetaNode>,
) -> Option<Instrument> {
    let instrument = history_instrument_from_meta(symbol, meta);
    if let (Some(meta), Some(instrument)) = (meta, instrument.as_ref()) {
        store_history_instrument(client, symbol, meta, instrument);
    }
    if let Some(meta) = meta {
        client.store_currency_hints(
            symbol,
            CurrencyHints::from_chart(
                meta.currency.as_deref(),
                meta.exchange_name.as_deref(),
                meta.full_exchange_name.as_deref(),
                meta.instrument_type.as_deref(),
            ),
        );
    }
    instrument
}

fn history_adjustment_plan(
    auto_adjust: bool,
    quote: &crate::history::wire::QuoteBlock,
    adjclose: &[Option<f64>],
    len: usize,
    ctx: &mut ProjectionContext,
) -> Result<Option<AdjustmentPlan>, YfError> {
    if auto_adjust {
        adjustment_plan_for_series(quote, adjclose, len, ctx).map(Some)
    } else {
        Ok(None)
    }
}

async fn history_trading_currency(
    client: &YfClient,
    symbol: &str,
    chart_currency: Option<&str>,
    options: &CallOptions,
    ctx: &mut ProjectionContext,
) -> Result<Option<ResolvedCurrencyUnit>, YfError> {
    let projected = project_currency_resolution(
        ctx,
        symbol,
        CurrencyPurpose::Trading,
        chart_currency,
        client
            .resolve_trading_currency(
                symbol,
                None,
                TradingCurrencyEvidence::ChartMeta(chart_currency),
                options,
            )
            .await,
    )?;

    let issue = projected.issue().cloned();
    if let Some(currency) = projected.into_unit() {
        return Ok(Some(currency));
    }

    ctx.dropped_item(
        "candle",
        None,
        issue.unwrap_or(ProjectionIssue::CurrencyUnresolved),
    )?;
    Ok(None)
}

async fn action_default_currency(
    client: &YfClient,
    symbol: &str,
    events: Option<&crate::history::wire::Events>,
    chart_currency: Option<&str>,
    trading_currency: Option<&ResolvedCurrencyUnit>,
    options: &CallOptions,
    ctx: &mut ProjectionContext,
) -> Result<Option<ResolvedCurrencyUnit>, YfError> {
    if !events_need_default_currency(events) {
        return Ok(trading_currency.cloned());
    }

    if let Some(currency) = trading_currency {
        return Ok(Some(currency.clone()));
    }

    match client
        .resolve_corporate_action_currency(
            symbol,
            None,
            CorporateActionCurrencyEvidence::ChartMeta(chart_currency),
            options,
        )
        .await
    {
        Ok(currency) => {
            ctx.currency_resolution(symbol, CurrencyPurpose::CorporateAction, &currency)?;
            Ok(Some(currency.into_unit()))
        }
        Err(err) => {
            if ctx.policy() == DataQuality::Strict {
                Err(err)
            } else {
                ctx.omitted_present_field(
                    "chart.meta.currency",
                    None,
                    ProjectionIssue::ProviderError {
                        message: err.to_string(),
                    },
                )?;
                Ok(None)
            }
        }
    }
}

fn events_need_default_currency(events: Option<&crate::history::wire::Events>) -> bool {
    let Some(events) = events else {
        return false;
    };

    events.dividends.as_ref().is_some_and(|events| {
        events
            .values()
            .any(|event| event.amount.is_some() && is_missing_currency(event.currency.as_deref()))
    }) || events.capital_gains.as_ref().is_some_and(|events| {
        events
            .values()
            .any(|event| event.amount.is_some() && is_missing_currency(event.currency.as_deref()))
    })
}

fn is_missing_currency(currency: Option<&str>) -> bool {
    currency.is_none_or(|currency| currency.trim().is_empty())
}

fn map_meta(
    meta: Option<&MetaNode>,
    ctx: &mut ProjectionContext,
) -> Result<Option<HistoryMeta>, YfError> {
    let Some(meta) = meta else {
        return Ok(None);
    };

    let timezone = parse_history_timezone(meta, ctx)?;

    Ok(Some(HistoryMeta {
        timezone,
        utc_offset_seconds: meta.gmtoffset,
    }))
}

fn parse_history_timezone(
    meta: &MetaNode,
    ctx: &mut ProjectionContext,
) -> Result<Option<Tz>, YfError> {
    for (path, field, value) in [
        (
            "chart.meta.exchangeTimezoneName",
            "exchangeTimezoneName",
            meta.exchange_timezone_name.as_deref(),
        ),
        ("chart.meta.timezone", "timezone", meta.timezone.as_deref()),
    ] {
        let Some(timezone) = value.map(str::trim).filter(|timezone| !timezone.is_empty()) else {
            continue;
        };

        match timezone.parse::<Tz>() {
            Ok(timezone) => return Ok(Some(timezone)),
            Err(err) => {
                ctx.omitted_present_field(
                    path,
                    meta.symbol.as_deref(),
                    ProjectionIssue::InvalidField {
                        field,
                        details: err.to_string(),
                    },
                )?;
            }
        }
    }

    Ok(None)
}

fn history_instrument_from_meta(
    requested_symbol: &str,
    meta: Option<&MetaNode>,
) -> Option<Instrument> {
    let meta = meta?;
    let instrument_type = meta
        .instrument_type
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())?;
    let kind = parse_yahoo_quote_type(instrument_type).ok()?;

    let exchange = first_parsed_yahoo_exchange([
        meta.full_exchange_name.as_deref(),
        meta.exchange_name.as_deref(),
    ]);

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

    instrument.ok()
}

fn store_history_instrument(
    client: &YfClient,
    requested_symbol: &str,
    meta: &MetaNode,
    instrument: &Instrument,
) {
    client.store_instrument(requested_symbol.to_string(), instrument.clone());
    if let Some(provider_symbol) = meta
        .symbol
        .as_deref()
        .map(str::trim)
        .filter(|symbol| !symbol.is_empty() && *symbol != requested_symbol)
    {
        client.store_instrument(provider_symbol.to_string(), instrument.clone());
    }
}