Skip to main content

Ticker

Struct Ticker 

Source
pub struct Ticker { /* private fields */ }
Expand description

Ticker for fetching symbol-specific data.

Provides access to quotes, charts, financials, news, and other data for a specific symbol. Uses smart lazy loading - quote data is fetched once and cached.

§Example

use finance_query::Ticker;

let ticker = Ticker::new("AAPL").await?;

// Get quote data
let quote = ticker.quote().await?;
println!("Price: {:?}", quote.regular_market_price);

// Get chart data
use finance_query::{Interval, TimeRange};
let chart = ticker.chart(Interval::OneDay, TimeRange::OneMonth).await?;
println!("Candles: {}", chart.candles.len());

Implementations§

Source§

impl Ticker

Source

pub async fn new(symbol: impl Into<String>) -> Result<Self>

Creates a new ticker with default configuration

§Arguments
  • symbol - Stock symbol (e.g., “AAPL”, “MSFT”)
§Examples
use finance_query::Ticker;

let ticker = Ticker::new("AAPL").await?;
Source

pub fn builder(symbol: impl Into<String>) -> TickerBuilder

Creates a new builder for Ticker

Use this for custom configuration (language, region, timeout, proxy).

§Arguments
  • symbol - Stock symbol (e.g., “AAPL”, “MSFT”)
§Examples
use finance_query::Ticker;

// Simple case with defaults (same as new())
let ticker = Ticker::builder("AAPL").build().await?;

// With custom configuration
let ticker = Ticker::builder("AAPL")
    .lang("ja-JP")
    .region_code("JP")
    .build()
    .await?;
Source

pub fn symbol(&self) -> &str

Returns the ticker symbol

Source

pub fn client_handle(&self) -> ClientHandle

Returns a shareable handle to this ticker’s authenticated session.

Pass the handle to other Ticker or Tickers builders via .client() to reuse the same session without re-authenticating.

§Example
use finance_query::Ticker;

let aapl = Ticker::new("AAPL").await?;
let handle = aapl.client_handle();

let msft = Ticker::builder("MSFT").client(handle).build().await?;
Source§

impl Ticker

Source

pub async fn price(&self) -> Result<Option<Price>>

Get price information

Source

pub async fn summary_detail(&self) -> Result<Option<SummaryDetail>>

Get summary detail

Source

pub async fn financial_data(&self) -> Result<Option<FinancialData>>

Get financial data

Source

pub async fn key_stats(&self) -> Result<Option<DefaultKeyStatistics>>

Get key statistics

Source

pub async fn asset_profile(&self) -> Result<Option<AssetProfile>>

Get asset profile

Source

pub async fn calendar_events(&self) -> Result<Option<CalendarEvents>>

Get calendar events

Source

pub async fn earnings(&self) -> Result<Option<Earnings>>

Get earnings

Source

pub async fn earnings_trend(&self) -> Result<Option<EarningsTrend>>

Get earnings trend

Source

pub async fn earnings_history(&self) -> Result<Option<EarningsHistory>>

Get earnings history

Source

pub async fn recommendation_trend(&self) -> Result<Option<RecommendationTrend>>

Get recommendation trend

Source

pub async fn insider_holders(&self) -> Result<Option<InsiderHolders>>

Get insider holders

Source

pub async fn insider_transactions(&self) -> Result<Option<InsiderTransactions>>

Get insider transactions

Source

pub async fn institution_ownership( &self, ) -> Result<Option<InstitutionOwnership>>

Get institution ownership

Source

pub async fn fund_ownership(&self) -> Result<Option<FundOwnership>>

Get fund ownership

Source

pub async fn major_holders(&self) -> Result<Option<MajorHoldersBreakdown>>

Get major holders breakdown

Source

pub async fn share_purchase_activity( &self, ) -> Result<Option<NetSharePurchaseActivity>>

Get net share purchase activity

Source

pub async fn quote_type(&self) -> Result<Option<QuoteTypeData>>

Get quote type

Source

pub async fn summary_profile(&self) -> Result<Option<SummaryProfile>>

Get summary profile

Source

pub async fn sec_filings(&self) -> Result<Option<SecFilings>>

👎Deprecated since 2.2.0: Use edgar_submissions() for comprehensive SEC EDGAR data instead of limited Yahoo Finance metadata

Get SEC filings (limited Yahoo Finance data)

DEPRECATED: This method returns limited SEC filing metadata from Yahoo Finance. For comprehensive filing data directly from SEC EDGAR, use edgar_submissions() instead.

To use EDGAR methods:

edgar::init("user@example.com")?;
let ticker = Ticker::new("AAPL").await?;
let submissions = ticker.edgar_submissions().await?;  // Comprehensive EDGAR data
Source

pub async fn grading_history(&self) -> Result<Option<UpgradeDowngradeHistory>>

Get upgrade/downgrade history

Source

pub async fn fund_performance(&self) -> Result<Option<FundPerformance>>

Get fund performance data (returns, trailing returns, risk statistics)

Primarily relevant for ETFs and mutual funds. Returns None for equities.

Source

pub async fn fund_profile(&self) -> Result<Option<FundProfile>>

Get fund profile (category, family, fees, legal type)

Primarily relevant for ETFs and mutual funds. Returns None for equities.

Source

pub async fn top_holdings(&self) -> Result<Option<TopHoldings>>

Get top holdings for ETFs and mutual funds

Includes top stock/bond holdings with weights and sector weightings. Returns None for equities.

Source

pub async fn index_trend(&self) -> Result<Option<IndexTrend>>

Get index trend data (P/E estimates and growth rates)

Contains trend data for the symbol’s associated index.

Source

pub async fn industry_trend(&self) -> Result<Option<IndustryTrend>>

Get industry trend data

Contains P/E and growth estimates for the symbol’s industry.

Source

pub async fn sector_trend(&self) -> Result<Option<SectorTrend>>

Get sector trend data

Contains P/E and growth estimates for the symbol’s sector.

Source

pub async fn equity_performance(&self) -> Result<Option<EquityPerformance>>

Get equity performance vs benchmark

Performance comparison across multiple time periods.

Source§

impl Ticker

Source

pub async fn quote(&self) -> Result<Quote>

Get full quote data, optionally including logo URLs.

Use TickerBuilder::logo() to enable logo fetching for this ticker instance.

When logos are enabled, fetches both quote summary and logo URL in parallel using tokio::join! for minimal latency impact (~0-100ms overhead).

Source

pub async fn chart(&self, interval: Interval, range: TimeRange) -> Result<Chart>

Get historical chart data

Source

pub async fn chart_range( &self, interval: Interval, start: i64, end: i64, ) -> Result<Chart>

Get historical chart data for a custom date range.

Unlike chart() which uses predefined time ranges, this method accepts absolute start/end timestamps for precise date control.

Results are not cached since custom ranges have unbounded key space.

§Arguments
  • interval - Time interval between data points
  • start - Start date as Unix timestamp (seconds since epoch)
  • end - End date as Unix timestamp (seconds since epoch)
§Example
use finance_query::{Ticker, Interval};
use chrono::NaiveDate;

let ticker = Ticker::new("AAPL").await?;

// Q3 2024
let start = NaiveDate::from_ymd_opt(2024, 7, 1).unwrap()
    .and_hms_opt(0, 0, 0).unwrap().and_utc().timestamp();
let end = NaiveDate::from_ymd_opt(2024, 9, 30).unwrap()
    .and_hms_opt(23, 59, 59).unwrap().and_utc().timestamp();

let chart = ticker.chart_range(Interval::OneDay, start, end).await?;
println!("Q3 2024 candles: {}", chart.candles.len());
Source

pub async fn dividends(&self, range: TimeRange) -> Result<Vec<Dividend>>

Get dividend history

Returns historical dividend payments sorted by date. Events are lazily loaded (fetched once, then filtered by range).

§Arguments
  • range - Time range to filter dividends
§Example
use finance_query::{Ticker, TimeRange};

let ticker = Ticker::new("AAPL").await?;

// Get all dividends
let all = ticker.dividends(TimeRange::Max).await?;

// Get last year's dividends
let recent = ticker.dividends(TimeRange::OneYear).await?;
Source

pub async fn dividend_analytics( &self, range: TimeRange, ) -> Result<DividendAnalytics>

Compute dividend analytics for the requested time range.

Calculates statistics on the dividend history: total paid, payment count, average payment, and Compound Annual Growth Rate (CAGR).

CAGR note: requires at least two payments spanning at least one calendar year.

§Arguments
  • range - Time range to analyse
§Example
use finance_query::{Ticker, TimeRange};

let ticker = Ticker::new("AAPL").await?;
let analytics = ticker.dividend_analytics(TimeRange::FiveYears).await?;

println!("Total paid: ${:.2}", analytics.total_paid);
println!("Payments:   {}", analytics.payment_count);
if let Some(cagr) = analytics.cagr {
    println!("CAGR:       {:.1}%", cagr * 100.0);
}
Source

pub async fn splits(&self, range: TimeRange) -> Result<Vec<Split>>

Get stock split history

Returns historical stock splits sorted by date. Events are lazily loaded (fetched once, then filtered by range).

§Arguments
  • range - Time range to filter splits
§Example
use finance_query::{Ticker, TimeRange};

let ticker = Ticker::new("NVDA").await?;

// Get all splits
let all = ticker.splits(TimeRange::Max).await?;

// Get last 5 years
let recent = ticker.splits(TimeRange::FiveYears).await?;
Source

pub async fn capital_gains(&self, range: TimeRange) -> Result<Vec<CapitalGain>>

Get capital gains distribution history

Returns historical capital gain distributions sorted by date. This is primarily relevant for mutual funds and ETFs. Events are lazily loaded (fetched once, then filtered by range).

§Arguments
  • range - Time range to filter capital gains
§Example
use finance_query::{Ticker, TimeRange};

let ticker = Ticker::new("VFIAX").await?;

// Get all capital gains
let all = ticker.capital_gains(TimeRange::Max).await?;

// Get last 2 years
let recent = ticker.capital_gains(TimeRange::TwoYears).await?;
Source

pub async fn indicators( &self, interval: Interval, range: TimeRange, ) -> Result<IndicatorsSummary>

Calculate all technical indicators from chart data

§Arguments
  • interval - The time interval for each candle
  • range - The time range to fetch data for
§Returns

Returns IndicatorsSummary containing all calculated indicators.

§Example
use finance_query::{Ticker, Interval, TimeRange};

let ticker = Ticker::new("AAPL").await?;
let indicators = ticker.indicators(Interval::OneDay, TimeRange::OneYear).await?;

println!("RSI(14): {:?}", indicators.rsi_14);
println!("MACD: {:?}", indicators.macd);
Source

pub async fn indicator( &self, indicator: Indicator, interval: Interval, range: TimeRange, ) -> Result<IndicatorResult>

Calculate a specific technical indicator over a time range.

Returns the full time series for the requested indicator, not just the latest value. This is useful when you need historical indicator values for analysis or charting.

§Arguments
  • indicator - The indicator to calculate (from crate::indicators::Indicator)
  • interval - Time interval for candles (1d, 1h, etc.)
  • range - Time range for historical data
§Returns

An IndicatorResult containing the full time series. Access the data using match:

  • IndicatorResult::Series(values) - for simple indicators (SMA, EMA, RSI, ATR, OBV, VWAP, WMA)
  • IndicatorResult::Macd(data) - for MACD (macd_line, signal_line, histogram)
  • IndicatorResult::Bollinger(data) - for Bollinger Bands (upper, middle, lower)
§Example
use finance_query::{Ticker, Interval, TimeRange};
use finance_query::indicators::{Indicator, IndicatorResult};

let ticker = Ticker::new("AAPL").await?;

// Calculate 14-period RSI
let result = ticker.indicator(
    Indicator::Rsi(14),
    Interval::OneDay,
    TimeRange::ThreeMonths
).await?;

match result {
    IndicatorResult::Series(values) => {
        println!("Latest RSI: {:?}", values.last());
    }
    _ => {}
}

// Calculate MACD
let macd_result = ticker.indicator(
    Indicator::Macd { fast: 12, slow: 26, signal: 9 },
    Interval::OneDay,
    TimeRange::SixMonths
).await?;
Source

pub async fn recommendations(&self, limit: u32) -> Result<Recommendation>

Get analyst recommendations

Source

pub async fn financials( &self, statement_type: StatementType, frequency: Frequency, ) -> Result<FinancialStatement>

Get financial statements

§Arguments
  • statement_type - Type of statement (Income, Balance, CashFlow)
  • frequency - Annual or Quarterly
§Example
use finance_query::{Ticker, Frequency, StatementType};

let ticker = Ticker::new("AAPL").await?;
let income = ticker.financials(StatementType::Income, Frequency::Annual).await?;
println!("Revenue: {:?}", income.statement.get("TotalRevenue"));
Source

pub async fn news(&self) -> Result<Vec<News>>

Get news articles for this symbol

§Example
use finance_query::Ticker;

let ticker = Ticker::new("AAPL").await?;
let news = ticker.news().await?;
for article in news {
    println!("{}: {}", article.source, article.title);
}
Source

pub async fn options(&self, date: Option<i64>) -> Result<Options>

Get options chain

Source

pub async fn backtest<S: Strategy>( &self, strategy: S, interval: Interval, range: TimeRange, config: Option<BacktestConfig>, ) -> Result<BacktestResult>

Run a backtest with the given strategy and configuration.

§Arguments
  • strategy - Trading strategy implementing the Strategy trait
  • interval - Candle interval (1d, 1h, etc.)
  • range - Time range for historical data
  • config - Backtest configuration (optional, uses defaults if None)
§Example
use finance_query::{Ticker, Interval, TimeRange};
use finance_query::backtesting::{SmaCrossover, BacktestConfig};

let ticker = Ticker::new("AAPL").await?;

// Simple backtest with defaults
let strategy = SmaCrossover::new(10, 20);
let result = ticker.backtest(
    strategy,
    Interval::OneDay,
    TimeRange::OneYear,
    None,
).await?;

println!("{}", result.summary());
println!("Total trades: {}", result.trades.len());

// With custom config
let config = BacktestConfig::builder()
    .initial_capital(50_000.0)
    .commission_pct(0.001)
    .stop_loss_pct(0.05)
    .allow_short(true)
    .build()?;

let result = ticker.backtest(
    SmaCrossover::new(5, 20).with_short(true),
    Interval::OneDay,
    TimeRange::TwoYears,
    Some(config),
).await?;
Source

pub async fn risk( &self, interval: Interval, range: TimeRange, benchmark: Option<&str>, ) -> Result<RiskSummary>

Compute a risk summary for this symbol.

Requires the risk feature flag.

Calculates Value at Risk, Sharpe/Sortino/Calmar ratios, and maximum drawdown from close-to-close returns derived from the requested chart data.

§Arguments
  • interval - Candle interval (use Interval::OneDay for daily risk metrics)
  • range - Historical range to analyse
  • benchmark - Optional symbol to use as the benchmark for beta calculation
§Example
use finance_query::{Ticker, Interval, TimeRange};

let ticker = Ticker::new("AAPL").await?;

// Risk vs no benchmark
let summary = ticker.risk(Interval::OneDay, TimeRange::OneYear, None).await?;
println!("VaR 95%:      {:.2}%", summary.var_95 * 100.0);
println!("Max drawdown: {:.2}%", summary.max_drawdown * 100.0);

// Risk with S&P 500 as benchmark
let summary = ticker.risk(Interval::OneDay, TimeRange::OneYear, Some("^GSPC")).await?;
println!("Beta: {:?}", summary.beta);
Source

pub async fn edgar_submissions(&self) -> Result<EdgarSubmissions>

Get SEC EDGAR filing history for this symbol.

Returns company metadata and recent filings. Results are cached for the lifetime of this Ticker instance.

Requires EDGAR to be initialized via edgar::init(email).

§Example
use finance_query::{Ticker, edgar};

edgar::init("user@example.com")?;
let ticker = Ticker::new("AAPL").await?;

let submissions = ticker.edgar_submissions().await?;
println!("Company: {:?}", submissions.name);
Source

pub async fn edgar_company_facts(&self) -> Result<CompanyFacts>

Get SEC EDGAR company facts (structured XBRL financial data) for this symbol.

Returns all extracted XBRL facts organized by taxonomy. Results are cached for the lifetime of this Ticker instance.

Requires EDGAR to be initialized via edgar::init(email).

§Example
use finance_query::{Ticker, edgar};

edgar::init("user@example.com")?;
let ticker = Ticker::new("AAPL").await?;

let facts = ticker.edgar_company_facts().await?;
if let Some(revenue) = facts.get_us_gaap_fact("Revenue") {
    println!("Revenue data points: {:?}", revenue.units.keys().collect::<Vec<_>>());
}
Source

pub async fn clear_cache(&self)

Clear all cached data, forcing fresh fetches on next access.

Use this when you need up-to-date data from a long-lived Ticker instance.

§Example
use finance_query::Ticker;

let ticker = Ticker::new("AAPL").await?;
let quote = ticker.quote().await?; // fetches from API

// ... some time later ...
ticker.clear_cache().await;
let fresh_quote = ticker.quote().await?; // fetches again
Source

pub async fn clear_quote_cache(&self)

Clear only the cached quote summary data.

The next call to any quote accessor (e.g., price(), financial_data()) will re-fetch all quote modules from the API.

Source

pub async fn clear_chart_cache(&self)

Clear only the cached chart and events data.

The next call to chart(), dividends(), splits(), or capital_gains() will re-fetch from the API.

Trait Implementations§

Source§

impl Clone for Ticker

Source§

fn clone(&self) -> Ticker

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Key for T
where T: Clone,

Source§

fn align() -> usize

The alignment necessary for the key. Must return a power of two.
Source§

fn size(&self) -> usize

The size of the key in bytes.
Source§

unsafe fn init(&self, ptr: *mut u8)

Initialize the key in the given memory location. Read more
Source§

unsafe fn get<'a>(ptr: *const u8) -> &'a T

Get a reference to the key from the given memory location. Read more
Source§

unsafe fn drop_in_place(ptr: *mut u8)

Drop the key in place. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> PlanCallbackArgs for T

Source§

impl<T> PlanCallbackOut for T