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
impl Ticker
Sourcepub fn builder(symbol: impl Into<String>) -> TickerBuilder
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?;Sourcepub fn client_handle(&self) -> ClientHandle
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
impl Ticker
Sourcepub async fn summary_detail(&self) -> Result<Option<SummaryDetail>>
pub async fn summary_detail(&self) -> Result<Option<SummaryDetail>>
Get summary detail
Sourcepub async fn financial_data(&self) -> Result<Option<FinancialData>>
pub async fn financial_data(&self) -> Result<Option<FinancialData>>
Get financial data
Sourcepub async fn asset_profile(&self) -> Result<Option<AssetProfile>>
pub async fn asset_profile(&self) -> Result<Option<AssetProfile>>
Get asset profile
Sourcepub async fn calendar_events(&self) -> Result<Option<CalendarEvents>>
pub async fn calendar_events(&self) -> Result<Option<CalendarEvents>>
Get calendar events
Sourcepub async fn earnings_trend(&self) -> Result<Option<EarningsTrend>>
pub async fn earnings_trend(&self) -> Result<Option<EarningsTrend>>
Get earnings trend
Sourcepub async fn earnings_history(&self) -> Result<Option<EarningsHistory>>
pub async fn earnings_history(&self) -> Result<Option<EarningsHistory>>
Get earnings history
Sourcepub async fn recommendation_trend(&self) -> Result<Option<RecommendationTrend>>
pub async fn recommendation_trend(&self) -> Result<Option<RecommendationTrend>>
Get recommendation trend
Sourcepub async fn insider_holders(&self) -> Result<Option<InsiderHolders>>
pub async fn insider_holders(&self) -> Result<Option<InsiderHolders>>
Get insider holders
Sourcepub async fn insider_transactions(&self) -> Result<Option<InsiderTransactions>>
pub async fn insider_transactions(&self) -> Result<Option<InsiderTransactions>>
Get insider transactions
Sourcepub async fn institution_ownership(
&self,
) -> Result<Option<InstitutionOwnership>>
pub async fn institution_ownership( &self, ) -> Result<Option<InstitutionOwnership>>
Get institution ownership
Sourcepub async fn fund_ownership(&self) -> Result<Option<FundOwnership>>
pub async fn fund_ownership(&self) -> Result<Option<FundOwnership>>
Get fund ownership
Sourcepub async fn major_holders(&self) -> Result<Option<MajorHoldersBreakdown>>
pub async fn major_holders(&self) -> Result<Option<MajorHoldersBreakdown>>
Get major holders breakdown
Get net share purchase activity
Sourcepub async fn quote_type(&self) -> Result<Option<QuoteTypeData>>
pub async fn quote_type(&self) -> Result<Option<QuoteTypeData>>
Get quote type
Sourcepub async fn summary_profile(&self) -> Result<Option<SummaryProfile>>
pub async fn summary_profile(&self) -> Result<Option<SummaryProfile>>
Get summary profile
Sourcepub 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
pub async fn sec_filings(&self) -> Result<Option<SecFilings>>
edgar_submissions() for comprehensive SEC EDGAR data instead of limited Yahoo Finance metadataGet 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 dataSourcepub async fn grading_history(&self) -> Result<Option<UpgradeDowngradeHistory>>
pub async fn grading_history(&self) -> Result<Option<UpgradeDowngradeHistory>>
Get upgrade/downgrade history
Sourcepub async fn fund_performance(&self) -> Result<Option<FundPerformance>>
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.
Sourcepub async fn fund_profile(&self) -> Result<Option<FundProfile>>
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.
Sourcepub async fn top_holdings(&self) -> Result<Option<TopHoldings>>
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.
Sourcepub async fn index_trend(&self) -> Result<Option<IndexTrend>>
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.
Sourcepub async fn industry_trend(&self) -> Result<Option<IndustryTrend>>
pub async fn industry_trend(&self) -> Result<Option<IndustryTrend>>
Get industry trend data
Contains P/E and growth estimates for the symbol’s industry.
Sourcepub async fn sector_trend(&self) -> Result<Option<SectorTrend>>
pub async fn sector_trend(&self) -> Result<Option<SectorTrend>>
Get sector trend data
Contains P/E and growth estimates for the symbol’s sector.
Sourcepub async fn equity_performance(&self) -> Result<Option<EquityPerformance>>
pub async fn equity_performance(&self) -> Result<Option<EquityPerformance>>
Get equity performance vs benchmark
Performance comparison across multiple time periods.
Source§impl Ticker
impl Ticker
Sourcepub async fn quote(&self) -> Result<Quote>
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).
Sourcepub async fn chart(&self, interval: Interval, range: TimeRange) -> Result<Chart>
pub async fn chart(&self, interval: Interval, range: TimeRange) -> Result<Chart>
Get historical chart data
Sourcepub async fn chart_range(
&self,
interval: Interval,
start: i64,
end: i64,
) -> Result<Chart>
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 pointsstart- 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());Sourcepub async fn dividends(&self, range: TimeRange) -> Result<Vec<Dividend>>
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?;Sourcepub async fn dividend_analytics(
&self,
range: TimeRange,
) -> Result<DividendAnalytics>
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);
}Sourcepub async fn splits(&self, range: TimeRange) -> Result<Vec<Split>>
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?;Sourcepub async fn capital_gains(&self, range: TimeRange) -> Result<Vec<CapitalGain>>
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?;Sourcepub async fn indicators(
&self,
interval: Interval,
range: TimeRange,
) -> Result<IndicatorsSummary>
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 candlerange- 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);Sourcepub async fn indicator(
&self,
indicator: Indicator,
interval: Interval,
range: TimeRange,
) -> Result<IndicatorResult>
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 (fromcrate::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?;
Sourcepub async fn recommendations(&self, limit: u32) -> Result<Recommendation>
pub async fn recommendations(&self, limit: u32) -> Result<Recommendation>
Get analyst recommendations
Sourcepub async fn financials(
&self,
statement_type: StatementType,
frequency: Frequency,
) -> Result<FinancialStatement>
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"));Sourcepub async fn news(&self) -> Result<Vec<News>>
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);
}Sourcepub async fn backtest<S: Strategy>(
&self,
strategy: S,
interval: Interval,
range: TimeRange,
config: Option<BacktestConfig>,
) -> Result<BacktestResult>
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 traitinterval- Candle interval (1d, 1h, etc.)range- Time range for historical dataconfig- 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?;Sourcepub async fn risk(
&self,
interval: Interval,
range: TimeRange,
benchmark: Option<&str>,
) -> Result<RiskSummary>
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 (useInterval::OneDayfor daily risk metrics)range- Historical range to analysebenchmark- 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);Sourcepub async fn edgar_submissions(&self) -> Result<EdgarSubmissions>
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);Sourcepub async fn edgar_company_facts(&self) -> Result<CompanyFacts>
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<_>>());
}Sourcepub async fn clear_cache(&self)
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 againSourcepub async fn clear_quote_cache(&self)
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.
Sourcepub async fn clear_chart_cache(&self)
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§
Auto Trait Implementations§
impl Freeze for Ticker
impl !RefUnwindSafe for Ticker
impl Send for Ticker
impl Sync for Ticker
impl Unpin for Ticker
impl UnsafeUnpin for Ticker
impl !UnwindSafe for Ticker
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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