finance-query API reference#
Generated by
cargo soothfast docs referenceMeasurements and verified claims come from the latest baseline; CI gates them.
finance_query#
AnalystEstimate struct#
pub struct AnalystEstimate
AnalystRecommendation struct#
pub struct AnalystRecommendation
AroonData struct#
pub struct AroonData
AssetClass enum#
pub enum AssetClass
BatchCapitalGainsResponse struct#
define_batch_response!
BatchChartsResponse struct#
define_batch_response!
BatchDividendsResponse struct#
define_batch_response!
BatchFinancialsResponse struct#
define_batch_response!
BatchIndicatorsResponse struct#
define_batch_response!
BatchNewsResponse struct#
define_batch_response!
BatchOptionsResponse struct#
define_batch_response!
BatchQuotesResponse struct#
define_batch_response!
BatchRecommendationsResponse struct#
define_batch_response!
BatchSparksResponse struct#
define_batch_response!
BatchSplitsResponse struct#
define_batch_response!
BollingerBands struct#
pub struct BollingerBands
BollingerBandsData struct#
pub struct BollingerBandsData
BullBearPowerData struct#
pub struct BullBearPowerData
CalendarDetail enum#
pub enum CalendarDetail
CalendarEvent struct#
pub struct CalendarEvent
CalendarKind enum#
pub enum CalendarKind
Candle struct#
pub struct Candle
CandlePattern enum#
pub enum CandlePattern
Capability struct#
pub struct Capability(u32)
CapitalGain struct#
pub struct CapitalGain
Chart struct#
pub struct Chart
ChartEvents struct#
pub struct ChartEvents
ChartMeta struct#
pub struct ChartMeta
CikEntry struct#
pub struct CikEntry
ClientHandle struct#
pub struct ClientHandle(pub(crate) Arc<YahooClient>)
CommitmentsOfTraders struct#
pub struct CommitmentsOfTraders
Commodity struct#
domain_handle!
CommodityQuote struct#
pub struct CommodityQuote
CompanyFacts struct#
pub struct CompanyFacts
CompanyProfile struct#
pub struct CompanyProfile
ConditionValue enum#
pub enum ConditionValue
CongressionalTrade struct#
pub struct CongressionalTrade
Contracts struct#
pub struct Contracts(pub Vec<OptionContract>)
CotObservation struct#
pub struct CotObservation
CryptoCoin struct#
domain_handle!
CryptoProvider trait#
pub trait CryptoProvider: ProviderCore
CryptoQuote struct#
pub struct CryptoQuote
Currency struct#
pub struct Currency
CustomId struct#
pub struct CustomId(u16)
Discovery struct#
domain_handle!
Dividend struct#
pub struct Dividend
DividendAnalytics struct#
pub struct DividendAnalytics
DonchianChannelsData struct#
pub struct DonchianChannelsData
EarningsCalendarEntry struct#
pub struct EarningsCalendarEntry
EarningsSurprise struct#
pub struct EarningsSurprise
EarningsTranscript struct#
pub struct EarningsTranscript
EconomicCatalog struct#
pub struct EconomicCatalog
EconomicCategory struct#
pub struct EconomicCategory
EconomicIndicator struct#
domain_handle!
EconomicProvider trait#
pub trait EconomicProvider: ProviderCore
EconomicRelease struct#
pub struct EconomicRelease
EconomicSeries struct#
pub struct EconomicSeries
EconomicSeriesMatch struct#
pub struct EconomicSeriesMatch
EdgarFiling struct#
pub struct EdgarFiling
EdgarFilingFile struct#
pub struct EdgarFilingFile
EdgarFilingIndex struct#
pub struct EdgarFilingIndex
EdgarFilingIndexItem struct#
pub struct EdgarFilingIndexItem
EdgarFilingRecent struct#
pub struct EdgarFilingRecent
EdgarFilings struct#
pub struct EdgarFilings
EdgarSearchHit struct#
pub struct EdgarSearchHit
EdgarSearchHitsContainer struct#
pub struct EdgarSearchHitsContainer
EdgarSearchResults struct#
pub struct EdgarSearchResults
EdgarSearchSource struct#
pub struct EdgarSearchSource
EdgarSearchTotal struct#
pub struct EdgarSearchTotal
EdgarSubmissions struct#
pub struct EdgarSubmissions
ElderRayData struct#
pub struct ElderRayData
EmployeeCount struct#
pub struct EmployeeCount
EquityField enum#
pub enum EquityField
EquityScreenerQuery type_alias#
pub type EquityScreenerQuery = ScreenerQuery<EquityField>
ErrorCategory enum#
pub enum ErrorCategory
EtfCountryWeighting struct#
pub struct EtfCountryWeighting
EtfHolding struct#
pub struct EtfHolding
EtfProfile struct#
pub struct EtfProfile
EtfSectorWeighting struct#
pub struct EtfSectorWeighting
EventKind enum#
pub enum EventKind
Exchange struct#
pub struct Exchange
ExchangeCode enum#
pub enum ExchangeCode
ExchangeInfo struct#
pub struct ExchangeInfo
ExecutiveCompensation struct#
pub struct ExecutiveCompensation
FactConcept struct#
pub struct FactConcept
FactUnit struct#
pub struct FactUnit
FactsByTaxonomy struct#
pub struct FactsByTaxonomy(pub HashMap<String, FactConcept>)
FailToDeliver struct#
pub struct FailToDeliver
FearAndGreed struct#
pub struct FearAndGreed
FearGreedLabel enum#
pub enum FearGreedLabel
Fetch enum#
pub enum Fetch
FilingSearchFilters struct#
pub struct FilingSearchFilters
FilingSearchHit struct#
pub struct FilingSearchHit
FilingSection struct#
pub struct FilingSection
FilingSectionForm enum#
pub enum FilingSectionForm
Filings struct#
domain_handle!
FinanceError enum#
pub enum FinanceError
FinancialRatiosTtm struct#
pub struct FinancialRatiosTtm
FinancialStatement struct#
pub struct FinancialStatement
ForexPair struct#
domain_handle!
ForexProvider trait#
pub trait ForexProvider: ProviderCore
ForexQuote struct#
pub struct ForexQuote
FormattedValue struct#
pub struct FormattedValue<T>
Frequency enum#
pub enum Frequency
FundField enum#
pub enum FundField
FundScreenerQuery type_alias#
pub type FundScreenerQuery = ScreenerQuery<FundField>
FuturesContract struct#
domain_handle!
FuturesQuote struct#
pub struct FuturesQuote
GradingAction struct#
pub struct GradingAction
IchimokuData struct#
pub struct IchimokuData
Index struct#
domain_handle!
IndexConstituent struct#
pub struct IndexConstituent
IndexConstituentChange struct#
pub struct IndexConstituentChange
IndexQuote struct#
pub struct IndexQuote
Indicator enum#
pub enum Indicator
IndicatorError enum#
pub enum IndicatorError
IndicatorResult enum#
pub enum IndicatorResult
IndicatorsSummary struct#
pub struct IndicatorsSummary
IndicesRegion enum#
pub enum Region
Industry enum#
pub enum Industry
IndustryData struct#
pub struct IndustryData
IndustryPe struct#
pub struct IndustryPe
InsiderTrade struct#
pub struct InsiderTrade
InsiderTransaction struct#
pub struct InsiderTransaction
InstitutionalHolding struct#
pub struct InstitutionalHolding
Interval enum#
pub enum Interval
IpoCalendarEntry struct#
pub struct IpoCalendarEntry
KeltnerChannelsData struct#
pub struct KeltnerChannelsData
KeyMetricsTtm struct#
pub struct KeyMetricsTtm
LogicalOperator enum#
pub enum LogicalOperator
LookupOptions struct#
pub struct LookupOptions
LookupQuote struct#
pub struct LookupQuote
LookupResults struct#
pub struct LookupResults
LookupType enum#
pub enum LookupType
MacdData struct#
pub struct MacdData
MacdResult struct#
pub struct MacdResult
MajorIndex enum#
pub enum MajorIndex
Market struct#
pub struct Market
MarketCalendar struct#
domain_handle!
MarketCalendarEntry struct#
pub struct MarketCalendarEntry
MarketHours struct#
pub struct MarketHours
MarketSnapshot struct#
pub struct MarketSnapshot
MarketSummaryQuote struct#
pub struct MarketSummaryQuote
MarketTime struct#
pub struct MarketTime
MoverDirection enum#
pub enum MoverDirection
MoverQuote struct#
pub struct MoverQuote
News struct#
pub struct News
Operation enum#
pub enum Operation
Operator enum#
pub enum Operator
OptionChain struct#
pub struct OptionChain
OptionContract struct#
pub struct OptionContract
Options struct#
pub struct Options
OptionsQuote struct#
pub struct OptionsQuote
PatternSentiment enum#
pub enum PatternSentiment
Period enum#
pub enum Period
PressRelease struct#
pub struct PressRelease
PriceTargetConsensus struct#
pub struct PriceTargetConsensus
PriceTargetSummary struct#
pub struct PriceTargetSummary
Provider enum#
pub enum Provider
ProviderFiling struct#
pub struct ProviderFiling
ProviderFilings struct#
pub struct ProviderFilings
ProviderHealth struct#
pub struct ProviderHealth
Providers struct#
pub struct Providers
ProvidersBuilder struct#
pub struct ProvidersBuilder
QueryCondition struct#
pub struct QueryCondition<F: ScreenerField>
QueryGroup struct#
pub struct QueryGroup<F: ScreenerField>
QueryOperand enum#
pub enum QueryOperand<F: ScreenerField>
Quote struct#
pub struct Quote<F: Format = Both>
QuoteSummaryResponse struct#
pub struct QuoteSummaryResponse
QuoteType enum#
pub enum QuoteType
RatingConsensus struct#
pub struct RatingConsensus
Recommendation struct#
pub struct Recommendation
Region enum#
pub enum Region
ResearchReport struct#
pub struct ResearchReport
ResearchReports struct#
pub struct ResearchReports(pub Vec<ResearchReport>)
Result type_alias#
pub type Result<T> = std::result::Result<T, FinanceError>
RetryPolicy struct#
pub struct RetryPolicy
RiskFactor struct#
pub struct RiskFactor
Routes struct#
pub struct Routes
Screener enum#
pub enum Screener
ScreenerField trait#
pub trait ScreenerField: Clone + Serialize + 'static
ScreenerFieldExt trait#
pub trait ScreenerFieldExt: ScreenerField + Sized
ScreenerFilters struct#
pub struct ScreenerFilters
ScreenerFundCategory enum#
pub enum ScreenerFundCategory
ScreenerMatch struct#
pub struct ScreenerMatch
ScreenerPeerGroup enum#
pub enum ScreenerPeerGroup
ScreenerQuery struct#
pub struct ScreenerQuery<F: ScreenerField = EquityField>
ScreenerQuote struct#
pub struct ScreenerQuote
ScreenerResults struct#
pub struct ScreenerResults
SearchNews struct#
pub struct SearchNews
SearchNewsList struct#
pub struct SearchNewsList(pub Vec<SearchNews>)
SearchOptions struct#
pub struct SearchOptions
SearchQuote struct#
pub struct SearchQuote
SearchQuotes struct#
pub struct SearchQuotes(pub Vec<SearchQuote>)
SearchResults struct#
pub struct SearchResults
Sector enum#
pub enum Sector
SectorData struct#
pub struct SectorData
SectorPe struct#
pub struct SectorPe
SectorPerformance struct#
pub struct SectorPerformance
SectorPerformanceHistory struct#
pub struct SectorPerformanceHistory
Sentiment struct#
pub struct Sentiment
SentimentLabel enum#
pub enum SentimentLabel
ShareFloat struct#
pub struct ShareFloat
ShortInterest struct#
pub struct ShortInterest
ShortVolume struct#
pub struct ShortVolume
SimilarSymbol struct#
pub struct SimilarSymbol
Snapshot struct#
domain_handle!
SortType enum#
pub enum SortType
Spark struct#
pub struct Spark
SparkData struct#
pub struct SparkData
Split struct#
pub struct Split
StatementType enum#
pub enum StatementType
StochasticData struct#
pub struct StochasticData
SuperTrendData struct#
pub struct SuperTrendData
SymbolDetails struct#
pub struct SymbolDetails
SymbolMatch struct#
pub struct SymbolMatch
SymbolSentiment struct#
pub struct SymbolSentiment
Ticker struct#
pub struct Ticker
TickerBuilder struct#
pub struct TickerBuilder
Tickers struct#
pub struct Tickers
TickersBuilder struct#
pub struct TickersBuilder
TimeRange enum#
pub enum TimeRange
Transcript struct#
pub struct Transcript
TranscriptWithMeta struct#
pub struct TranscriptWithMeta
TrendingQuote struct#
pub struct TrendingQuote
ValueFormat enum#
pub enum ValueFormat
analyst_estimates function#
pub async fn analyst_estimates(symbol: &str, period: Period) -> Result<Vec<AnalystEstimate>>
analyst_recommendations function#
pub async fn analyst_recommendations(symbol: &str) -> Result<Vec<AnalystRecommendation>>
analyze_sentiment function#
pub fn analyze(text: &str) -> Sentiment
atr function#
pub fn atr(highs: &[f64], lows: &[f64], closes: &[f64], period: usize) -> Result<Vec<Option<f64>>>
earnings_calendar function#
pub async fn earnings_calendar() -> Result<Vec<EarningsCalendarEntry>>
insider_trading function#
pub async fn insider_trading(symbol: &str, limit: u32) -> Result<Vec<InsiderTransaction>>
ipo_calendar function#
pub async fn ipo_calendar() -> Result<Vec<IpoCalendarEntry>>
patterns function#
pub fn patterns(candles: &[Candle]) -> Vec<Option<CandlePattern>>
symbol_sentiment function#
pub async fn symbol_sentiment(symbol: &str) -> Result<crate::models::sentiment::SymbolSentiment>
finance_query::adapters::alphavantage::models#
EarningsCalendarEntryDTO struct#
pub struct EarningsCalendarEntryDTO
A single earnings calendar entry.
IpoCalendarEntryDTO struct#
pub struct IpoCalendarEntryDTO
A single IPO calendar entry.
finance_query::adapters::fmp::corporate::insider_trading#
InsiderTradeDTO struct#
pub struct InsiderTradeDTO
Insider trading transaction record.
finance_query::adapters::fmp::fundamentals::estimates#
AnalystEstimateDTO struct#
pub struct AnalystEstimateDTO
Analyst estimate entry.
AnalystRecommendationDTO struct#
pub struct AnalystRecommendationDTO
Analyst recommendation entry.
finance_query::backtesting#
BacktestComparison struct#
pub struct BacktestComparison
BacktestConfig struct#
pub struct BacktestConfig
BacktestConfigBuilder struct#
pub struct BacktestConfigBuilder
BacktestEngine struct#
pub struct BacktestEngine
BacktestError enum#
pub enum BacktestError
BacktestResult struct#
pub struct BacktestResult
BayesianSearch struct#
pub struct BayesianSearch
BenchmarkMetrics struct#
pub struct BenchmarkMetrics
BollingerMeanReversion struct#
pub struct BollingerMeanReversion
ComparisonReport struct#
pub struct ComparisonReport
ComparisonRow struct#
pub struct ComparisonRow
DonchianBreakout struct#
pub struct DonchianBreakout
EnsembleMode enum#
pub enum EnsembleMode
EnsembleStrategy struct#
pub struct EnsembleStrategy
EquityPoint struct#
pub struct EquityPoint
GridSearch struct#
pub struct GridSearch
MacdSignal struct#
pub struct MacdSignal
MonteCarloConfig struct#
pub struct MonteCarloConfig
MonteCarloMethod enum#
pub enum MonteCarloMethod
MonteCarloResult struct#
pub struct MonteCarloResult
OptimizationReport struct#
pub struct OptimizationReport
OptimizationResult struct#
pub struct OptimizationResult
OptimizeMetric enum#
pub enum OptimizeMetric
OrderType enum#
pub enum OrderType
ParamRange enum#
pub enum ParamRange
ParamValue enum#
pub enum ParamValue
ParetoPoint struct#
pub struct ParetoPoint
ParetoReport struct#
pub struct ParetoReport
PendingOrder struct#
pub struct PendingOrder
PercentileStats struct#
pub struct PercentileStats
PerformanceMetrics struct#
pub struct PerformanceMetrics
Position struct#
pub struct Position
PositionExtremes struct#
pub struct PositionExtremes
PositionSide enum#
pub enum PositionSide
PositionSizing enum#
pub enum PositionSizing
Result type_alias#
pub type Result<T> = std::result::Result<T, BacktestError>
RsiReversal struct#
pub struct RsiReversal
Signal struct#
pub struct Signal
SignalDirection enum#
pub enum SignalDirection
SignalMetadata struct#
pub struct SignalMetadata
SignalRecord struct#
pub struct SignalRecord
SignalStrength struct#
pub struct SignalStrength(f64)
SizingContext struct#
pub struct SizingContext
SmaCrossover struct#
pub struct SmaCrossover
Strategy trait#
pub trait Strategy: Send + Sync
StrategyBuilder struct#
pub struct StrategyBuilder<E = (), X = ()>
StrategyContext struct#
pub struct StrategyContext<'a>
SuperTrendFollow struct#
pub struct SuperTrendFollow
Trade struct#
pub struct Trade
WalkForwardConfig struct#
pub struct WalkForwardConfig
WalkForwardReport struct#
pub struct WalkForwardReport
WindowResult struct#
pub struct WindowResult
finance_query::backtesting::comparison::BacktestComparison#
ranked_by function#
pub fn ranked_by(self, metric: OptimizeMetric) -> ComparisonReport
Rank all added results by metric and return a [ComparisonReport].
Results are sorted best-first (highest score wins for all metrics
except [OptimizeMetric::MinDrawdown], which is already negated
internally so that a lower drawdown yields a higher score).
finance_query::backtesting::condition#
Above struct#
pub struct Above<R: IndicatorRef>
AboveRef struct#
pub struct AboveRef<R1: IndicatorRef, R2: IndicatorRef>
All struct#
pub struct All<C: Condition>
And struct#
pub struct And<C1: Condition, C2: Condition>
Any struct#
pub struct Any<C: Condition>
Below struct#
pub struct Below<R: IndicatorRef>
BelowRef struct#
pub struct BelowRef<R1: IndicatorRef, R2: IndicatorRef>
Between struct#
pub struct Between<R: IndicatorRef>
Condition trait#
pub trait Condition: Clone + Send + Sync + 'static
A condition that can be evaluated on each candle.
Conditions are the building blocks of trading strategies.
They can be combined using and(), or(), and not() operations.
Example#
use finance_query::backtesting::condition::Condition;
fn my_custom_condition(ctx: &StrategyContext) -> bool {
// Custom logic here
true
}
ConditionBuilder struct#
pub struct ConditionBuilder<C: Condition>
ConstantCondition struct#
pub struct ConstantCondition(bool)
A condition that always returns the same value.
Useful for testing or as a placeholder.
CrossesAbove struct#
pub struct CrossesAbove<R: IndicatorRef>
CrossesAboveRef struct#
pub struct CrossesAboveRef<R1: IndicatorRef, R2: IndicatorRef>
CrossesBelow struct#
pub struct CrossesBelow<R: IndicatorRef>
CrossesBelowRef struct#
pub struct CrossesBelowRef<R1: IndicatorRef, R2: IndicatorRef>
Equals struct#
pub struct Equals<R: IndicatorRef>
HasPosition struct#
pub struct HasPosition
HeldForBars struct#
pub struct HeldForBars
HtfIndicatorSpec struct#
pub struct HtfIndicatorSpec
Describes an indicator that must be pre-computed on a resampled (HTF) candle series.
Returned by [Condition::htf_requirements] and processed by the engine to build
stretched arrays stored in StrategyContext::indicators under htf_key.
InLoss struct#
pub struct InLoss
InProfit struct#
pub struct InProfit
IsLong struct#
pub struct IsLong
IsShort struct#
pub struct IsShort
NoPosition struct#
pub struct NoPosition
Not struct#
pub struct Not<C: Condition>
Or struct#
pub struct Or<C1: Condition, C2: Condition>
StopLoss struct#
pub struct StopLoss
TakeProfit struct#
pub struct TakeProfit
TrailingStop struct#
pub struct TrailingStop
TrailingTakeProfit struct#
pub struct TrailingTakeProfit
always_false function#
pub fn always_false() -> ConstantCondition
Convenience function to create a condition that always returns false.
always_true function#
pub fn always_true() -> ConstantCondition
Convenience function to create a condition that always returns true.
has_position function#
pub fn has_position() -> HasPosition
held_for_bars function#
pub fn held_for_bars(min_bars: usize) -> HeldForBars
in_loss function#
pub fn in_loss() -> InLoss
in_profit function#
pub fn in_profit() -> InProfit
is_long function#
pub fn is_long() -> IsLong
is_short function#
pub fn is_short() -> IsShort
no_position function#
pub fn no_position() -> NoPosition
stop_loss function#
pub fn stop_loss(pct: f64) -> StopLoss
take_profit function#
pub fn take_profit(pct: f64) -> TakeProfit
trailing_stop function#
pub fn trailing_stop(trail_pct: f64) -> TrailingStop
trailing_take_profit function#
pub fn trailing_take_profit(trail_pct: f64) -> TrailingTakeProfit
finance_query::backtesting::config::BacktestConfig#
calculate_position_size function#
pub fn calculate_position_size(&self, available_capital: f64, price: f64) -> f64
Calculate position size based on available capital.
price must be the fully-adjusted entry price (after slippage and
spread) so that subsequent fill guards (entry_value + costs > cash)
do not over-allocate capital.
When commission_fn is set the commission component cannot be
analytically solved for, so only spread and transaction-tax fractions
are deducted from the denominator; the fill-rejection guard catches any
remaining over-allocation.
finance_query::backtesting::config::builder::BacktestConfigBuilder#
margin_interest_rate function#
pub fn margin_interest_rate(mut self, rate: f64) -> Self
Set the annual interest rate charged on a debit cash balance.
finance_query::backtesting::config::costs#
CommissionFn struct#
pub struct CommissionFn(Arc<dyn Fn(f64, f64) -> f64 + Send + Sync>)
A custom commission function: f(size, price) -> commission_amount.
When set on [BacktestConfig] via [BacktestConfigBuilder::commission_fn],
it replaces the flat commission + percentage commission_pct fields.
Use it to model broker-specific fee schedules such as per-share fees with
a minimum, tiered rates, or Robinhood-style zero-commission structures.
Example#
use finance_query::backtesting::BacktestConfig;
// IB-style: $0.005 per share, minimum $1.00 per order
let config = BacktestConfig::builder()
.commission_fn(|size, price| (size * 0.005_f64).max(1.00))
.build()
.unwrap();
finance_query::backtesting::engine::BacktestEngine#
run_with_dividends function#
pub fn run_with_dividends<S: Strategy>( &self, symbol: &str, candles: &[Candle], strategy: S, dividends: &[Dividend], ) -> Result<BacktestResult>
Run a backtest and credit dividend income for any dividends paid while a position is open.
dividends should be sorted by timestamp (ascending). The engine credits
each dividend whose ex-date falls on or before the current candle bar.
When [BacktestConfig::reinvest_dividends] is true, the income is also
used to notionally purchase additional shares at the ex-date close price.
finance_query::backtesting::optimizer::ParamRange#
float_bounds function#
pub fn float_bounds(start: f64, end: f64) -> Self
Continuous float bounds — [BayesianSearch] only.
A step of 0.0 intentionally makes [GridSearch] return an error, giving
a clear signal when the wrong optimiser is used with this range type.
float_range function#
pub fn float_range(start: f64, end: f64, step: f64) -> Self
Stepped float range — compatible with both [GridSearch] and [BayesianSearch].
int_bounds function#
pub fn int_bounds(start: i64, end: i64) -> Self
Continuous integer bounds for [BayesianSearch].
Equivalent to int_range(start, end, 1). Also usable with [GridSearch]
(enumerates every integer in [start, end]), but prefer int_range with a
wider step when the grid would be very large.
int_range function#
pub fn int_range(start: i64, end: i64, step: i64) -> Self
Stepped integer range — compatible with both [GridSearch] and [BayesianSearch].
finance_query::backtesting::optimizer::grid::GridSearch#
run function#
pub fn run<S, F>( &self, symbol: &str, candles: &[Candle], config: &BacktestConfig, factory: F, ) -> Result<OptimizationReport> where S: Strategy + Send, F: Fn(&HashMap<String, ParamValue>) -> S + Send + Sync,
Run the grid search.
symbol is used only for labelling in the returned results.
factory receives the current parameter map and returns a strategy
instance. Combinations that exceed the strategy's warmup period are
silently skipped.
Returns an error when the grid is empty or all combinations were skipped.
finance_query::backtesting::portfolio#
AllocationSnapshot struct#
pub struct AllocationSnapshot
PortfolioConfig struct#
pub struct PortfolioConfig
PortfolioEngine struct#
pub struct PortfolioEngine
PortfolioResult struct#
pub struct PortfolioResult
RebalanceMode enum#
pub enum RebalanceMode
SymbolData struct#
pub struct SymbolData
finance_query::backtesting::position::Position#
close function#
pub fn close( self, exit_timestamp: i64, exit_price: f64, exit_commission: f64, exit_signal: Signal, ) -> Trade
Close this position and create a Trade.
dividend_income accumulated during the hold is added to P&L and
preserved on the returned Trade for reporting purposes.
partial_close function#
pub fn partial_close( &mut self, fraction: f64, exit_ts: i64, exit_price: f64, commission: f64, exit_tax: f64, signal: Signal, ) -> Trade
Partially close this position and return a completed [Trade].
Closes fraction of the current position quantity, allocating a
proportional share of accumulated entry costs and dividend income to the
trade P&L. The remaining position stays open with reduced quantity,
dividend balances, and entry cost bases.
[Trade::is_partial] is true for all trades returned by this method.
For a full close prefer Position::close
(or the crate-internal close_with_tax for tax-aware exits), which sets
is_partial = false. The engine's scale_out_position delegates
fraction >= 1.0 to close_position for exactly this reason.
The caller is responsible for updating cash from the returned trade's exit proceeds.
Arguments#
fraction– Portion of current quantity to close (0.0..=1.0).exit_ts– Timestamp of the fill.exit_price– Adjusted exit price (after slippage/spread).commission– Exit-side commission for this close.exit_tax– Exit-side transaction tax for this close.signal– Signal that triggered the partial exit.
scale_in function#
pub fn scale_in( &mut self, fill_price: f64, additional_qty: f64, commission: f64, entry_tax: f64, )
Add shares to this position (pyramid / scale-in).
Updates the weighted-average entry_price and entry_quantity to reflect
the blended cost basis and increments scale_in_count. The caller is
responsible for debiting the entry cost from available cash and for applying
slippage/spread to fill_price before calling this method.
Arguments#
fill_price– Adjusted entry price for the new shares.additional_qty– Number of shares to add. No-op if<= 0.0.commission– Commission paid for this add (already applied to cash).entry_tax– Transaction tax for this add (already applied to cash).
finance_query::backtesting::refs#
AccumulationDistributionRef struct#
pub struct AccumulationDistributionRef
AdxRef struct#
pub struct AdxRef
AlmaConfig struct#
pub struct AlmaConfig
AlmaRef struct#
pub struct AlmaRef
AroonConfig struct#
pub struct AroonConfig
AroonDownRef struct#
pub struct AroonDownRef
AroonUpRef struct#
pub struct AroonUpRef
AtrRef struct#
pub struct AtrRef
AwesomeOscillatorRef struct#
pub struct AwesomeOscillatorRef
BalanceOfPowerRef struct#
pub struct BalanceOfPowerRef
BearPowerRef struct#
pub struct BearPowerRef
BollingerConfig struct#
pub struct BollingerConfig
BollingerLowerRef struct#
pub struct BollingerLowerRef
BollingerMiddleRef struct#
pub struct BollingerMiddleRef
BollingerUpperRef struct#
pub struct BollingerUpperRef
BullPowerRef struct#
pub struct BullPowerRef
CandleBody struct#
pub struct CandleBody
CandleRange struct#
pub struct CandleRange
CciRef struct#
pub struct CciRef
ChaikinOscillatorRef struct#
pub struct ChaikinOscillatorRef
ChoppinessIndexRef struct#
pub struct ChoppinessIndexRef
ClosePrice struct#
pub struct ClosePrice
CmfRef struct#
pub struct CmfRef
CmoRef struct#
pub struct CmoRef
CoppockCurveRef struct#
pub struct CoppockCurveRef
DemaRef struct#
pub struct DemaRef
DonchianConfig struct#
pub struct DonchianConfig
DonchianLowerRef struct#
pub struct DonchianLowerRef
DonchianMiddleRef struct#
pub struct DonchianMiddleRef
DonchianUpperRef struct#
pub struct DonchianUpperRef
ElderBearPowerRef struct#
pub struct ElderBearPowerRef
ElderBullPowerRef struct#
pub struct ElderBullPowerRef
EmaRef struct#
pub struct EmaRef
GapPct struct#
pub struct GapPct
HighPrice struct#
pub struct HighPrice
HmaRef struct#
pub struct HmaRef
HtfCondition struct#
pub struct HtfCondition<C: Condition>
IchimokuBaseRef struct#
pub struct IchimokuBaseRef
IchimokuConfig struct#
pub struct IchimokuConfig
IchimokuConversionRef struct#
pub struct IchimokuConversionRef
IchimokuLaggingRef struct#
pub struct IchimokuLaggingRef
IchimokuLeadingARef struct#
pub struct IchimokuLeadingARef
IchimokuLeadingBRef struct#
pub struct IchimokuLeadingBRef
IndicatorRef trait#
pub trait IndicatorRef: Clone + Send + Sync + 'static
A reference to a value that can be compared in conditions.
This is the building block for creating conditions. Each indicator reference knows:
- Its unique key for storing computed values
- What indicators it requires
- How to retrieve its value from the strategy context
Implementing Custom References#
use finance_query::backtesting::refs::IndicatorRef;
#[derive(Clone)]
struct MyCustomRef {
period: usize,
}
impl IndicatorRef for MyCustomRef {
fn key(&self) -> &str {
"my_custom_14" // pre-computed at construction time
}
fn required_indicators(&self) -> Vec<(String, Indicator)> {
vec![(self.key().to_string(), Indicator::Sma(self.period))]
}
fn value(&self, ctx: &StrategyContext) -> Option<f64> {
ctx.indicator(self.key())
}
fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
ctx.indicator_prev(self.key())
}
}
IndicatorRefExt trait#
pub trait IndicatorRefExt: IndicatorRef + Sized
Extension trait that adds condition-building methods to all indicator references.
This trait provides a fluent API for building conditions from indicator values.
It is automatically implemented for all types that implement IndicatorRef.
Example#
use finance_query::backtesting::refs::*;
// All these methods are available on any IndicatorRef
let cond1 = rsi(14).above(70.0);
let cond2 = rsi(14).below(30.0);
let cond3 = rsi(14).crosses_above(30.0);
let cond4 = rsi(14).crosses_below(70.0);
let cond5 = rsi(14).between(30.0, 70.0);
let cond6 = sma(10).above_ref(sma(20));
let cond7 = sma(10).crosses_above_ref(sma(20));
IsBearish struct#
pub struct IsBearish
IsBullish struct#
pub struct IsBullish
KeltnerConfig struct#
pub struct KeltnerConfig
KeltnerLowerRef struct#
pub struct KeltnerLowerRef
KeltnerMiddleRef struct#
pub struct KeltnerMiddleRef
KeltnerUpperRef struct#
pub struct KeltnerUpperRef
LowPrice struct#
pub struct LowPrice
MacdConfig struct#
pub struct MacdConfig
MacdHistogramRef struct#
pub struct MacdHistogramRef
MacdLineRef struct#
pub struct MacdLineRef
MacdSignalRef struct#
pub struct MacdSignalRef
McginleyDynamicRef struct#
pub struct McginleyDynamicRef
MedianPrice struct#
pub struct MedianPrice
MfiRef struct#
pub struct MfiRef
MomentumRef struct#
pub struct MomentumRef
ObvRef struct#
pub struct ObvRef
OpenPrice struct#
pub struct OpenPrice
ParabolicSarConfig struct#
pub struct ParabolicSarConfig
ParabolicSarRef struct#
pub struct ParabolicSarRef
PriceChangePct struct#
pub struct PriceChangePct
RelativeVolume struct#
pub struct RelativeVolume
RocRef struct#
pub struct RocRef
RsiRef struct#
pub struct RsiRef
SmaRef struct#
pub struct SmaRef
StochasticConfig struct#
pub struct StochasticConfig
StochasticDRef struct#
pub struct StochasticDRef
StochasticKRef struct#
pub struct StochasticKRef
StochasticRsiConfig struct#
pub struct StochasticRsiConfig
StochasticRsiDRef struct#
pub struct StochasticRsiDRef
StochasticRsiRef struct#
pub struct StochasticRsiRef
SupertrendConfig struct#
pub struct SupertrendConfig
SupertrendUptrendRef struct#
pub struct SupertrendUptrendRef
SupertrendValueRef struct#
pub struct SupertrendValueRef
TemaRef struct#
pub struct TemaRef
TrueRangeRef struct#
pub struct TrueRangeRef
TypicalPrice struct#
pub struct TypicalPrice
VolumeRef struct#
pub struct VolumeRef
VwapRef struct#
pub struct VwapRef
VwmaRef struct#
pub struct VwmaRef
WilliamsRRef struct#
pub struct WilliamsRRef
WmaRef struct#
pub struct WmaRef
accumulation_distribution function#
pub fn accumulation_distribution() -> AccumulationDistributionRef
adx function#
pub fn adx(period: usize) -> AdxRef
alma function#
pub fn alma(period: usize, offset: f64, sigma: f64) -> AlmaRef
aroon function#
pub fn aroon(period: usize) -> AroonConfig
atr function#
pub fn atr(period: usize) -> AtrRef
awesome_oscillator function#
pub fn awesome_oscillator(fast: usize, slow: usize) -> AwesomeOscillatorRef
balance_of_power function#
pub fn balance_of_power(period: Option<usize>) -> BalanceOfPowerRef
bear_power function#
pub fn bear_power(period: usize) -> BearPowerRef
bollinger function#
pub fn bollinger(period: usize, std_dev: f64) -> BollingerConfig
bull_power function#
pub fn bull_power(period: usize) -> BullPowerRef
candle_body function#
pub fn candle_body() -> CandleBody
candle_range function#
pub fn candle_range() -> CandleRange
cci function#
pub fn cci(period: usize) -> CciRef
chaikin_oscillator function#
pub fn chaikin_oscillator() -> ChaikinOscillatorRef
choppiness_index function#
pub fn choppiness_index(period: usize) -> ChoppinessIndexRef
close function#
pub fn close() -> ClosePrice
cmf function#
pub fn cmf(period: usize) -> CmfRef
cmo function#
pub fn cmo(period: usize) -> CmoRef
coppock_curve function#
pub fn coppock_curve(wma_period: usize, long_roc: usize, short_roc: usize) -> CoppockCurveRef
dema function#
pub fn dema(period: usize) -> DemaRef
donchian function#
pub fn donchian(period: usize) -> DonchianConfig
elder_bear_power function#
pub fn elder_bear_power(period: usize) -> ElderBearPowerRef
elder_bull_power function#
pub fn elder_bull_power(period: usize) -> ElderBullPowerRef
ema function#
pub fn ema(period: usize) -> EmaRef
gap_pct function#
pub fn gap_pct() -> GapPct
high function#
pub fn high() -> HighPrice
hma function#
pub fn hma(period: usize) -> HmaRef
htf function#
pub fn htf<C: Condition>(interval: Interval, cond: C) -> HtfCondition<C>
htf_region function#
pub fn htf_region<C: Condition>(interval: Interval, region: Region, cond: C) -> HtfCondition<C>
ichimoku function#
pub fn ichimoku() -> IchimokuConfig
ichimoku_custom function#
pub fn ichimoku_custom( conversion: usize, base: usize, lagging: usize, displacement: usize, ) -> IchimokuConfig
is_bearish function#
pub fn is_bearish() -> IsBearish
is_bullish function#
pub fn is_bullish() -> IsBullish
keltner function#
pub fn keltner(period: usize, multiplier: f64, atr_period: usize) -> KeltnerConfig
low function#
pub fn low() -> LowPrice
macd function#
pub fn macd(fast: usize, slow: usize, signal: usize) -> MacdConfig
mcginley function#
pub fn mcginley(period: usize) -> McginleyDynamicRef
median_price function#
pub fn median_price() -> MedianPrice
mfi function#
pub fn mfi(period: usize) -> MfiRef
momentum function#
pub fn momentum(period: usize) -> MomentumRef
obv function#
pub fn obv() -> ObvRef
open function#
pub fn open() -> OpenPrice
parabolic_sar function#
pub fn parabolic_sar(step: f64, max: f64) -> ParabolicSarRef
price function#
pub fn price() -> ClosePrice
price_change_pct function#
pub fn price_change_pct() -> PriceChangePct
relative_volume function#
pub fn relative_volume(period: usize) -> RelativeVolume
roc function#
pub fn roc(period: usize) -> RocRef
rsi function#
pub fn rsi(period: usize) -> RsiRef
sma function#
pub fn sma(period: usize) -> SmaRef
stochastic function#
pub fn stochastic(k_period: usize, k_slow: usize, d_period: usize) -> StochasticConfig
stochastic_rsi function#
pub fn stochastic_rsi( rsi_period: usize, stoch_period: usize, k_period: usize, d_period: usize, ) -> StochasticRsiConfig
supertrend function#
pub fn supertrend(period: usize, multiplier: f64) -> SupertrendConfig
tema function#
pub fn tema(period: usize) -> TemaRef
true_range function#
pub fn true_range() -> TrueRangeRef
typical_price function#
pub fn typical_price() -> TypicalPrice
volume function#
pub fn volume() -> VolumeRef
vwap function#
pub fn vwap() -> VwapRef
vwma function#
pub fn vwma(period: usize) -> VwmaRef
williams_r function#
pub fn williams_r(period: usize) -> WilliamsRRef
wma function#
pub fn wma(period: usize) -> WmaRef
finance_query::backtesting::refs::oscillators::StochasticRsiConfig#
d function#
pub fn d(&self) -> StochasticRsiDRef
Reference to the %D signal line (SMA of %K).
k function#
pub fn k(&self) -> StochasticRsiRef
Reference to the smoothed %K line.
finance_query::backtesting::resample#
base_to_htf_index function#
pub fn base_to_htf_index(base_candles: &[Candle], htf_candles: &[Candle]) -> Vec<Option<usize>>
Map each base-timeframe index to the most recently completed HTF bar index.
A "completed" HTF bar is one whose timestamp (the last constituent bar's
timestamp) is less than or equal to the current base bar's timestamp.
Using <= rather than < ensures that on the final bar of an HTF period
(e.g. a Friday close for a weekly bar), the engine can immediately see the
now-finalized HTF candle. Using < would introduce an artificial one-bar
delay: on Friday, htf.timestamp == base.timestamp, so < fails and the
engine falls back to the prior week's data even though the weekly bar is
already complete.
htf_candles must have been produced by [resample] with the same
utc_offset_secs used for the base series so that bucket boundaries are
consistent.
Returns None for bars where no HTF bar has completed yet (e.g. during
the first HTF period).
resample function#
pub fn resample(candles: &[Candle], interval: Interval, utc_offset_secs: i64) -> Vec<Candle>
Resample candles from their base timeframe to interval.
utc_offset_secs shifts each candle's timestamp into the exchange's local
time before computing calendar bucket boundaries (weekly Monday start,
month boundary, etc.). Pass 0 for UTC-aligned bucketing (default for US
markets). Use Region::utc_offset_secs to obtain the correct value for
non-US exchanges.
Notes#
- Calendar-aligned intervals (
OneWeek,OneMonth,ThreeMonths) respectutc_offset_secs. Weekly bars start on the local Monday. - Sub-daily intervals use fixed-second buckets relative to local midnight.
finance_query::backtesting::result::BacktestResult#
by_day_of_week function#
pub fn by_day_of_week(&self) -> HashMap<Weekday, PerformanceMetrics>
Performance metrics broken down by day of week.
Each trade is attributed to the weekday on which it closed
(exit_timestamp). Only weekdays present in the trade log appear in
the result. Trades and equity-curve points with timestamps that cannot
be converted to a valid date are silently skipped.
Sharpe / Sortino annualisation#
The equity curve is filtered to bars that fall on each specific
weekday, so consecutive equity points in each slice are roughly one
week apart (for a daily-bar backtest). bars_per_year is inferred
from the calendar span of each slice so that annualisation matches the
actual sampling frequency — you do not need to adjust the config.
The inferred value is approximately 52 for daily bars, 12 for
weekly bars, and so on.
Other caveats#
The same open-position and signal-count caveats from
by_year apply here.
by_month function#
pub fn by_month(&self) -> HashMap<(i32, u32), PerformanceMetrics>
Performance metrics broken down by calendar month.
Each trade is attributed to the (year, month) in which it closed.
Uses the same equity-slicing approach as by_year;
the same caveats about open positions, partial periods, and signal
counts apply here as well.
by_year function#
pub fn by_year(&self) -> HashMap<i32, PerformanceMetrics>
Performance metrics broken down by calendar year.
Each trade is attributed to the year in which it closed
(exit_timestamp). The equity curve is sliced to the bars that fall
within that calendar year, and the equity at the first bar of the year
serves as initial_capital for the period metrics.
Years with no closed trades are omitted from the result.
Caveats#
- Open positions: a position that is open throughout the year contributes to the equity-curve drawdown and Sharpe of that year but does not appear in
total_tradesorwin_rate, because those are derived from closed trades only. Strategies with long holding periods will show systematically low trade counts per year. - Partial years: the first and last year of a backtest typically cover fewer than 12 months.
annualized_return_pct,calmar_ratio, andserenity_ratioare set to0.0for slices shorter than half a year (< bars_per_year / 2bars) to prevent geometric-compounding distortion. total_signals/executed_signals: these fields are0in period breakdowns because signal records are not partitioned per period. Use [BacktestResult::signals] directly if needed.
finance_query::backtesting::result::metrics::PerformanceMetrics#
max_drawdown_percentage function#
pub fn max_drawdown_percentage(&self) -> f64
Maximum drawdown as a conventional percentage (0–100).
Equivalent to self.max_drawdown_pct * 100.0. Provided because
max_drawdown_pct is stored as a fraction (0.0–1.0) while most other
return fields use true percentages.
finance_query::backtesting::signal::Signal#
exit function#
pub fn exit(timestamp: i64, price: f64) -> Self
Create an exit signal
scale_in function#
pub fn scale_in(fraction: f64, timestamp: i64, price: f64) -> Self
Create a scale-in signal — add to an existing position.
fraction is the portion of current portfolio equity to allocate to
the additional shares. Must be in 0.0..=1.0; values outside this range
are clamped by the engine. Has no effect if no position is currently open.
Example#
use finance_query::backtesting::Signal;
// In a custom Strategy::on_candle implementation:
# let (ctx_timestamp, ctx_price) = (0i64, 0.0f64);
// Add 10% of current equity to the existing long position.
let signal = Signal::scale_in(0.10, ctx_timestamp, ctx_price);
scale_out function#
pub fn scale_out(fraction: f64, timestamp: i64, price: f64) -> Self
Create a scale-out signal — partially exit an existing position.
fraction is the portion of the current position quantity to close.
Must be in 0.0..=1.0; values outside this range are clamped. A fraction
of 1.0 closes the entire position (equivalent to [Signal::exit]). Has
no effect if no position is currently open.
Example#
use finance_query::backtesting::Signal;
// In a custom Strategy::on_candle implementation:
# let (ctx_timestamp, ctx_price) = (0i64, 0.0f64);
// Close half the current position to lock in partial profits.
let signal = Signal::scale_out(0.50, ctx_timestamp, ctx_price);
finance_query::backtesting::strategy#
CustomStrategy struct#
pub struct CustomStrategy<E: Condition, X: Condition>
finance_query::backtesting::strategy::StrategyContext#
crossed_above function#
pub fn crossed_above(&self, fast_name: &str, slow_name: &str) -> bool
Check if crossover occurred (fast crosses above slow)
indicator function#
pub fn indicator(&self, name: &str) -> Option<f64>
Get indicator value at current index
indicator_crossed_above function#
pub fn indicator_crossed_above(&self, name: &str, threshold: f64) -> bool
Check if indicator crossed above a threshold.
Returns true when prev <= threshold and current > threshold.
The inclusive lower bound (<=) means a signal fires even when the
previous bar sat exactly on the threshold, the same inclusive-previous
convention crossed_above uses for
indicator-vs-indicator crossings.
indicator_prev function#
pub fn indicator_prev(&self, name: &str) -> Option<f64>
Get indicator value at previous index
finance_query::backtesting::strategy::builder::StrategyBuilder#
regime_filter function#
pub fn regime_filter<C: Condition>(mut self, condition: C) -> Self
Set a market regime filter.
When set, entry signals (long and short) are suppressed on any bar
where the filter evaluates to false. Exit signals are never
blocked by the regime filter, ensuring open positions can always be
closed regardless of market conditions.
The regime filter's indicators are included in required_indicators()
and therefore pre-computed by the engine like any other indicator.
Example#
use finance_query::backtesting::strategy::StrategyBuilder;
use finance_query::backtesting::refs::*;
// Only trade when price is above the 200-period SMA
let strategy = StrategyBuilder::new("Trend Following")
.regime_filter(sma(200).above_ref(sma(400)))
.entry(ema(10).crosses_above_ref(ema(30)))
.exit(ema(10).crosses_below_ref(ema(30)))
.build();
finance_query::backtesting::strategy::ensemble::EnsembleStrategy#
add function#
pub fn add<S: Strategy + 'static>(mut self, strategy: S, weight: f64) -> Self
Add a sub-strategy with the given weight.
Weight is only meaningful for [EnsembleMode::WeightedMajority]; other
modes ignore it. Negative weights are treated as zero.
build function#
pub fn build(self) -> Self
Finalise the ensemble. Returns self (all configuration happens in the
builder methods).
mode function#
pub fn mode(mut self, mode: EnsembleMode) -> Self
Set the voting mode.
finance_query::backtesting::walk_forward::WalkForwardConfig#
new function#
pub fn new(grid: GridSearch, config: BacktestConfig) -> Self
Create a new walk-forward config.
Defaults: in_sample_bars = 252, out_of_sample_bars = 63, step_bars = None.
run function#
pub fn run<S, F>( &self, symbol: &str, candles: &[Candle], factory: F, ) -> Result<WalkForwardReport> where S: Strategy + Clone + Send, F: Fn(&HashMap<String, ParamValue>) -> S, F: Send + Sync,
Run the walk-forward test.
symbol is used only for labelling. factory receives the parameter
map selected by each in-sample optimisation and must return a fresh
strategy instance.
Returns an error if there is not enough data for at least one complete window pair, or if the grid search or the out-of-sample simulation fails on any window (fail-fast — a partial result is never returned).
finance_query::cftc#
commitments_of_traders function#
pub async fn fetch_commitments_of_traders_response(symbol: &str) -> Result<CommitmentsOfTraders>
finance_query::constants::enums::interval::Interval#
as_str function#
pub fn as_str(&self) -> &'static str
Convert interval to Yahoo Finance API format
finance_query::constants::enums::region::Region#
utc_offset_secs function#
pub const fn utc_offset_secs(&self) -> i64
UTC offset in seconds for the region's primary exchange.
Returns the standard-time (non-DST) UTC offset of each country's main exchange. This is used by the backtesting engine to align higher-timeframe resampling bucket boundaries to local calendar weeks and months, preventing APAC and other non-UTC exchanges from having bars mis-bucketed into the prior week due to UTC midnight falling inside their local trading day.
Note#
DST transitions are not modelled. For exchanges in regions with DST (e.g. NYSE, LSE) the boundary shift is at most ±1 hour and affects only the transition candles. This is a deliberate simplification — exact DST handling would require a timezone database dependency.
finance_query::constants::enums::time_range::TimeRange#
as_str function#
pub fn as_str(&self) -> &'static str
Convert time range to Yahoo Finance API format
default_interval function#
pub fn default_interval(&self) -> Interval
A sensible default candle interval for this range, used by the
history(range) convenience on domain handles: finer granularity for
short ranges, coarser for long ones.
finance_query::constants::industries::Industry#
as_slug function#
pub fn as_slug(self) -> &'static str
Returns the lowercase hyphenated slug used by finance::industry().
Example#
use finance_query::Industry;
assert_eq!(Industry::Semiconductors.as_slug(), "semiconductors");
assert_eq!(Industry::SoftwareApplication.as_slug(), "software-application");
finance_query::crypto#
CoinQuote struct#
pub struct CoinQuote
GlobalCryptoStats struct#
pub struct GlobalCryptoStats
TrendingCoin struct#
pub struct TrendingCoin
coin function#
pub async fn coin(id: &str, vs_currency: &str) -> Result<CoinQuote>
coins function#
pub async fn coins(vs_currency: &str, count: usize) -> Result<Vec<CoinQuote>>
global function#
pub async fn fetch_crypto_global_response() -> Result<crate::models::crypto::GlobalCryptoStats>
search function#
pub async fn fetch_symbol_search_response(query: &str, limit: u32) -> Result<Vec<SymbolMatch>>
trending function#
pub async fn fetch_crypto_trending_response() -> Result<Vec<crate::models::crypto::TrendingCoin>>
finance_query::defi#
ChainAllocation struct#
pub struct ChainAllocation
ChainTvl struct#
pub struct ChainTvl
ProtocolTvl struct#
pub struct ProtocolTvl
StablecoinSupply struct#
pub struct StablecoinSupply
TvlPoint struct#
pub struct TvlPoint
chains function#
pub async fn chains() -> Result<Vec<ChainTvl>>
Fetch aggregate total value locked for every chain, largest first.
stablecoins function#
pub async fn stablecoins() -> Result<Vec<StablecoinSupply>>
Fetch circulating supply for every tracked stablecoin, largest first.
Supplies are denominated in the coin's pegged asset — read peg_type
before summing across coins pegged to different currencies.
finance_query::domains::commodities::Commodity#
quote function#
pub async fn quote(&self) -> Result<crate::models::commodities::CommodityQuote>
Fetch the current quote for this commodity.
finance_query::domains::crypto::CryptoCoin#
quote function#
pub async fn quote(&self, vs_currency: &str) -> Result<crate::models::crypto::CryptoQuote>
Fetch the current quote for this coin priced in vs_currency (e.g., "usd").
tvl function#
pub async fn tvl(&self) -> Result<crate::models::crypto::defi::ProtocolTvl>
Fetch total value locked for this handle read as a DeFi protocol
slug (e.g. providers.crypto("aave")).
Routed through Capability::CRYPTO; only DefiLlama serves it, so route
CRYPTO to include Provider::DefiLlama.
The id is a protocol slug here, not a coin id — most DefiLlama slugs
happen to match their CoinGecko id, but not all do. The response is
cached on the handle, so a repeat call costs nothing.
tvl_history function#
pub async fn tvl_history(&self) -> Result<Vec<crate::models::crypto::defi::TvlPoint>>
Fetch this protocol's full TVL history, oldest first.
Same routing and slug semantics as tvl.
finance_query::domains::discovery::Discovery#
search function#
pub async fn search(&self, query: &str, limit: u32) -> Result<Vec<SymbolMatch>>
Search the configured providers' symbol universe.
Results are cached per (query, limit) pair.
finance_query::domains::economic::EconomicIndicator#
series function#
pub async fn series(&self) -> Result<crate::models::economic::EconomicSeries>
Fetch the full data series for this economic indicator.
finance_query::domains::filings::Filings#
get function#
pub async fn get(&self) -> Result<crate::models::filings::ProviderFilings>
Fetch SEC filings for this symbol.
search_all function#
pub async fn search_all( &self, query: &str, filters: crate::models::filings::FilingSearchFilters, ) -> Result<Vec<crate::models::filings::FilingSearchHit>>
Full-text search across every filer via the FILINGS route (currently EDGAR only). Not cached.
Searches filing text, so it answers "which filings mention this"
rather than "what has this company filed" — the query shape
get cannot express.
finance_query::domains::forex::ForexPair#
quote function#
pub async fn quote(&self) -> Result<crate::models::forex::ForexQuote>
Fetch the current exchange rate for this currency pair.
finance_query::domains::futures::FuturesContract#
commitments_of_traders function#
pub async fn commitments_of_traders( &self, ) -> Result<crate::models::futures::cot::CommitmentsOfTraders>
Fetch weekly CFTC Commitments of Traders positioning for this futures contract — long/short/spread broken down by trader category (commercial hedgers, swap dealers, managed money, other reportables, small traders).
Routed through Capability::FUTURES; only Provider::Cftc
serves it, so route FUTURES to include it. CFTC covers physical
commodities only (agriculture, energy, metals) via the disaggregated
futures-only report — the symbol is either a recognised Yahoo-style
continuous futures root ("GC=F", "CL=F", …) or a raw CFTC
cftc_contract_market_code passed straight through.
finance_query::domains::indices::Index#
constituents function#
pub async fn constituents(&self) -> Result<Vec<crate::models::indices::IndexConstituent>>
Fetch the index's current constituents (major indices only). Not cached — constituent lists change rarely but the call is uncommon.
finance_query::domains::market::Market#
crypto_global function#
pub async fn crypto_global(&self) -> Result<crate::models::crypto::GlobalCryptoStats>
Fetch aggregate global cryptocurrency market statistics.
Routes through Capability::CRYPTO.
Currently CoinGecko only.
crypto_trending function#
pub async fn crypto_trending(&self) -> Result<Vec<crate::models::crypto::TrendingCoin>>
Fetch coins/nfts/categories trending in the last 24h.
Routes through Capability::CRYPTO.
Currently CoinGecko only.
grouped_daily function#
pub async fn grouped_daily(&self, date: &str) -> Result<Vec<(String, Candle)>>
Fetch grouped daily OHLCV bars for every stock ticker on date
(YYYY-MM-DD) in one call — "give me every ticker's OHLC for this
date" rather than one symbol at a time.
Routes through Capability::CHART
(the same capability backing per-symbol chart methods) rather than
MARKET, since it's OHLCV data rather than a performance statistic.
Currently Polygon only. Not cached — one date is one request either way.
finance_query::edgar#
company_facts function#
pub async fn company_facts(cik: u64) -> Result<CompanyFacts>
filing_index function#
pub async fn filing_index(accession_number: &str) -> Result<EdgarFilingIndex>
init function#
pub fn init(email: impl Into<String>) -> Result<()>
init_with_config function#
pub fn init_with_config( email: impl Into<String>, app_name: impl Into<String>, timeout: Duration, ) -> Result<()>
resolve_cik function#
pub async fn resolve_cik(symbol: &str) -> Result<u64>
search function#
pub async fn search( query: &str, forms: Option<&[&str]>, start_date: Option<&str>, end_date: Option<&str>, from: Option<usize>, size: Option<usize>, ) -> Result<EdgarSearchResults>
submissions function#
pub async fn submissions(cik: u64) -> Result<EdgarSubmissions>
finance_query::feeds#
FeedEntry struct#
pub struct FeedEntry
A single entry from an RSS/Atom feed.
FeedSource enum#
pub enum FeedSource
A named or custom RSS/Atom feed source.
fetch function#
pub async fn fetch(source: FeedSource) -> Result<Vec<FeedEntry>>
Fetch and parse a single feed source.
Returns an empty Vec (not an error) when the feed is reachable but empty.
fetch_all function#
pub async fn fetch_all(sources: impl IntoIterator<Item = FeedSource>) -> Result<Vec<FeedEntry>>
Fetch multiple feed sources concurrently and merge the results.
Results are deduplicated by URL and sorted newest-first when dates are available. Feeds that fail individually are skipped (not propagated as errors).
A single reqwest::Client is shared across all concurrent fetches within
this call, reusing connection pools and TLS state.
parse_bytes function#
pub fn parse_bytes(bytes: &[u8], source_name: &str) -> Result<Vec<FeedEntry>>
Parse already-fetched RSS/Atom bytes into entries, without a network round-trip.
Used internally by [fetch]/[fetch_all]; also useful for callers that
fetch feed bytes through their own HTTP client/cache/proxy, and for
offline parsing benchmarks/tests.
finance_query::feeds::FeedSource#
url function#
pub fn url(&self) -> String
Return the URL for this feed source.
finance_query::finance#
currencies function#
pub async fn currencies() -> Result<Vec<crate::models::market::currencies::Currency>>
Get list of available currencies
Returns currency information from Yahoo Finance.
Examples#
use finance_query::finance;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
let currencies = finance::currencies().await?;
# Ok(())
# }
custom_screener function#
pub async fn custom_screener<F: crate::models::discovery::screeners::ScreenerField>( query: crate::models::discovery::screeners::ScreenerQuery<F>, ) -> Result<ScreenerResults>
Execute a custom screener query
Allows flexible filtering of stocks/funds/ETFs based on various criteria.
Use [EquityScreenerQuery][crate::EquityScreenerQuery] for stock screeners
or [FundScreenerQuery][crate::FundScreenerQuery] for mutual fund screeners.
Arguments#
query- The custom screener query to execute
Examples#
use finance_query::{finance, EquityField, EquityScreenerQuery, ScreenerFieldExt};
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
// Find US large-cap stocks with high volume
let query = EquityScreenerQuery::new()
.size(25)
.sort_by(EquityField::IntradayMarketCap, false)
.add_condition(EquityField::Region.eq_str("us"))
.add_condition(EquityField::AvgDailyVol3M.gt(200_000.0))
.add_condition(EquityField::IntradayMarketCap.gt(10_000_000_000.0));
let result = finance::custom_screener(query).await?;
println!("Found {} stocks", result.quotes.len());
# Ok(())
# }
earnings_transcript function#
pub async fn earnings_transcript( symbol: &str, quarter: Option<&str>, year: Option<i32>, ) -> Result<Transcript>
Get earnings transcript for a symbol
Fetches the earnings call transcript, handling all the complexity internally:
- Gets the company ID (quartrId) from the quote_type endpoint
- Scrapes available earnings calls
- Fetches the requested transcript
Arguments#
symbol- Stock symbol (e.g., "AAPL", "MSFT")quarter- Optional fiscal quarter (Q1, Q2, Q3, Q4). If None, gets latest.year- Optional fiscal year. If None, gets latest.
Examples#
use finance_query::finance;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
// Get the latest transcript
let latest = finance::earnings_transcript("AAPL", None, None).await?;
println!("Quarter: {} {}", latest.quarter(), latest.year());
// Get a specific quarter
let q4_2024 = finance::earnings_transcript("AAPL", Some("Q4"), Some(2024)).await?;
# Ok(())
# }
earnings_transcripts function#
pub async fn earnings_transcripts( symbol: &str, limit: Option<usize>, ) -> Result<Vec<TranscriptWithMeta>>
Get all earnings transcripts for a symbol
Fetches transcripts for all available earnings calls.
Arguments#
symbol- Stock symbol (e.g., "AAPL", "MSFT")limit- Optional maximum number of transcripts. If None, fetches all.
Examples#
use finance_query::finance;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
// Get all transcripts
let all = finance::earnings_transcripts("AAPL", None).await?;
// Get only the 5 most recent
let recent = finance::earnings_transcripts("AAPL", Some(5)).await?;
for t in &recent {
println!("{}: {} {}", t.title, t.transcript.quarter(), t.transcript.year());
}
# Ok(())
# }
exchanges function#
pub async fn exchanges() -> Result<Vec<crate::models::market::exchanges::Exchange>>
Get list of supported exchanges
Scrapes the Yahoo Finance help page for a list of supported exchanges with their symbol suffixes and data delay information.
Examples#
use finance_query::finance;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
let exchanges = finance::exchanges().await?;
for exchange in &exchanges {
println!("{} - {} ({})", exchange.country, exchange.market, exchange.suffix);
}
# Ok(())
# }
fear_and_greed function#
pub async fn fear_and_greed() -> Result<crate::models::sentiment::FearAndGreed>
Fetch the current CNN Fear & Greed Index from Alternative.me.
Returns a 0–100 sentiment score and its classification. No API key required.
Examples#
use finance_query::finance;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
let fg = finance::fear_and_greed().await?;
println!("Fear & Greed: {} ({})", fg.value, fg.classification.as_str());
# Ok(())
# }
fear_and_greed_crypto function#
pub async fn fear_and_greed_crypto( limit: u32, ) -> Result<Vec<crate::models::sentiment::FearAndGreed>>
Fetch the crypto Fear & Greed Index from Alternative.me — current value
plus up to limit - 1 historical readings (newest first).
Alternative.me's index specifically tracks crypto (Bitcoin) market sentiment from volatility, momentum, social media, dominance, and Google Trends signals. No API key required.
Arguments#
limit- Number of readings to return, newest first (1for just the current value; e.g.30for the trailing month).
Examples#
use finance_query::finance;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
let history = finance::fear_and_greed_crypto(7).await?;
let latest = &history[0];
println!("Crypto Fear & Greed: {} ({})", latest.value, latest.classification.as_str());
# Ok(())
# }
hours function#
pub async fn hours(region: Option<Region>) -> Result<crate::models::market::hours::MarketHours>
Get market hours/status
Returns the current status for various markets.
Arguments#
region- Optional region override. If None, uses default (US).
Examples#
use finance_query::{finance, Region};
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
// Get US market hours (default)
let hours = finance::hours(None).await?;
// Get Japan market hours
let jp_hours = finance::hours(Some(Region::Japan)).await?;
# Ok(())
# }
indices function#
pub async fn indices( region: Option<crate::constants::indices::Region>, ) -> Result<crate::tickers::BatchQuotesResponse>
Get world market indices quotes
Returns quotes for major world indices, optionally filtered by region.
Arguments#
region- Optional region filter. If None, returns all world indices.
Examples#
use finance_query::{finance, IndicesRegion};
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
// Get all world indices
let all = finance::indices(None).await?;
println!("Fetched {} indices", all.success_count());
// Get only Americas indices
let americas = finance::indices(Some(IndicesRegion::Americas)).await?;
# Ok(())
# }
industry function#
pub async fn industry(industry_key: impl AsRef<str>) -> Result<IndustryData>
Fetch detailed industry data from Yahoo Finance
Returns comprehensive industry information including overview, performance, top companies, top performing companies, top growth companies, and research reports.
Arguments#
industry_key- The industry key/slug (e.g., "semiconductors", "software-infrastructure")
Examples#
use finance_query::finance;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
let industry = finance::industry("semiconductors").await?;
println!("Industry: {} ({} companies)", industry.name,
industry.overview.as_ref().map(|o| o.companies_count.unwrap_or(0)).unwrap_or(0));
for company in industry.top_companies.iter().take(5) {
println!(" {} - {:?}", company.symbol, company.name);
}
# Ok(())
# }
lookup function#
pub async fn lookup( query: &str, options: &LookupOptions, ) -> Result<crate::models::discovery::lookup::LookupResults>
Look up symbols by type (equity, ETF, mutual fund, index, future, currency, cryptocurrency)
Unlike search, lookup specializes in discovering tickers filtered by asset type. Optionally fetches logo URLs via an additional API call.
Arguments#
query- Search term (company name, symbol, etc.)options- Lookup configuration options
Examples#
use finance_query::{finance, LookupOptions, LookupType, Region};
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
// Simple lookup with defaults
let results = finance::lookup("Apple", &LookupOptions::default()).await?;
println!("Found {} results", results.result_count());
// Lookup equities with logos
let options = LookupOptions::new()
.lookup_type(LookupType::Equity)
.count(10)
.include_logo(true);
let results = finance::lookup("NVDA", &options).await?;
for quote in &results.quotes {
println!("{}: {:?}", quote.symbol, quote.logo_url);
}
# Ok(())
# }
market_summary function#
pub async fn market_summary( region: Option<Region>, ) -> Result<Vec<crate::models::market::market_summary::MarketSummaryQuote>>
Get market summary
Returns market summary with major indices, currencies, and commodities.
Arguments#
region- Optional region for localization. If None, uses default (US).
Examples#
use finance_query::{finance, Region};
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
// Use default (US)
let summary = finance::market_summary(None).await?;
// Or specify a region
let summary = finance::market_summary(Some(Region::Canada)).await?;
# Ok(())
# }
news function#
pub async fn news() -> Result<Vec<crate::models::corporate::news::News>>
Get general market news
Examples#
use finance_query::finance;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
let news = finance::news().await?;
for article in news {
println!("{}: {}", article.source, article.title);
}
# Ok(())
# }
screener function#
pub async fn screener(screener_type: Screener, count: u32) -> Result<ScreenerResults>
Fetch data from a predefined Yahoo Finance screener
Returns stocks/funds matching the criteria of the specified screener type.
Arguments#
screener_type- The predefined screener to usecount- Number of results to return (max 250)
Examples#
use finance_query::{finance, Screener};
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
// Get top gainers
let gainers = finance::screener(Screener::DayGainers, 25).await?;
println!("Top gainers: {:#?}", gainers);
// Get most shorted stocks
let shorted = finance::screener(Screener::MostShortedStocks, 25).await?;
// Get growth technology stocks
let tech = finance::screener(Screener::GrowthTechnologyStocks, 25).await?;
# Ok(())
# }
search function#
pub async fn search(query: &str, options: &SearchOptions) -> Result<SearchResults>
Search for stock symbols and companies
Arguments#
query- Search term (company name, symbol, etc.)options- Search configuration options
Examples#
use finance_query::{finance, SearchOptions, Region};
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
// Simple search with defaults
let results = finance::search("Apple", &SearchOptions::default()).await?;
println!("Found {} results", results.result_count());
// Search with custom options
let options = SearchOptions::new()
.quotes_count(10)
.news_count(5)
.enable_research_reports(true)
.region(Region::Canada);
let results = finance::search("NVDA", &options).await?;
println!("Found {} quotes", results.quotes.len());
# Ok(())
# }
sector function#
pub async fn sector(sector_type: Sector) -> Result<SectorData>
Fetch detailed sector data from Yahoo Finance
Returns comprehensive sector information including overview, performance, top companies, ETFs, mutual funds, industries, and research reports.
Arguments#
sector_type- The sector to fetch data for
Examples#
use finance_query::{finance, Sector};
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
let sector = finance::sector(Sector::Technology).await?;
println!("Sector: {} ({} companies)", sector.name,
sector.overview.as_ref().map(|o| o.companies_count.unwrap_or(0)).unwrap_or(0));
for company in sector.top_companies.iter().take(5) {
println!(" {} - {:?}", company.symbol, company.name);
}
# Ok(())
# }
trending function#
pub async fn trending( region: Option<Region>, ) -> Result<Vec<crate::models::discovery::trending::TrendingQuote>>
Get trending tickers for a region
Returns trending stocks for a specific region.
Arguments#
region- Optional region for localization. If None, uses default (US).
Examples#
use finance_query::{finance, Region};
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
// Use default (US)
let trending = finance::trending(None).await?;
// Or specify a region
let trending = finance::trending(Some(Region::Canada)).await?;
# Ok(())
# }
finance_query::fmp#
init function#
pub fn init(api_key: impl Into<String>) -> Result<()>
init_with_timeout function#
pub fn init_with_timeout(api_key: impl Into<String>, timeout: Duration) -> Result<()>
finance_query::format#
Both struct#
pub struct Both
Pretty struct#
pub struct Pretty
Raw struct#
pub struct Raw
finance_query::fred#
MacroObservation struct#
pub struct MacroObservation
MacroSeries struct#
pub struct MacroSeries
ReleaseDate struct#
pub struct ReleaseDate
TreasuryYield struct#
pub struct TreasuryYield
release_dates function#
pub async fn release_dates() -> Result<Vec<ReleaseDate>>
series function#
pub async fn series(series_id: &str) -> Result<MacroSeries>
treasury_yields function#
pub async fn treasury_yields(year: u32) -> Result<Vec<TreasuryYield>>
finance_query::gdelt#
news function#
pub async fn fetch_news_response(symbol: &str) -> Result<Vec<News>>
finance_query::indicators#
AroonResult struct#
pub struct AroonResult
DonchianChannelsResult struct#
pub struct DonchianChannelsResult
ElderRayResult struct#
pub struct BullBearPowerResult
FibonacciLevels struct#
pub struct FibonacciLevels
IchimokuResult struct#
pub struct IchimokuResult
KeltnerChannelsResult struct#
pub struct KeltnerChannelsResult
PivotPoints struct#
pub struct PivotPoints
Result type_alias#
pub type Result<T> = std::result::Result<T, IndicatorError>
Result type for indicator calculations
StochasticResult struct#
pub struct StochasticResult
SuperTrendResult struct#
pub struct SuperTrendResult
ZigZagPoint struct#
pub struct ZigZagPoint
accumulation_distribution function#
pub fn accumulation_distribution( highs: &[f64], lows: &[f64], closes: &[f64], volumes: &[f64], ) -> Result<Vec<Option<f64>>>
adx function#
pub fn adx(highs: &[f64], lows: &[f64], closes: &[f64], period: usize) -> Result<Vec<Option<f64>>>
alma function#
pub fn alma(data: &[f64], period: usize, offset: f64, sigma: f64) -> Result<Vec<Option<f64>>>
aroon function#
pub fn aroon(highs: &[f64], lows: &[f64], period: usize) -> Result<AroonResult>
awesome_oscillator function#
pub fn awesome_oscillator( highs: &[f64], lows: &[f64], fast: usize, slow: usize, ) -> Result<Vec<Option<f64>>>
balance_of_power function#
pub fn balance_of_power( opens: &[f64], highs: &[f64], lows: &[f64], closes: &[f64], period: Option<usize>, ) -> Result<Vec<Option<f64>>>
bollinger_bands function#
pub fn bollinger_bands( data: &[f64], period: usize, std_dev_multiplier: f64, ) -> Result<BollingerBands>
bull_bear_power function#
pub fn bull_bear_power( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, ) -> Result<BullBearPowerResult>
cci function#
pub fn cci(highs: &[f64], lows: &[f64], closes: &[f64], period: usize) -> Result<Vec<Option<f64>>>
chaikin_oscillator function#
pub fn chaikin_oscillator( highs: &[f64], lows: &[f64], closes: &[f64], volumes: &[f64], ) -> Result<Vec<Option<f64>>>
choppiness_index function#
pub fn choppiness_index( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, ) -> Result<Vec<Option<f64>>>
cmf function#
pub fn cmf( highs: &[f64], lows: &[f64], closes: &[f64], volumes: &[f64], period: usize, ) -> Result<Vec<Option<f64>>>
cmo function#
pub fn cmo(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
coppock_curve function#
pub fn coppock_curve( data: &[f64], long_roc: usize, short_roc: usize, wma_period: usize, ) -> Result<Vec<Option<f64>>>
dema function#
pub fn dema(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
donchian_channels function#
pub fn donchian_channels( highs: &[f64], lows: &[f64], period: usize, ) -> Result<DonchianChannelsResult>
elder_ray function#
pub fn elder_ray( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, ) -> Result<ElderRayResult>
ema function#
pub fn ema(data: &[f64], period: usize) -> Vec<Option<f64>>
fibonacci_pivot_points function#
pub fn fibonacci_pivot_points( highs: &[f64], lows: &[f64], closes: &[f64], ) -> Result<Vec<Option<PivotPoints>>>
fibonacci_retracement function#
pub fn fibonacci_retracement( highs: &[f64], lows: &[f64], period: usize, ) -> Result<Vec<Option<FibonacciLevels>>>
heikin_ashi function#
pub fn heikin_ashi(candles: &[Candle]) -> Result<Vec<Candle>>
hma function#
pub fn hma(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
ichimoku function#
pub fn ichimoku( highs: &[f64], lows: &[f64], closes: &[f64], conversion: usize, base: usize, lagging: usize, displacement: usize, ) -> Result<IchimokuResult>
keltner_channels function#
pub fn keltner_channels( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, atr_period: usize, multiplier: f64, ) -> Result<KeltnerChannelsResult>
last_value function#
pub fn last_value(values: &[Option<f64>]) -> Option<f64>
Helper function to extract the last non-None value from a vector.
Useful for converting historical indicator values to latest value only.
Example#
use finance_query::indicators::last_value;
let values = vec![None, None, Some(10.0), Some(20.0)];
assert_eq!(last_value(&values), Some(20.0));
macd function#
pub fn macd( data: &[f64], fast_period: usize, slow_period: usize, signal_period: usize, ) -> Result<MacdResult>
mcginley_dynamic function#
pub fn mcginley_dynamic(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
mfi function#
pub fn mfi( highs: &[f64], lows: &[f64], closes: &[f64], volumes: &[f64], period: usize, ) -> Result<Vec<Option<f64>>>
momentum function#
pub fn momentum(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
obv function#
pub fn obv(closes: &[f64], volumes: &[f64]) -> Result<Vec<Option<f64>>>
parabolic_sar function#
pub fn parabolic_sar( highs: &[f64], lows: &[f64], closes: &[f64], acceleration: f64, maximum: f64, ) -> Result<Vec<Option<f64>>>
pivot_points function#
pub fn pivot_points( highs: &[f64], lows: &[f64], closes: &[f64], ) -> Result<Vec<Option<PivotPoints>>>
roc function#
pub fn roc(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
rsi function#
pub fn rsi(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
sma function#
pub fn sma(data: &[f64], period: usize) -> Vec<Option<f64>>
stochastic function#
pub fn stochastic( highs: &[f64], lows: &[f64], closes: &[f64], k_period: usize, k_slow: usize, d_period: usize, ) -> Result<StochasticResult>
stochastic_rsi function#
pub fn stochastic_rsi( data: &[f64], rsi_period: usize, stoch_period: usize, k_period: usize, d_period: usize, ) -> Result<StochasticResult>
supertrend function#
pub fn supertrend( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, multiplier: f64, ) -> Result<SuperTrendResult>
tema function#
pub fn tema(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
true_range function#
pub fn true_range(highs: &[f64], lows: &[f64], closes: &[f64]) -> Result<Vec<Option<f64>>>
vwap function#
pub fn vwap( highs: &[f64], lows: &[f64], closes: &[f64], volumes: &[f64], ) -> Result<Vec<Option<f64>>>
vwma function#
pub fn vwma(data: &[f64], volumes: &[f64], period: usize) -> Result<Vec<Option<f64>>>
williams_r function#
pub fn williams_r( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, ) -> Result<Vec<Option<f64>>>
wma function#
pub fn wma(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
zigzag function#
pub fn zigzag(highs: &[f64], lows: &[f64], deviation_pct: f64) -> Result<Vec<ZigZagPoint>>
finance_query::indicators::Indicator#
warmup_bars function#
pub fn warmup_bars(&self) -> usize
Minimum number of data bars required before this indicator produces meaningful output.
Used by the backtesting engine's CustomStrategy to automatically
compute the warmup period instead of parsing key-name suffixes.
Examples#
use finance_query::indicators::Indicator;
assert_eq!(Indicator::Sma(20).warmup_bars(), 20);
assert_eq!(Indicator::Macd { fast: 12, slow: 26, signal: 9 }.warmup_bars(), 35);
assert_eq!(Indicator::Bollinger { period: 20, std_dev: 2.0 }.warmup_bars(), 20);
finance_query::models::chart::data::Chart#
pivot_points function#
pub fn pivot_points( &self, ) -> crate::indicators::Result<Vec<Option<crate::indicators::PivotPoints>>>
Calculate classic (standard) Pivot Points.
Each bar's levels are derived from the previous bar's
high/low/close; the first bar is None.
finance_query::models::corporate::calendar_events#
EarningsCalendar struct#
pub struct EarningsCalendar
Earnings calendar information
finance_query::models::corporate::earnings#
EarningsChart struct#
pub struct EarningsChart
Earnings chart showing quarterly data
FinancialsChart struct#
pub struct FinancialsChart
Financial chart showing revenue and earnings over time
QuarterlyEarnings struct#
pub struct QuarterlyEarnings
Quarterly earnings entry
QuarterlyFinancials struct#
pub struct QuarterlyFinancials
Quarterly financial data entry
YearlyFinancials struct#
pub struct YearlyFinancials
Yearly financial data entry
finance_query::models::corporate::earnings_history#
EarningsHistoryEntry struct#
pub struct EarningsHistoryEntry
Single historical earnings entry
finance_query::models::corporate::earnings_trend#
EarningsEstimate struct#
pub struct EarningsEstimate
Earnings estimate data
EarningsTrendPeriod struct#
pub struct EarningsTrendPeriod
Earnings trend for a specific period
EpsRevisions struct#
pub struct EpsRevisions
EPS revision data
EpsTrend struct#
pub struct EpsTrend
EPS trend over time
RevenueEstimate struct#
pub struct RevenueEstimate
Revenue estimate data
finance_query::models::corporate::equity_performance#
Benchmark struct#
pub struct Benchmark
Benchmark information
PerformanceOverview struct#
pub struct PerformanceOverview
Performance metrics across multiple time periods
finance_query::models::corporate::fund_ownership#
FundOwner struct#
pub struct FundOwner
Individual fund owner
finance_query::models::corporate::fund_performance#
AnnualReturn struct#
pub struct AnnualReturn
Single year's return data
AnnualTotalReturns struct#
pub struct AnnualTotalReturns
Annual total returns by year
PastQuarterlyReturns struct#
pub struct PastQuarterlyReturns
Past quarterly returns
PerformanceOverview struct#
pub struct PerformanceOverview
Performance overview with key return metrics
PerformanceOverviewCat struct#
pub struct PerformanceOverviewCat
Category average performance overview
RiskOverviewStatistics struct#
pub struct RiskOverviewStatistics
Risk overview statistics
RiskOverviewStatisticsCat struct#
pub struct RiskOverviewStatisticsCat
Category average risk overview statistics
RiskStatistic struct#
pub struct RiskStatistic
Risk statistics for a specific time period
TrailingReturns struct#
pub struct TrailingReturns
Trailing returns at market price
TrailingReturnsCat struct#
pub struct TrailingReturnsCat
Category average trailing returns
TrailingReturnsNav struct#
pub struct TrailingReturnsNav
Trailing returns at NAV (Net Asset Value)
finance_query::models::corporate::fund_profile#
FeesExpenses struct#
pub struct FeesExpenses
Fees and expenses for a fund
FeesExpensesCat struct#
pub struct FeesExpensesCat
Average fees and expenses for funds in the same category
ManagementInfo struct#
pub struct ManagementInfo
Fund management information
finance_query::models::corporate::insider_holders#
InsiderHolder struct#
pub struct InsiderHolder
Individual insider holder information
finance_query::models::corporate::insider_transactions#
InsiderTransaction struct#
pub struct InsiderTransaction
Individual insider transaction
finance_query::models::corporate::institution_ownership#
InstitutionOwner struct#
pub struct InstitutionOwner
Individual institutional owner
finance_query::models::corporate::recommendation_trend#
RecommendationPeriod struct#
pub struct RecommendationPeriod
Recommendations for a specific time period
finance_query::models::corporate::sec_filings#
SecExhibit struct#
pub struct SecExhibit
SEC filing exhibit
SecFiling struct#
pub struct SecFiling
Individual SEC filing
finance_query::models::corporate::top_holdings#
BondRating struct#
pub struct BondRating
Bond rating distribution
EquityHoldings struct#
pub struct EquityHoldings
Equity holdings valuation metrics
Holding struct#
pub struct Holding
Individual holding in the fund
SectorWeighting struct#
pub struct SectorWeighting
Sector weighting distribution (single sector from Yahoo's array format)
finance_query::models::corporate::transcript#
Paragraph struct#
pub struct Paragraph
A paragraph (section spoken by one speaker).
Sentence struct#
pub struct Sentence
A sentence within a paragraph.
SpeakerData struct#
pub struct SpeakerData
Information about a speaker.
SpeakerMapping struct#
pub struct SpeakerMapping
Mapping of a speaker ID to speaker information.
TranscriptContent struct#
pub struct TranscriptContent
Transcript content including speakers and full transcript.
TranscriptData struct#
pub struct TranscriptData
Full transcript data with paragraphs.
TranscriptMetadata struct#
pub struct TranscriptMetadata
Metadata about the transcript.
Word struct#
pub struct Word
A word with timing and confidence information.
finance_query::models::corporate::upgrade_downgrade_history#
GradeChange struct#
pub struct GradeChange
Individual analyst rating change
finance_query::models::discovery::reference::ScreenerFilters#
new function#
pub fn new() -> Self
An empty filter set — matches the provider's default universe.
finance_query::models::discovery::screeners::query::ScreenerQuery#
add_or_conditions function#
pub fn add_or_conditions(mut self, conditions: Vec<QueryCondition<F>>) -> Self
Add multiple conditions that are OR'd together.
Example#
use finance_query::{EquityField, EquityScreenerQuery, ScreenerFieldExt};
// Accept US or GB region
let query = EquityScreenerQuery::new()
.add_or_conditions(vec![
EquityField::Region.eq_str("us"),
EquityField::Region.eq_str("gb"),
]);
finance_query::models::discovery::search::thumbnail#
NewsThumbnail struct#
pub struct NewsThumbnail
Thumbnail image with multiple resolutions
ThumbnailResolution struct#
pub struct ThumbnailResolution
Individual thumbnail resolution
finance_query::models::filings::filing_index#
EdgarFilingIndexDirectory struct#
pub struct EdgarFilingIndexDirectory
Directory metadata for an EDGAR filing.
finance_query::models::filings::submissions::EdgarFilingRecent#
to_filings function#
pub fn to_filings(&self) -> Vec<EdgarFiling>
Convert parallel arrays into a vector of individual filings.
Example#
# use finance_query::EdgarSubmissions;
# fn example(submissions: EdgarSubmissions) {
if let Some(filings) = &submissions.filings {
if let Some(recent) = &filings.recent {
for filing in recent.to_filings() {
println!("{}: {} ({})", filing.filing_date, filing.form, filing.primary_doc_description);
}
}
}
# }
finance_query::models::format#
Format trait#
pub trait Format: sealed::Sealed + Clone + std::fmt::Debug + PartialEq + 'static
Marker trait that controls how FormattedValue fields are typed.
Sealed — only [Both], [Raw], and [Pretty] implement this trait.
finance_query::models::format::sealed#
Sealed trait#
pub trait Sealed
Blocks external crates from implementing Format;
only this module can name Sealed, so it can only be satisfied here.
finance_query::models::fundamentals::balance_sheet_history#
BalanceSheetHistory struct#
pub struct BalanceSheetHistory
Balance sheet history (annual statements)
BalanceSheetHistoryQuarterly struct#
pub struct BalanceSheetHistoryQuarterly
Balance sheet history (quarterly statements)
finance_query::models::fundamentals::cashflow_statement_history#
CashflowStatementHistory struct#
pub struct CashflowStatementHistory
Cash flow statement history (annual statements)
CashflowStatementHistoryQuarterly struct#
pub struct CashflowStatementHistoryQuarterly
Cash flow statement history (quarterly statements)
finance_query::models::fundamentals::income_statement_history#
IncomeStatementHistory struct#
pub struct IncomeStatementHistory
Income statement history (annual statements)
IncomeStatementHistoryQuarterly struct#
pub struct IncomeStatementHistoryQuarterly
Income statement history (quarterly statements)
finance_query::models::market::index_trend#
TrendEstimate struct#
pub struct TrendEstimate
Growth estimate for a specific period
finance_query::models::market::industries::response#
BenchmarkPerformance struct#
pub struct BenchmarkPerformance
Benchmark performance for comparison
GrowthCompany struct#
pub struct GrowthCompany
Top growth company by growth estimate
IndustryCompany struct#
pub struct IndustryCompany
Company within an industry
IndustryOverview struct#
pub struct IndustryOverview
Industry overview statistics
IndustryPerformance struct#
pub struct IndustryPerformance
Industry performance metrics
PerformingCompany struct#
pub struct PerformingCompany
Top performing company by YTD return
ResearchReport struct#
pub struct ResearchReport
Research report
finance_query::models::market::sectors::response#
ResearchReport struct#
pub struct ResearchReport
A research report about the sector
SectorCompany struct#
pub struct SectorCompany
A company in the sector's top companies list
SectorETF struct#
pub struct SectorETF
An ETF tracking the sector
SectorIndustry struct#
pub struct SectorIndustry
An industry within the sector
SectorMutualFund struct#
pub struct SectorMutualFund
A mutual fund in the sector
SectorOverview struct#
pub struct SectorOverview
Sector overview statistics
SectorPerformance struct#
pub struct SectorPerformance
Sector performance metrics
finance_query::models::quote::data::Quote#
as_raw function#
#[derive(Debug, Clone, Serialize, Deserialize, FormatConvert)]
Clone and convert into a Raw view.
finance_query::models::sentiment::score::Sentiment#
neutral function#
pub fn neutral() -> Self
A neutral, zero-confidence score (used as the empty aggregate).
finance_query::openfigi#
SecurityIdKind enum#
pub enum SecurityIdKind
SecurityMapping struct#
pub struct SecurityMapping
resolve function#
pub async fn resolve(kind: SecurityIdKind, id: &str) -> Result<Vec<SecurityMapping>>
Resolve an identifier of any supported [SecurityIdKind].
resolve_cusip function#
pub async fn resolve_cusip(cusip: &str) -> Result<Vec<SecurityMapping>>
Resolve a CUSIP to every instrument carrying it.
Returns an empty list when the identifier is well-formed but matches nothing; a malformed identifier is an error.
resolve_isin function#
pub async fn resolve_isin(isin: &str) -> Result<Vec<SecurityMapping>>
Resolve an ISIN to every instrument carrying it.
resolve_many function#
pub async fn resolve_many( kind: SecurityIdKind, ids: &[&str], ) -> Result<Vec<Vec<SecurityMapping>>>
Resolve many identifiers of the same kind in as few requests as possible (OpenFIGI accepts 10 per request without a key).
The result is positional: element i answers ids[i], with an empty
list where nothing matched.
resolve_sedol function#
pub async fn resolve_sedol(sedol: &str) -> Result<Vec<SecurityMapping>>
Resolve a SEDOL to every instrument carrying it.
finance_query::providers::adapter#
ProviderCore trait#
pub trait ProviderCore: Send + Sync
Identity shared by every capability trait: the provider id and the
NotSupported error constructor used by default method bodies.
finance_query::providers::adapter::dispatch#
ProviderAdapter trait#
pub trait ProviderAdapter: ProviderCore
A configured provider as seen by [crate::ProviderSet] dispatch: lifecycle
plus one as_* accessor per capability. Override an accessor to
Some(self) for each capability trait the provider implements.
capabilities is derived from which accessors are
overridden, so a provider cannot advertise a capability it does not serve.
finance_query::providers::adapter::equity#
ChartProvider trait#
pub trait ChartProvider: ProviderCore
[crate::Capability::CHART] — historical OHLCV candles and sparklines.
CorporateProvider trait#
pub trait CorporateProvider: ProviderCore
[crate::Capability::CORPORATE] — news, corporate events, similar-symbol
recommendations.
FilingsProvider trait#
pub trait FilingsProvider: ProviderCore
[crate::Capability::FILINGS] — SEC filing data.
FundamentalsProvider trait#
pub trait FundamentalsProvider: ProviderCore
[crate::Capability::FUNDAMENTALS] — financial statements and share-supply data.
OptionsProvider trait#
pub trait OptionsProvider: ProviderCore
[crate::Capability::OPTIONS] — options chains.
QuoteProvider trait#
pub trait QuoteProvider: ProviderCore
[crate::Capability::QUOTE] — single and batch equity quotes.
finance_query::providers::adapter::markets#
CalendarProvider trait#
pub trait CalendarProvider: ProviderCore
[crate::Capability::CALENDAR] — market-wide calendars.
CommoditiesProvider trait#
pub trait CommoditiesProvider: ProviderCore
[crate::Capability::COMMODITIES] — commodity price quotes.
DiscoveryProvider trait#
pub trait DiscoveryProvider: ProviderCore
[crate::Capability::DISCOVERY] — symbol search, reference data, exchanges,
screeners.
FuturesProvider trait#
pub trait FuturesProvider: ProviderCore
[crate::Capability::FUTURES] — futures contract quotes.
IndicesProvider trait#
pub trait IndicesProvider: ProviderCore
[crate::Capability::INDICES] — stock market index quotes.
MarketProvider trait#
pub trait MarketProvider: ProviderCore
[crate::Capability::MARKET] — sector/industry performance and movers.
Movers is the required primary (every current implementor serves it);
the sector/industry statistics default to NotSupported since coverage
is ragged (FMP serves all of them; Yahoo and Alpha Vantage only movers).
finance_query::providers::capability::Capability#
name function#
pub fn name(self) -> &'static str
Returns a short lowercase name for this capability (e.g., "quote", "chart").
Returns "unknown" for combined capability flags or unrecognised bits;
Display spells combined sets out instead (e.g.
"quote|chart").
finance_query::providers::config::Providers#
builder function#
pub fn builder() -> ProvidersBuilder
Create a builder for configuring providers.
calendar function#
pub fn calendar(&self) -> crate::domains::MarketCalendar
Create a MarketCalendar handle backed by this provider set.
Routes market-wide earnings/IPO/dividend/split/economic calendars
through Capability::CALENDAR.
commodity function#
pub fn commodity(&self, symbol: impl Into<String>) -> crate::domains::Commodity
Create a Commodity handle backed by this provider set.
crypto function#
pub fn crypto(&self, id: impl Into<String>) -> crate::domains::CryptoCoin
Create a CryptoCoin handle backed by this provider set.
Compiled in unconditionally. With no built-in provider for this
capability, register one with [ProvidersBuilder::with_adapter] or
enable its feature, or these calls return NoProviderAvailable.
discovery function#
pub fn discovery(&self) -> crate::domains::Discovery
Create a Discovery handle backed by this provider set.
Routes symbol search, reference data, and screening through
Capability::DISCOVERY. Distinct from
[crate::finance::search], which is a Yahoo-only shortcut.
economic function#
pub fn economic(&self, series_id: impl Into<String>) -> crate::domains::EconomicIndicator
Create an EconomicIndicator handle backed by this provider set.
Compiled in unconditionally. With no built-in provider for this
capability, register one with [ProvidersBuilder::with_adapter] or
enable its feature, or these calls return NoProviderAvailable.
economic_catalog function#
pub fn economic_catalog(&self) -> crate::domains::EconomicCatalog
Create an EconomicCatalog handle backed by
this provider set.
Routes series search and category/release browsing through
Capability::ECONOMIC. Unlike
economic it takes no series id — it is how you find
one.
Compiled in unconditionally. With no built-in provider for this
capability, register one with [ProvidersBuilder::with_adapter] or
enable its feature, or these calls return NoProviderAvailable.
filings function#
pub fn filings(&self, symbol: impl Into<String>) -> crate::domains::Filings
Create a Filings handle backed by this provider set.
Always available — EDGAR is auto-injected when no other FILINGS provider is configured.
forex function#
pub fn forex( &self, from: impl Into<String>, to: impl Into<String>, ) -> crate::domains::ForexPair
Create a ForexPair handle backed by this provider set.
Compiled in unconditionally. With no built-in provider for this
capability, register one with [ProvidersBuilder::with_adapter] or
enable its feature, or these calls return NoProviderAvailable.
from_set function#
pub fn from_set(set: Arc<ProviderSet>) -> Self
Wrap a [ProviderSet] assembled by hand.
The lower-level counterpart to builder, for a caller
that has already built its own adapters and route table. Nothing is
initialised: ProviderAdapter::initialize
is the builder's job, so a hand-built set must be ready to use.
futures function#
pub fn futures(&self, symbol: impl Into<String>) -> crate::domains::FuturesContract
Create a FuturesContract handle backed by this provider set.
health function#
pub fn health(&self) -> Vec<ProviderHealth>
Snapshot recent health for every configured provider.
Each [ProviderHealth] entry reflects up to the last 20 dispatch
outcomes recorded in-process for that provider (recency window is
internal and unspecified beyond "recent"), plus a best-effort
rate-limit budget estimate where the provider exposes one. Purely
observational — it does not affect routing or retries.
Example#
use finance_query::Providers;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
let providers = Providers::builder().build().await?;
for health in providers.health() {
println!("{:?}: healthy={}", health.provider, health.is_healthy);
}
# Ok(())
# }
index function#
pub fn index(&self, symbol: impl Into<String>) -> crate::domains::Index
Create an Index handle backed by this provider set.
market function#
pub fn market(&self) -> crate::domains::Market
Create a Market handle backed by this provider set.
Routes sector/industry performance and movers through
Capability::MARKET. Movers work on the
default keyless route (Yahoo screeners); the sector/industry
statistics need a keyed provider (FMP).
snapshot function#
pub fn snapshot(&self) -> crate::domains::Snapshot
Create a Snapshot handle backed by this provider set.
Routes cross-market snapshots through
Capability::QUOTE. Needs a provider whose
snapshot endpoint spans asset classes, currently Polygon alone.
Compiled in unconditionally. With no built-in provider for this
capability, register one with [ProvidersBuilder::with_adapter] or
enable its feature, or these calls return NoProviderAvailable.
ticker function#
pub fn ticker(&self, symbol: impl Into<String>) -> crate::TickerBuilder
Create a TickerBuilder pre-wired to this provider set.
The returned builder accepts the same optional configuration as
Ticker::builder (.cache(), .logo(),
.format()) before calling .build().
The language configured via [ProvidersBuilder::lang] or
[ProvidersBuilder::region] is inherited (override with .lang() on
the returned builder). With the translation feature, a non-English
language translates text fields automatically.
tickers function#
pub fn tickers<S, I>(&self, symbols: I) -> crate::TickersBuilder where S: Into<String>, I: IntoIterator<Item = S>,
Create a TickersBuilder pre-wired to this provider set.
The returned builder accepts the same optional configuration as
Tickers::builder (.cache(),
.max_concurrency(), .logo(), .format()) before calling .build().
The language configured via [ProvidersBuilder::lang] or
[ProvidersBuilder::region] is inherited (override with .lang() on
the returned builder). With the translation feature, a non-English
language translates text fields automatically.
finance_query::providers::config::ProvidersBuilder#
fetch function#
pub fn fetch(mut self, mode: Fetch) -> Self
Configure how providers are queried. Default: Sequential.
Use [Fetch::Sequential] or [Fetch::Parallel].
lang function#
pub fn lang(mut self, lang: impl Into<String>) -> Self
Set the language code (e.g., "en-US", "ja-JP").
Inherited by every Ticker/Tickers handle created from the built
[Providers]. With the translation feature, a non-English language
translates text fields on those handles automatically.
region function#
pub fn region(mut self, region: crate::constants::Region) -> Self
Set the region (automatically sets lang and region code).
retry function#
pub fn retry(mut self, policy: RetryPolicy) -> Self
Opt into retrying FinanceError::RateLimited errors during dispatch
See [RetryPolicy] for the exact semantics.
Default is no retry — omitting this call preserves the exact
prior behavior: a RateLimited error is treated like any other
failure and dispatch moves straight to the next routed provider.
with_adapter function#
pub fn with_adapter(mut self, adapter: Arc<dyn crate::ProviderAdapter>) -> Self
Register an adapter this crate does not build itself.
Route to it by the id its ProviderCore::id
returns, usually [Provider::Custom]. Registering alone does not route
anything: a capability with no explicit route still falls back to its
default provider.
# use std::sync::Arc;
# use finance_query::{Capability, Provider, Providers, ProviderAdapter};
# async fn f(my_adapter: Arc<dyn ProviderAdapter>) -> finance_query::Result<()> {
let providers = Providers::builder()
.with_adapter(my_adapter)
.route(Capability::ECONOMIC, [Provider::custom("my-source")])
.build()
.await?;
# let _ = providers;
# Ok(())
# }
finance_query::providers::operation::Operation#
capability function#
pub fn capability(self) -> Capability
The coarser [Capability] bit this operation falls under.
finance_query::providers::provider::Provider#
capabilities function#
pub fn capabilities(self) -> Capability
Capability bitflags for this provider variant, derived from each
adapter's as_* accessor overrides — implementing a capability trait
and declaring it can no longer drift apart. Yahoo is the one exception:
constructing YahooProvider needs a live auth handshake, so its set is
a const declared beside its accessor overrides (yahoo::CAPS).
[Provider::Custom] returns [Capability::NONE]. An id carries no
adapter, so a custom provider's real set is
ProviderAdapter::capabilities
on the registered instance.
custom function#
pub fn custom(id: &'static str) -> Self
A provider this crate does not build, identified by id.
Interning is process-wide and append-only, so the same id always maps
to the same value and Provider::custom("x") == Provider::custom("x").
finance_query::providers::retry::RetryPolicy#
base_delay function#
pub fn base_delay(mut self, delay: Duration) -> Self
Override the base delay (see [RetryPolicy::base_delay] field docs).
jitter function#
pub fn jitter(mut self, jitter: f64) -> Self
Override the jitter fraction (see [RetryPolicy::jitter] field docs).
max_delay function#
pub fn max_delay(mut self, max_delay: Duration) -> Self
Override the max delay cap (see [RetryPolicy::max_delay] field docs).
max_retry_after function#
pub fn max_retry_after(mut self, max_retry_after: Duration) -> Self
Override the cap on an explicit retry_after hint
(see [RetryPolicy::max_retry_after] field docs).
multiplier function#
pub fn multiplier(mut self, multiplier: f64) -> Self
Override the backoff multiplier (see [RetryPolicy::multiplier] field docs).
finance_query::quote#
AssetProfile struct#
pub struct AssetProfile
CalendarEvents struct#
pub struct CalendarEvents
CompanyOfficer struct#
pub struct CompanyOfficer
DefaultKeyStatistics struct#
pub struct DefaultKeyStatistics<F: Format = Both>
Earnings struct#
pub struct Earnings
EarningsHistory struct#
pub struct EarningsHistory
EarningsTrend struct#
pub struct EarningsTrend
EquityPerformance struct#
pub struct EquityPerformance
FinancialData struct#
pub struct FinancialData<F: Format = Both>
FundOwnership struct#
pub struct FundOwnership
FundPerformance struct#
pub struct FundPerformance
FundProfile struct#
pub struct FundProfile
IndexTrend struct#
pub struct IndexTrend
IndustryTrend struct#
pub struct IndustryTrend
InsiderHolders struct#
pub struct InsiderHolders
InsiderTransactions struct#
pub struct InsiderTransactions
InstitutionOwnership struct#
pub struct InstitutionOwnership
MajorHoldersBreakdown struct#
pub struct MajorHoldersBreakdown
NetSharePurchaseActivity struct#
pub struct NetSharePurchaseActivity
Price struct#
pub struct Price<F: Format = Both>
QuoteTypeData struct#
pub struct QuoteTypeData
RecommendationTrend struct#
pub struct RecommendationTrend
SecFilings struct#
pub struct SecFilings
SectorTrend struct#
pub struct SectorTrend
SummaryDetail struct#
pub struct SummaryDetail<F: Format = Both>
SummaryProfile struct#
pub struct SummaryProfile
TopHoldings struct#
pub struct TopHoldings
UpgradeDowngradeHistory struct#
pub struct UpgradeDowngradeHistory
finance_query::risk#
RiskSummary struct#
pub struct RiskSummary
Comprehensive risk summary for a symbol.
Obtain via Ticker::risk.
beta function#
pub fn beta(asset_returns: &[f64], benchmark_returns: &[f64]) -> Option<f64>
calmar_ratio function#
pub fn calmar_ratio(total_return: f64, years: f64, max_drawdown: f64) -> Option<f64>
historical_cvar function#
pub fn historical_cvar(returns: &[f64], confidence: f64) -> Option<f64>
historical_var function#
pub fn historical_var(returns: &[f64], confidence: f64) -> Option<f64>
information_ratio function#
pub fn information_ratio( asset_returns: &[f64], benchmark_returns: &[f64], periods_per_year: f64, ) -> Option<f64>
kelly_criterion function#
pub fn kelly_criterion(win_rate: f64, avg_win_pct: f64, avg_loss_pct: f64) -> f64
max_drawdown function#
pub fn max_drawdown(returns: &[f64]) -> DrawdownResult
omega_ratio function#
pub fn omega_ratio(returns: &[f64]) -> f64
parametric_cvar function#
pub fn parametric_cvar(returns: &[f64], confidence: f64) -> Option<f64>
parametric_var function#
pub fn parametric_var(returns: &[f64], confidence: f64) -> Option<f64>
sharpe_ratio function#
pub fn sharpe_ratio(returns: &[f64], risk_free_rate: f64, periods_per_year: f64) -> Option<f64>
sortino_ratio function#
pub fn sortino_ratio(returns: &[f64], risk_free_rate: f64, periods_per_year: f64) -> Option<f64>
tracking_error function#
pub fn tracking_error( asset_returns: &[f64], benchmark_returns: &[f64], periods_per_year: f64, ) -> Option<f64>
ulcer_index function#
pub fn ulcer_index(returns: &[f64]) -> f64
win_loss_stats function#
pub fn win_loss_stats(returns: &[f64]) -> (f64, f64, f64)
finance_query::risk::drawdown#
DrawdownResult struct#
pub struct DrawdownResult
Maximum drawdown result.
finance_query::streaming#
AlertCondition enum#
pub enum AlertCondition
AlertConditionKind enum#
pub enum AlertConditionKind
AlertEvaluator struct#
pub struct AlertEvaluator
AlertEvent struct#
pub struct AlertEvent
AlertExt trait#
pub trait AlertExt: Stream<Item = PriceUpdate> + Sized + Unpin
AlertRule struct#
pub struct AlertRule
AlertStream struct#
pub struct AlertStream<S>
AssetClass enum#
pub enum AssetClass
Batched struct#
pub struct Batched<S> where S: Stream,
BookLevel struct#
pub struct BookLevel
DepthStream struct#
stream_handle!
DepthStreamBuilder struct#
pub struct DepthStreamBuilder
EconomicStream struct#
stream_handle!
EconomicStreamBuilder struct#
pub struct EconomicStreamBuilder
Greeks struct#
pub struct Greeks
MarketHoursType enum#
pub enum MarketHoursType
NewsStream struct#
pub struct NewsStream
NewsStreamBuilder struct#
pub struct NewsStreamBuilder
OptionContractUpdate struct#
pub struct OptionContractUpdate
OptionType enum#
pub enum OptionType
OptionsChainStream struct#
stream_handle!
OptionsChainStreamBuilder struct#
pub struct OptionsChainStreamBuilder
OrderBookUpdate struct#
pub struct OrderBookUpdate
PriceSource enum#
pub enum PriceSource
PriceStream struct#
pub struct PriceStream
PriceStreamBuilder struct#
pub struct PriceStreamBuilder
PriceUpdate struct#
pub struct PriceUpdate
QuoteType enum#
pub enum QuoteType
SeriesUpdate struct#
pub struct SeriesUpdate
StreamBatchExt trait#
pub trait StreamBatchExt: Stream + Sized + Unpin
StreamError enum#
pub enum StreamError
StreamResult type_alias#
pub type StreamResult<T> = std::result::Result<T, StreamError>
TradeStream struct#
stream_handle!
TradeStreamBuilder struct#
pub struct TradeStreamBuilder
TradeTick struct#
pub struct TradeTick
finance_query::streaming::book::DepthStreamBuilder#
max_reconnect_attempts function#
stream_builder!( DepthStreamBuilder, pairs = "Add crypto pairs to subscribe to." )
Cap the number of consecutive reconnect attempts before the stream gives up and ends (default: unlimited, i.e. retry forever).
finance_query::streaming::client::PriceStreamBuilder#
max_reconnect_attempts function#
pub fn max_reconnect_attempts(mut self, max: u32) -> Self
Cap the number of consecutive reconnect attempts before the stream gives up and ends (default: unlimited, i.e. retry forever).
finance_query::streaming::news::NewsStream#
resubscribe function#
pub fn resubscribe(&self) -> Self
Create a new receiver for this stream.
Useful when you need multiple consumers of the same news subscription.
finance_query::streaming::news::NewsStreamBuilder#
poll_interval function#
pub fn poll_interval(mut self, interval: Duration) -> Self
Set the interval between polls of all subscribed sources (default: 5 minutes).
finance_query::streaming::options::OptionsChainStreamBuilder#
greeks_refresh function#
pub fn greeks_refresh(mut self, interval: Option<Duration>) -> Self
Interval between greeks/open-interest snapshot refreshes.
None disables them, leaving only WebSocket bid/ask/last (one REST
call per underlying per interval otherwise). Default: 60s.
max_reconnect_attempts function#
stream_builder!( OptionsChainStreamBuilder, underlyings = "Add underlyings (or full OCC contract symbols) to follow." )
Cap the number of consecutive reconnect attempts before the stream gives up and ends (default: unlimited, i.e. retry forever).
finance_query::streaming::pricing#
MarketHoursTypeProto enum#
pub enum MarketHoursTypeProto
Protobuf enum for market hours type
QuoteTypeProto enum#
pub enum QuoteTypeProto
Protobuf enum for quote type
finance_query::streaming::trades::TradeStreamBuilder#
build function#
pub async fn build(self) -> StreamResult<TradeStream>
Build and start the stream.
Errors#
Returns StreamError::ConnectionFailed
when the chosen asset class has no trade feed.
max_reconnect_attempts function#
stream_builder!(TradeStreamBuilder, symbols = "Add symbols to subscribe to.")
Cap the number of consecutive reconnect attempts before the stream gives up and ends (default: unlimited, i.e. retry forever).
finance_query::ticker::core::Ticker#
builder function#
pub fn builder(symbol: impl Into<String>) -> TickerBuilder
Creates a new builder for Ticker.
calendar function#
pub async fn calendar( &self, range: TimeRange, ) -> Result<Vec<crate::models::calendar::CalendarEvent>>
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.
client_handle function#
pub fn client_handle(&self) -> ClientHandle
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 with
no Yahoo provider configured. For session sharing across multiple tickers,
prefer Providers::ticker instead.
dividend_analytics function#
pub async fn dividend_analytics(&self, range: TimeRange) -> Result<DividendAnalytics>
Compute dividend analytics for the requested time range.
edgar_company_facts function#
pub async fn edgar_company_facts(&self) -> Result<CompanyFacts>
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.
edgar_submissions function#
pub async fn edgar_submissions(&self) -> Result<EdgarSubmissions>
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 instead.
filings function#
pub async fn filings(&self) -> Result<ProviderFilings>
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 / edgar_company_facts.
financials function#
pub async fn financials( &self, stmt_type: StatementType, frequency: Frequency, ) -> Result<FinancialStatement>
Get financial statements.
news function#
pub async fn news(&self) -> Result<Vec<News>>
Get news articles for this symbol.
price function#
super::macros::define_quote_accessors!
Regular, pre- and post-market price, plus the day's range and volume.
quote function#
pub async fn quote<F>(&self) -> Result<Quote<F>> where F: Format, Quote<Both>: Into<Quote<F>>,
Get full quote data, optionally including logo URLs.
rating_consensus function#
pub async fn rating_consensus(&self) -> Result<crate::models::fundamentals::RatingConsensus>
Fetch the aggregated analyst rating consensus (grade distribution plus a
headline label) via the configured [Capability::FUNDAMENTALS] provider
(currently FMP only). Distinct from
recommendations, which returns similar symbols.
recommendations function#
pub async fn recommendations(&self, limit: u32) -> Result<Recommendation>
Get analyst recommendations and similar symbols.
risk function#
pub async fn risk( &self, interval: Interval, range: TimeRange, benchmark: Option<&str>, ) -> Result<risk::RiskSummary>
Compute a risk summary for this symbol.
finance_query::ticker::core::TickerBuilder#
build function#
pub async fn build(self) -> Result<Ticker>
Build the Ticker instance.
cache function#
pub fn cache(mut self, ttl: Duration) -> Self
Cache responses for ttl instead of the default 60 seconds.
no_cache function#
pub fn no_cache(mut self) -> 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.
finance_query::tickers::core::Tickers#
builder function#
pub fn builder<S, I>(symbols: I) -> TickersBuilder where S: Into<String>, I: IntoIterator<Item = S>,
Creates a new builder for Tickers
charts function#
pub async fn charts( &self, interval: Interval, range: TimeRange, ) -> Result<BatchChartsResponse>
Batch fetch charts for all symbols concurrently
Chart data cannot be batched in a single request, so this fetches all charts concurrently using tokio for maximum performance.
client_handle function#
pub fn client_handle(&self) -> ClientHandle
Returns a handle to the underlying Yahoo Finance session.
Pass to Ticker::builder or other
[Tickers::builder] calls via .client(handle) to share the
authenticated session without a new auth handshake.
Panics#
Panics if these tickers were created via Providers with
no Yahoo provider configured. For session sharing across multiple tickers,
prefer Providers::tickers instead.
finance_query::tickers::core::TickersBuilder#
logo function#
pub fn logo(mut self) -> Self
Include company logo URLs in quote responses.
When enabled, quotes() will fetch logo URLs in parallel with the
quote batch request, adding a small extra request.
finance_query::translation#
Lang struct#
pub struct Lang
Translatable trait#
pub trait Translatable
TranslationBackend trait#
pub trait TranslationBackend: Send + Sync
set_backend function#
pub fn set_backend(backend: Arc<dyn TranslationBackend>)
translate function#
pub async fn translate<T: Translatable + ?Sized>(value: &mut T, lang: &str) -> Result<()>
Translate the human-readable text fields of a value in place.
lang is a BCP 47 language tag (e.g. "ja", "de-DE", "zh-Hant").
English targets are a no-op. Returns an error for structurally invalid
tags or when the machine-translation backend fails; fields not covered
by the dictionary are left in English when no backend is available.
translate_texts function#
pub async fn translate_texts<S, I>(texts: I, lang: &Lang) -> Result<Vec<String>> where S: Into<String>, I: IntoIterator<Item = S>,
Translate a batch of raw English texts, preserving order.
Applies the dictionary, the process-wide memo cache, and the active machine-translation backend in that order. Texts without a dictionary hit are returned unchanged when no backend is available.
translate_with function#
pub async fn translate_with<T: Translatable + ?Sized>(value: &mut T, lang: &Lang) -> Result<()>
Like [translate], with an already-parsed [Lang].
