finance-query v3.0.0

finance-query API reference#

Generated by cargo soothfast docs reference Measurements and verified claims come from the latest baseline; CI gates them.

finance_query#

AnalystEstimate struct#

rust · ignore
pub struct AnalystEstimate

AnalystRecommendation struct#

rust · ignore
pub struct AnalystRecommendation

AroonData struct#

rust · ignore
pub struct AroonData

AssetClass enum#

rust · ignore
pub enum AssetClass

BatchCapitalGainsResponse struct#

rust · ignore
define_batch_response!

BatchChartsResponse struct#

rust · ignore
define_batch_response!

BatchDividendsResponse struct#

rust · ignore
define_batch_response!

BatchFinancialsResponse struct#

rust · ignore
define_batch_response!

BatchIndicatorsResponse struct#

rust · ignore
define_batch_response!

BatchNewsResponse struct#

rust · ignore
define_batch_response!

BatchOptionsResponse struct#

rust · ignore
define_batch_response!

BatchQuotesResponse struct#

rust · ignore
define_batch_response!

BatchRecommendationsResponse struct#

rust · ignore
define_batch_response!

BatchSparksResponse struct#

rust · ignore
define_batch_response!

BatchSplitsResponse struct#

rust · ignore
define_batch_response!

BollingerBands struct#

rust · ignore
pub struct BollingerBands

BollingerBandsData struct#

rust · ignore
pub struct BollingerBandsData

BullBearPowerData struct#

rust · ignore
pub struct BullBearPowerData

CalendarDetail enum#

rust · ignore
pub enum CalendarDetail

CalendarEvent struct#

rust · ignore
pub struct CalendarEvent

CalendarKind enum#

rust · ignore
pub enum CalendarKind

Candle struct#

rust · ignore
pub struct Candle

CandlePattern enum#

rust · ignore
pub enum CandlePattern

Capability struct#

rust · ignore
pub struct Capability(u32)
verified claims
allocallocs 0 <= 0
measured as `finance_query::dispatch_select`
instructions/iter68
callgrind Ir/iter68
median walltime (ns)4
p99 walltime (ns)5
allocations/iter0
allocated bytes/iter0

CapitalGain struct#

rust · ignore
pub struct CapitalGain

Chart struct#

rust · ignore
pub struct Chart
measured as `finance_query::de_chart`
instructions/iter109161
callgrind Ir/iter109161
median walltime (ns)9081
p99 walltime (ns)9173
allocations/iter13
allocated bytes/iter4369

ChartEvents struct#

rust · ignore
pub struct ChartEvents

ChartMeta struct#

rust · ignore
pub struct ChartMeta

CikEntry struct#

rust · ignore
pub struct CikEntry

ClientHandle struct#

rust · ignore
pub struct ClientHandle(pub(crate) Arc<YahooClient>)

CommitmentsOfTraders struct#

rust · ignore
pub struct CommitmentsOfTraders

Commodity struct#

rust · ignore
domain_handle!

CommodityQuote struct#

rust · ignore
pub struct CommodityQuote

CompanyFacts struct#

rust · ignore
pub struct CompanyFacts
measured as `finance_query::de_edgar_facts`
instructions/iter13991183
callgrind Ir/iter13991183
median walltime (ns)1371110
p99 walltime (ns)1491476
allocations/iter11899
allocated bytes/iter1356382

CompanyProfile struct#

rust · ignore
pub struct CompanyProfile

ConditionValue enum#

rust · ignore
pub enum ConditionValue

CongressionalTrade struct#

rust · ignore
pub struct CongressionalTrade

Contracts struct#

rust · ignore
pub struct Contracts(pub Vec<OptionContract>)

CotObservation struct#

rust · ignore
pub struct CotObservation

CryptoCoin struct#

rust · ignore
domain_handle!

CryptoProvider trait#

rust · ignore
pub trait CryptoProvider: ProviderCore

CryptoQuote struct#

rust · ignore
pub struct CryptoQuote

Currency struct#

rust · ignore
pub struct Currency
measured as `finance_query::de_currencies`
instructions/iter602439
callgrind Ir/iter602439
median walltime (ns)56181
p99 walltime (ns)56700
allocations/iter647
allocated bytes/iter54672
measured as `finance_query::ser_currencies`
instructions/iter223104
callgrind Ir/iter223104
median walltime (ns)16254
p99 walltime (ns)16673
allocations/iter8
allocated bytes/iter32640

CustomId struct#

rust · ignore
pub struct CustomId(u16)

Discovery struct#

rust · ignore
domain_handle!

Dividend struct#

rust · ignore
pub struct Dividend

DividendAnalytics struct#

rust · ignore
pub struct DividendAnalytics

DonchianChannelsData struct#

rust · ignore
pub struct DonchianChannelsData

EarningsCalendarEntry struct#

rust · ignore
pub struct EarningsCalendarEntry

EarningsSurprise struct#

rust · ignore
pub struct EarningsSurprise

EarningsTranscript struct#

rust · ignore
pub struct EarningsTranscript

EconomicCatalog struct#

rust · ignore
pub struct EconomicCatalog

EconomicCategory struct#

rust · ignore
pub struct EconomicCategory

EconomicIndicator struct#

rust · ignore
domain_handle!

EconomicProvider trait#

rust · ignore
pub trait EconomicProvider: ProviderCore

EconomicRelease struct#

rust · ignore
pub struct EconomicRelease

EconomicSeries struct#

rust · ignore
pub struct EconomicSeries

EconomicSeriesMatch struct#

rust · ignore
pub struct EconomicSeriesMatch

EdgarFiling struct#

rust · ignore
pub struct EdgarFiling

EdgarFilingFile struct#

rust · ignore
pub struct EdgarFilingFile

EdgarFilingIndex struct#

rust · ignore
pub struct EdgarFilingIndex

EdgarFilingIndexItem struct#

rust · ignore
pub struct EdgarFilingIndexItem

EdgarFilingRecent struct#

rust · ignore
pub struct EdgarFilingRecent

EdgarFilings struct#

rust · ignore
pub struct EdgarFilings

EdgarSearchHit struct#

rust · ignore
pub struct EdgarSearchHit

EdgarSearchHitsContainer struct#

rust · ignore
pub struct EdgarSearchHitsContainer

EdgarSearchResults struct#

rust · ignore
pub struct EdgarSearchResults

EdgarSearchSource struct#

rust · ignore
pub struct EdgarSearchSource

EdgarSearchTotal struct#

rust · ignore
pub struct EdgarSearchTotal

EdgarSubmissions struct#

rust · ignore
pub struct EdgarSubmissions
measured as `finance_query::de_edgar_submissions`
instructions/iter5293321
callgrind Ir/iter5293321
median walltime (ns)451730
p99 walltime (ns)469569
allocations/iter6784
allocated bytes/iter465397

ElderRayData struct#

rust · ignore
pub struct ElderRayData

EmployeeCount struct#

rust · ignore
pub struct EmployeeCount

EquityField enum#

rust · ignore
pub enum EquityField

EquityScreenerQuery type_alias#

rust · ignore
pub type EquityScreenerQuery = ScreenerQuery<EquityField>

ErrorCategory enum#

rust · ignore
pub enum ErrorCategory

EtfCountryWeighting struct#

rust · ignore
pub struct EtfCountryWeighting

EtfHolding struct#

rust · ignore
pub struct EtfHolding

EtfProfile struct#

rust · ignore
pub struct EtfProfile

EtfSectorWeighting struct#

rust · ignore
pub struct EtfSectorWeighting

EventKind enum#

rust · ignore
pub enum EventKind

Exchange struct#

rust · ignore
pub struct Exchange

ExchangeCode enum#

rust · ignore
pub enum ExchangeCode

ExchangeInfo struct#

rust · ignore
pub struct ExchangeInfo

ExecutiveCompensation struct#

rust · ignore
pub struct ExecutiveCompensation

FactConcept struct#

rust · ignore
pub struct FactConcept

FactUnit struct#

rust · ignore
pub struct FactUnit

FactsByTaxonomy struct#

rust · ignore
pub struct FactsByTaxonomy(pub HashMap<String, FactConcept>)

FailToDeliver struct#

rust · ignore
pub struct FailToDeliver

FearAndGreed struct#

rust · ignore
pub struct FearAndGreed
measured as `finance_query::de_fear_and_greed`
instructions/iter1425
callgrind Ir/iter1425
median walltime (ns)120
p99 walltime (ns)123
allocations/iter0
allocated bytes/iter0
measured as `finance_query::de_fear_and_greed_crypto_history`
instructions/iter15650
callgrind Ir/iter15650
median walltime (ns)1356
p99 walltime (ns)1397
allocations/iter3
allocated bytes/iter448

FearGreedLabel enum#

rust · ignore
pub enum FearGreedLabel

Fetch enum#

rust · ignore
pub enum Fetch

FilingSearchFilters struct#

rust · ignore
pub struct FilingSearchFilters

FilingSearchHit struct#

rust · ignore
pub struct FilingSearchHit

FilingSection struct#

rust · ignore
pub struct FilingSection

FilingSectionForm enum#

rust · ignore
pub enum FilingSectionForm

Filings struct#

rust · ignore
domain_handle!

FinanceError enum#

rust · ignore
pub enum FinanceError

FinancialRatiosTtm struct#

rust · ignore
pub struct FinancialRatiosTtm

FinancialStatement struct#

rust · ignore
pub struct FinancialStatement
measured as `finance_query::de_financials`
instructions/iter236900
callgrind Ir/iter236900
median walltime (ns)20546
p99 walltime (ns)20765
allocations/iter206
allocated bytes/iter22532

ForexPair struct#

rust · ignore
domain_handle!

ForexProvider trait#

rust · ignore
pub trait ForexProvider: ProviderCore

ForexQuote struct#

rust · ignore
pub struct ForexQuote

FormattedValue struct#

rust · ignore
pub struct FormattedValue<T>

Frequency enum#

rust · ignore
pub enum Frequency

FundField enum#

rust · ignore
pub enum FundField

FundScreenerQuery type_alias#

rust · ignore
pub type FundScreenerQuery = ScreenerQuery<FundField>

FuturesContract struct#

rust · ignore
domain_handle!

FuturesQuote struct#

rust · ignore
pub struct FuturesQuote

GradingAction struct#

rust · ignore
pub struct GradingAction

IchimokuData struct#

rust · ignore
pub struct IchimokuData

Index struct#

rust · ignore
domain_handle!

IndexConstituent struct#

rust · ignore
pub struct IndexConstituent

IndexConstituentChange struct#

rust · ignore
pub struct IndexConstituentChange

IndexQuote struct#

rust · ignore
pub struct IndexQuote

Indicator enum#

rust · ignore
pub enum Indicator

IndicatorError enum#

rust · ignore
pub enum IndicatorError

IndicatorResult enum#

rust · ignore
pub enum IndicatorResult

IndicatorsSummary struct#

rust · ignore
pub struct IndicatorsSummary

IndicesRegion enum#

rust · ignore
pub enum Region

Industry enum#

rust · ignore
pub enum Industry

IndustryData struct#

rust · ignore
pub struct IndustryData

IndustryPe struct#

rust · ignore
pub struct IndustryPe

InsiderTrade struct#

rust · ignore
pub struct InsiderTrade

InsiderTransaction struct#

rust · ignore
pub struct InsiderTransaction

InstitutionalHolding struct#

rust · ignore
pub struct InstitutionalHolding

Interval enum#

rust · ignore
pub enum Interval

IpoCalendarEntry struct#

rust · ignore
pub struct IpoCalendarEntry

KeltnerChannelsData struct#

rust · ignore
pub struct KeltnerChannelsData

KeyMetricsTtm struct#

rust · ignore
pub struct KeyMetricsTtm

LogicalOperator enum#

rust · ignore
pub enum LogicalOperator

LookupOptions struct#

rust · ignore
pub struct LookupOptions

LookupQuote struct#

rust · ignore
pub struct LookupQuote

LookupResults struct#

rust · ignore
pub struct LookupResults

LookupType enum#

rust · ignore
pub enum LookupType

MacdData struct#

rust · ignore
pub struct MacdData

MacdResult struct#

rust · ignore
pub struct MacdResult

MajorIndex enum#

rust · ignore
pub enum MajorIndex

Market struct#

rust · ignore
pub struct Market

MarketCalendar struct#

rust · ignore
domain_handle!

MarketCalendarEntry struct#

rust · ignore
pub struct MarketCalendarEntry

MarketHours struct#

rust · ignore
pub struct MarketHours
measured as `finance_query::de_hours`
instructions/iter7536
callgrind Ir/iter7536
median walltime (ns)712
p99 walltime (ns)728
allocations/iter10
allocated bytes/iter1046

MarketSnapshot struct#

rust · ignore
pub struct MarketSnapshot

MarketSummaryQuote struct#

rust · ignore
pub struct MarketSummaryQuote
measured as `finance_query::de_market_summary`
instructions/iter262258
callgrind Ir/iter262258
median walltime (ns)30479
p99 walltime (ns)31456
allocations/iter228
allocated bytes/iter36044

MarketTime struct#

rust · ignore
pub struct MarketTime

MoverDirection enum#

rust · ignore
pub enum MoverDirection

MoverQuote struct#

rust · ignore
pub struct MoverQuote

News struct#

rust · ignore
pub struct News
measured as `finance_query::de_news`
instructions/iter45306
callgrind Ir/iter45306
median walltime (ns)3757
p99 walltime (ns)4033
allocations/iter53
allocated bytes/iter6690

Operation enum#

rust · ignore
pub enum Operation

Operator enum#

rust · ignore
pub enum Operator

OptionChain struct#

rust · ignore
pub struct OptionChain

OptionContract struct#

rust · ignore
pub struct OptionContract

Options struct#

rust · ignore
pub struct Options
measured as `finance_query::de_options`
instructions/iter12505
callgrind Ir/iter12505
median walltime (ns)1052
p99 walltime (ns)1119
allocations/iter6
allocated bytes/iter1028

OptionsQuote struct#

rust · ignore
pub struct OptionsQuote

PatternSentiment enum#

rust · ignore
pub enum PatternSentiment

Period enum#

rust · ignore
pub enum Period

PressRelease struct#

rust · ignore
pub struct PressRelease

PriceTargetConsensus struct#

rust · ignore
pub struct PriceTargetConsensus

PriceTargetSummary struct#

rust · ignore
pub struct PriceTargetSummary

Provider enum#

rust · ignore
pub enum Provider

ProviderFiling struct#

rust · ignore
pub struct ProviderFiling

ProviderFilings struct#

rust · ignore
pub struct ProviderFilings

ProviderHealth struct#

rust · ignore
pub struct ProviderHealth

Providers struct#

rust · ignore
pub struct Providers

ProvidersBuilder struct#

rust · ignore
pub struct ProvidersBuilder

QueryCondition struct#

rust · ignore
pub struct QueryCondition<F: ScreenerField>

QueryGroup struct#

rust · ignore
pub struct QueryGroup<F: ScreenerField>

QueryOperand enum#

rust · ignore
pub enum QueryOperand<F: ScreenerField>

Quote struct#

rust · ignore
pub struct Quote<F: Format = Both>
verified claims
p99p99 1050708ns <= 3000000ns
measured as `finance_query::de_quote`
instructions/iter9568263
callgrind Ir/iter9568263
median walltime (ns)1027704
p99 walltime (ns)1050708
allocations/iter8235
allocated bytes/iter767090

QuoteSummaryResponse struct#

rust · ignore
pub struct QuoteSummaryResponse

QuoteType enum#

rust · ignore
pub enum QuoteType

RatingConsensus struct#

rust · ignore
pub struct RatingConsensus

Recommendation struct#

rust · ignore
pub struct Recommendation

Region enum#

rust · ignore
pub enum Region

ResearchReport struct#

rust · ignore
pub struct ResearchReport

ResearchReports struct#

rust · ignore
pub struct ResearchReports(pub Vec<ResearchReport>)

Result type_alias#

rust · ignore
pub type Result<T> = std::result::Result<T, FinanceError>

RetryPolicy struct#

rust · ignore
pub struct RetryPolicy

RiskFactor struct#

rust · ignore
pub struct RiskFactor

Routes struct#

rust · ignore
pub struct Routes

Screener enum#

rust · ignore
pub enum Screener

ScreenerField trait#

rust · ignore
pub trait ScreenerField: Clone + Serialize + 'static

ScreenerFieldExt trait#

rust · ignore
pub trait ScreenerFieldExt: ScreenerField + Sized

ScreenerFilters struct#

rust · ignore
pub struct ScreenerFilters

ScreenerFundCategory enum#

rust · ignore
pub enum ScreenerFundCategory

ScreenerMatch struct#

rust · ignore
pub struct ScreenerMatch

ScreenerPeerGroup enum#

rust · ignore
pub enum ScreenerPeerGroup

ScreenerQuery struct#

rust · ignore
pub struct ScreenerQuery<F: ScreenerField = EquityField>

ScreenerQuote struct#

rust · ignore
pub struct ScreenerQuote

ScreenerResults struct#

rust · ignore
pub struct ScreenerResults
measured as `finance_query::de_screener`
instructions/iter3849278
callgrind Ir/iter3849278
median walltime (ns)382528
p99 walltime (ns)399916
allocations/iter4498
allocated bytes/iter484379

SearchNews struct#

rust · ignore
pub struct SearchNews

SearchNewsList struct#

rust · ignore
pub struct SearchNewsList(pub Vec<SearchNews>)

SearchOptions struct#

rust · ignore
pub struct SearchOptions

SearchQuote struct#

rust · ignore
pub struct SearchQuote

SearchQuotes struct#

rust · ignore
pub struct SearchQuotes(pub Vec<SearchQuote>)

SearchResults struct#

rust · ignore
pub struct SearchResults
measured as `finance_query::de_search`
instructions/iter56239
callgrind Ir/iter56239
median walltime (ns)5335
p99 walltime (ns)5441
allocations/iter55
allocated bytes/iter5105

Sector enum#

rust · ignore
pub enum Sector

SectorData struct#

rust · ignore
pub struct SectorData

SectorPe struct#

rust · ignore
pub struct SectorPe

SectorPerformance struct#

rust · ignore
pub struct SectorPerformance

SectorPerformanceHistory struct#

rust · ignore
pub struct SectorPerformanceHistory

Sentiment struct#

rust · ignore
pub struct Sentiment

SentimentLabel enum#

rust · ignore
pub enum SentimentLabel

ShareFloat struct#

rust · ignore
pub struct ShareFloat

ShortInterest struct#

rust · ignore
pub struct ShortInterest

ShortVolume struct#

rust · ignore
pub struct ShortVolume

SimilarSymbol struct#

rust · ignore
pub struct SimilarSymbol

Snapshot struct#

rust · ignore
domain_handle!

SortType enum#

rust · ignore
pub enum SortType

Spark struct#

rust · ignore
pub struct Spark

SparkData struct#

rust · ignore
pub struct SparkData

Split struct#

rust · ignore
pub struct Split

StatementType enum#

rust · ignore
pub enum StatementType

StochasticData struct#

rust · ignore
pub struct StochasticData

SuperTrendData struct#

rust · ignore
pub struct SuperTrendData

SymbolDetails struct#

rust · ignore
pub struct SymbolDetails

SymbolMatch struct#

rust · ignore
pub struct SymbolMatch

SymbolSentiment struct#

rust · ignore
pub struct SymbolSentiment

Ticker struct#

rust · ignore
pub struct Ticker

TickerBuilder struct#

rust · ignore
pub struct TickerBuilder

Tickers struct#

rust · ignore
pub struct Tickers

TickersBuilder struct#

rust · ignore
pub struct TickersBuilder

TimeRange enum#

rust · ignore
pub enum TimeRange

Transcript struct#

rust · ignore
pub struct Transcript

TranscriptWithMeta struct#

rust · ignore
pub struct TranscriptWithMeta

TrendingQuote struct#

rust · ignore
pub struct TrendingQuote
measured as `finance_query::de_trending`
instructions/iter18398
callgrind Ir/iter18398
median walltime (ns)1349
p99 walltime (ns)1548
allocations/iter24
allocated bytes/iter1551

ValueFormat enum#

rust · ignore
pub enum ValueFormat

analyst_estimates function#

rust · ignore
pub async fn analyst_estimates(symbol: &str, period: Period) -> Result<Vec<AnalystEstimate>>

analyst_recommendations function#

rust · ignore
pub async fn analyst_recommendations(symbol: &str) -> Result<Vec<AnalystRecommendation>>

analyze_sentiment function#

rust · ignore
pub fn analyze(text: &str) -> Sentiment
measured as `finance_query::score_news`
instructions/iter922214
callgrind Ir/iter922214
median walltime (ns)78963
p99 walltime (ns)80369
allocations/iter976
allocated bytes/iter17381

atr function#

rust · ignore
pub fn atr(highs: &[f64], lows: &[f64], closes: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_atr`
instructions/iter57477
callgrind Ir/iter57477
median walltime (ns)11069
p99 walltime (ns)11186
allocations/iter2
allocated bytes/iter23896

earnings_calendar function#

rust · ignore
pub async fn earnings_calendar() -> Result<Vec<EarningsCalendarEntry>>

insider_trading function#

rust · ignore
pub async fn insider_trading(symbol: &str, limit: u32) -> Result<Vec<InsiderTransaction>>

ipo_calendar function#

rust · ignore
pub async fn ipo_calendar() -> Result<Vec<IpoCalendarEntry>>

patterns function#

rust · ignore
pub fn patterns(candles: &[Candle]) -> Vec<Option<CandlePattern>>
verified claims
complexityclaimed O(n); growth drift x1.12 over sizes [1024, 4096, 16384] (limit x2.5)
measured as `finance_query::ind_patterns`
instructions/iter1184450
callgrind Ir/iter1184450
median walltime (ns)96129
p99 walltime (ns)97923
allocations/iter1
allocated bytes/iter16384

symbol_sentiment function#

rust · ignore
pub async fn symbol_sentiment(symbol: &str) -> Result<crate::models::sentiment::SymbolSentiment>

finance_query::adapters::alphavantage::models#

EarningsCalendarEntryDTO struct#

rust · ignore
pub struct EarningsCalendarEntryDTO

A single earnings calendar entry.

IpoCalendarEntryDTO struct#

rust · ignore
pub struct IpoCalendarEntryDTO

A single IPO calendar entry.

finance_query::adapters::fmp::corporate::insider_trading#

InsiderTradeDTO struct#

rust · ignore
pub struct InsiderTradeDTO

Insider trading transaction record.

finance_query::adapters::fmp::fundamentals::estimates#

AnalystEstimateDTO struct#

rust · ignore
pub struct AnalystEstimateDTO

Analyst estimate entry.

AnalystRecommendationDTO struct#

rust · ignore
pub struct AnalystRecommendationDTO

Analyst recommendation entry.

finance_query::backtesting#

BacktestComparison struct#

rust · ignore
pub struct BacktestComparison

BacktestConfig struct#

rust · ignore
pub struct BacktestConfig

BacktestConfigBuilder struct#

rust · ignore
pub struct BacktestConfigBuilder

BacktestEngine struct#

rust · ignore
pub struct BacktestEngine

BacktestError enum#

rust · ignore
pub enum BacktestError

BacktestResult struct#

rust · ignore
pub struct BacktestResult

BayesianSearch struct#

rust · ignore
pub struct BayesianSearch
measured as `finance_query::bt_bayesian_search`
instructions/iter29255228
callgrind Ir/iter29255228
median walltime (ns)3018947
p99 walltime (ns)3070703
allocations/iter2382
allocated bytes/iter2592578

BenchmarkMetrics struct#

rust · ignore
pub struct BenchmarkMetrics

BollingerMeanReversion struct#

rust · ignore
pub struct BollingerMeanReversion

ComparisonReport struct#

rust · ignore
pub struct ComparisonReport

ComparisonRow struct#

rust · ignore
pub struct ComparisonRow

DonchianBreakout struct#

rust · ignore
pub struct DonchianBreakout

EnsembleMode enum#

rust · ignore
pub enum EnsembleMode

EnsembleStrategy struct#

rust · ignore
pub struct EnsembleStrategy

EquityPoint struct#

rust · ignore
pub struct EquityPoint

GridSearch struct#

rust · ignore
pub struct GridSearch
measured as `finance_query::bt_grid_search`
instructions/iter13141738
callgrind Ir/iter13141738
median walltime (ns)673122
p99 walltime (ns)798782
allocations/iter3012
allocated bytes/iter3101794

MacdSignal struct#

rust · ignore
pub struct MacdSignal

MonteCarloConfig struct#

rust · ignore
pub struct MonteCarloConfig
measured as `finance_query::bt_monte_carlo`
instructions/iter1091477
callgrind Ir/iter1091477
median walltime (ns)177047
p99 walltime (ns)178857
allocations/iter6
allocated bytes/iter16384

MonteCarloMethod enum#

rust · ignore
pub enum MonteCarloMethod

MonteCarloResult struct#

rust · ignore
pub struct MonteCarloResult

OptimizationReport struct#

rust · ignore
pub struct OptimizationReport

OptimizationResult struct#

rust · ignore
pub struct OptimizationResult

OptimizeMetric enum#

rust · ignore
pub enum OptimizeMetric

OrderType enum#

rust · ignore
pub enum OrderType

ParamRange enum#

rust · ignore
pub enum ParamRange

ParamValue enum#

rust · ignore
pub enum ParamValue

ParetoPoint struct#

rust · ignore
pub struct ParetoPoint

ParetoReport struct#

rust · ignore
pub struct ParetoReport

PendingOrder struct#

rust · ignore
pub struct PendingOrder

PercentileStats struct#

rust · ignore
pub struct PercentileStats

PerformanceMetrics struct#

rust · ignore
pub struct PerformanceMetrics

Position struct#

rust · ignore
pub struct Position

PositionExtremes struct#

rust · ignore
pub struct PositionExtremes

PositionSide enum#

rust · ignore
pub enum PositionSide

PositionSizing enum#

rust · ignore
pub enum PositionSizing

Result type_alias#

rust · ignore
pub type Result<T> = std::result::Result<T, BacktestError>

RsiReversal struct#

rust · ignore
pub struct RsiReversal

Signal struct#

rust · ignore
pub struct Signal

SignalDirection enum#

rust · ignore
pub enum SignalDirection

SignalMetadata struct#

rust · ignore
pub struct SignalMetadata

SignalRecord struct#

rust · ignore
pub struct SignalRecord

SignalStrength struct#

rust · ignore
pub struct SignalStrength(f64)

SizingContext struct#

rust · ignore
pub struct SizingContext

SmaCrossover struct#

rust · ignore
pub struct SmaCrossover

Strategy trait#

rust · ignore
pub trait Strategy: Send + Sync

StrategyBuilder struct#

rust · ignore
pub struct StrategyBuilder<E = (), X = ()>
measured as `finance_query::bt_strategy_builder`
instructions/iter1075236
callgrind Ir/iter1075236
median walltime (ns)188114
p99 walltime (ns)194384
allocations/iter328
allocated bytes/iter265698

StrategyContext struct#

rust · ignore
pub struct StrategyContext<'a>

SuperTrendFollow struct#

rust · ignore
pub struct SuperTrendFollow

Trade struct#

rust · ignore
pub struct Trade

WalkForwardConfig struct#

rust · ignore
pub struct WalkForwardConfig

WalkForwardReport struct#

rust · ignore
pub struct WalkForwardReport

WindowResult struct#

rust · ignore
pub struct WindowResult

finance_query::backtesting::comparison::BacktestComparison#

ranked_by function#

rust · ignore
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#

rust · ignore
pub struct Above<R: IndicatorRef>

AboveRef struct#

rust · ignore
pub struct AboveRef<R1: IndicatorRef, R2: IndicatorRef>

All struct#

rust · ignore
pub struct All<C: Condition>

And struct#

rust · ignore
pub struct And<C1: Condition, C2: Condition>

Any struct#

rust · ignore
pub struct Any<C: Condition>

Below struct#

rust · ignore
pub struct Below<R: IndicatorRef>

BelowRef struct#

rust · ignore
pub struct BelowRef<R1: IndicatorRef, R2: IndicatorRef>

Between struct#

rust · ignore
pub struct Between<R: IndicatorRef>

Condition trait#

rust · ignore
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#

ignore
use finance_query::backtesting::condition::Condition;

fn my_custom_condition(ctx: &StrategyContext) -> bool {
    // Custom logic here
    true
}

ConditionBuilder struct#

rust · ignore
pub struct ConditionBuilder<C: Condition>

ConstantCondition struct#

rust · ignore
pub struct ConstantCondition(bool)

A condition that always returns the same value.

Useful for testing or as a placeholder.

CrossesAbove struct#

rust · ignore
pub struct CrossesAbove<R: IndicatorRef>

CrossesAboveRef struct#

rust · ignore
pub struct CrossesAboveRef<R1: IndicatorRef, R2: IndicatorRef>

CrossesBelow struct#

rust · ignore
pub struct CrossesBelow<R: IndicatorRef>

CrossesBelowRef struct#

rust · ignore
pub struct CrossesBelowRef<R1: IndicatorRef, R2: IndicatorRef>

Equals struct#

rust · ignore
pub struct Equals<R: IndicatorRef>

HasPosition struct#

rust · ignore
pub struct HasPosition

HeldForBars struct#

rust · ignore
pub struct HeldForBars

HtfIndicatorSpec struct#

rust · ignore
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#

rust · ignore
pub struct InLoss

InProfit struct#

rust · ignore
pub struct InProfit

IsLong struct#

rust · ignore
pub struct IsLong

IsShort struct#

rust · ignore
pub struct IsShort

NoPosition struct#

rust · ignore
pub struct NoPosition

Not struct#

rust · ignore
pub struct Not<C: Condition>

Or struct#

rust · ignore
pub struct Or<C1: Condition, C2: Condition>

StopLoss struct#

rust · ignore
pub struct StopLoss

TakeProfit struct#

rust · ignore
pub struct TakeProfit

TrailingStop struct#

rust · ignore
pub struct TrailingStop

TrailingTakeProfit struct#

rust · ignore
pub struct TrailingTakeProfit

always_false function#

rust · ignore
pub fn always_false() -> ConstantCondition

Convenience function to create a condition that always returns false.

measured as `finance_query::cond_bench_always_false`
instructions/iter250414
callgrind Ir/iter250414
median walltime (ns)25563
p99 walltime (ns)26686
allocations/iter6
allocated bytes/iter24257

always_true function#

rust · ignore
pub fn always_true() -> ConstantCondition

Convenience function to create a condition that always returns true.

measured as `finance_query::cond_bench_always_true`
instructions/iter4333658
callgrind Ir/iter4333658
median walltime (ns)456665
p99 walltime (ns)463122
allocations/iter4045
allocated bytes/iter1710867

has_position function#

rust · ignore
pub fn has_position() -> HasPosition
measured as `finance_query::cond_bench_has_position`
instructions/iter4322665
callgrind Ir/iter4322665
median walltime (ns)462371
p99 walltime (ns)471607
allocations/iter4045
allocated bytes/iter1712862

held_for_bars function#

rust · ignore
pub fn held_for_bars(min_bars: usize) -> HeldForBars
measured as `finance_query::cond_bench_held_for_bars`
instructions/iter1519701
callgrind Ir/iter1519701
median walltime (ns)174947
p99 walltime (ns)176948
allocations/iter1041
allocated bytes/iter458837

in_loss function#

rust · ignore
pub fn in_loss() -> InLoss
measured as `finance_query::cond_bench_in_loss`
instructions/iter4359947
callgrind Ir/iter4359947
median walltime (ns)475252
p99 walltime (ns)486622
allocations/iter4045
allocated bytes/iter1702887

in_profit function#

rust · ignore
pub fn in_profit() -> InProfit
measured as `finance_query::cond_bench_in_profit`
instructions/iter558440
callgrind Ir/iter558440
median walltime (ns)54556
p99 walltime (ns)55352
allocations/iter142
allocated bytes/iter88980

is_long function#

rust · ignore
pub fn is_long() -> IsLong
measured as `finance_query::cond_bench_is_long`
instructions/iter4317905
callgrind Ir/iter4317905
median walltime (ns)469910
p99 walltime (ns)487934
allocations/iter4045
allocated bytes/iter1702887

is_short function#

rust · ignore
pub fn is_short() -> IsShort
measured as `finance_query::cond_bench_is_short`
instructions/iter401363
callgrind Ir/iter401363
median walltime (ns)38472
p99 walltime (ns)39573
allocations/iter13
allocated bytes/iter42860

no_position function#

rust · ignore
pub fn no_position() -> NoPosition
measured as `finance_query::cond_bench_no_position`
instructions/iter401363
callgrind Ir/iter401363
median walltime (ns)38478
p99 walltime (ns)39699
allocations/iter13
allocated bytes/iter42860

stop_loss function#

rust · ignore
pub fn stop_loss(pct: f64) -> StopLoss
measured as `finance_query::cond_bench_stop_loss`
instructions/iter456653
callgrind Ir/iter456653
median walltime (ns)47383
p99 walltime (ns)59930
allocations/iter24
allocated bytes/iter43690

take_profit function#

rust · ignore
pub fn take_profit(pct: f64) -> TakeProfit
measured as `finance_query::cond_bench_take_profit`
instructions/iter443285
callgrind Ir/iter443285
median walltime (ns)45417
p99 walltime (ns)48163
allocations/iter13
allocated bytes/iter42860

trailing_stop function#

rust · ignore
pub fn trailing_stop(trail_pct: f64) -> TrailingStop
measured as `finance_query::cond_bench_trailing_stop`
instructions/iter596793
callgrind Ir/iter596793
median walltime (ns)56597
p99 walltime (ns)59875
allocations/iter92
allocated bytes/iter88644

trailing_take_profit function#

rust · ignore
pub fn trailing_take_profit(trail_pct: f64) -> TrailingTakeProfit
measured as `finance_query::cond_bench_trailing_take_profit`
instructions/iter605815
callgrind Ir/iter605815
median walltime (ns)57490
p99 walltime (ns)60288
allocations/iter72
allocated bytes/iter63588

finance_query::backtesting::config::BacktestConfig#

calculate_position_size function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub fn float_range(start: f64, end: f64, step: f64) -> Self

Stepped float range — compatible with both [GridSearch] and [BayesianSearch].

int_bounds function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub struct AllocationSnapshot

PortfolioConfig struct#

rust · ignore
pub struct PortfolioConfig

PortfolioEngine struct#

rust · ignore
pub struct PortfolioEngine

PortfolioResult struct#

rust · ignore
pub struct PortfolioResult

RebalanceMode enum#

rust · ignore
pub enum RebalanceMode

SymbolData struct#

rust · ignore
pub struct SymbolData

finance_query::backtesting::position::Position#

close function#

rust · ignore
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#

rust · ignore
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#

scale_in function#

rust · ignore
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#

finance_query::backtesting::refs#

AccumulationDistributionRef struct#

rust · ignore
pub struct AccumulationDistributionRef

AdxRef struct#

rust · ignore
pub struct AdxRef

AlmaConfig struct#

rust · ignore
pub struct AlmaConfig

AlmaRef struct#

rust · ignore
pub struct AlmaRef

AroonConfig struct#

rust · ignore
pub struct AroonConfig

AroonDownRef struct#

rust · ignore
pub struct AroonDownRef

AroonUpRef struct#

rust · ignore
pub struct AroonUpRef

AtrRef struct#

rust · ignore
pub struct AtrRef

AwesomeOscillatorRef struct#

rust · ignore
pub struct AwesomeOscillatorRef

BalanceOfPowerRef struct#

rust · ignore
pub struct BalanceOfPowerRef

BearPowerRef struct#

rust · ignore
pub struct BearPowerRef

BollingerConfig struct#

rust · ignore
pub struct BollingerConfig

BollingerLowerRef struct#

rust · ignore
pub struct BollingerLowerRef

BollingerMiddleRef struct#

rust · ignore
pub struct BollingerMiddleRef

BollingerUpperRef struct#

rust · ignore
pub struct BollingerUpperRef

BullPowerRef struct#

rust · ignore
pub struct BullPowerRef

CandleBody struct#

rust · ignore
pub struct CandleBody

CandleRange struct#

rust · ignore
pub struct CandleRange

CciRef struct#

rust · ignore
pub struct CciRef

ChaikinOscillatorRef struct#

rust · ignore
pub struct ChaikinOscillatorRef

ChoppinessIndexRef struct#

rust · ignore
pub struct ChoppinessIndexRef

ClosePrice struct#

rust · ignore
pub struct ClosePrice

CmfRef struct#

rust · ignore
pub struct CmfRef

CmoRef struct#

rust · ignore
pub struct CmoRef

CoppockCurveRef struct#

rust · ignore
pub struct CoppockCurveRef

DemaRef struct#

rust · ignore
pub struct DemaRef

DonchianConfig struct#

rust · ignore
pub struct DonchianConfig

DonchianLowerRef struct#

rust · ignore
pub struct DonchianLowerRef

DonchianMiddleRef struct#

rust · ignore
pub struct DonchianMiddleRef

DonchianUpperRef struct#

rust · ignore
pub struct DonchianUpperRef

ElderBearPowerRef struct#

rust · ignore
pub struct ElderBearPowerRef

ElderBullPowerRef struct#

rust · ignore
pub struct ElderBullPowerRef

EmaRef struct#

rust · ignore
pub struct EmaRef

GapPct struct#

rust · ignore
pub struct GapPct

HighPrice struct#

rust · ignore
pub struct HighPrice

HmaRef struct#

rust · ignore
pub struct HmaRef

HtfCondition struct#

rust · ignore
pub struct HtfCondition<C: Condition>

IchimokuBaseRef struct#

rust · ignore
pub struct IchimokuBaseRef

IchimokuConfig struct#

rust · ignore
pub struct IchimokuConfig

IchimokuConversionRef struct#

rust · ignore
pub struct IchimokuConversionRef

IchimokuLaggingRef struct#

rust · ignore
pub struct IchimokuLaggingRef

IchimokuLeadingARef struct#

rust · ignore
pub struct IchimokuLeadingARef

IchimokuLeadingBRef struct#

rust · ignore
pub struct IchimokuLeadingBRef

IndicatorRef trait#

rust · ignore
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:

Implementing Custom References#

ignore
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#

rust · ignore
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#

ignore
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#

rust · ignore
pub struct IsBearish

IsBullish struct#

rust · ignore
pub struct IsBullish

KeltnerConfig struct#

rust · ignore
pub struct KeltnerConfig

KeltnerLowerRef struct#

rust · ignore
pub struct KeltnerLowerRef

KeltnerMiddleRef struct#

rust · ignore
pub struct KeltnerMiddleRef

KeltnerUpperRef struct#

rust · ignore
pub struct KeltnerUpperRef

LowPrice struct#

rust · ignore
pub struct LowPrice

MacdConfig struct#

rust · ignore
pub struct MacdConfig

MacdHistogramRef struct#

rust · ignore
pub struct MacdHistogramRef

MacdLineRef struct#

rust · ignore
pub struct MacdLineRef

MacdSignalRef struct#

rust · ignore
pub struct MacdSignalRef

McginleyDynamicRef struct#

rust · ignore
pub struct McginleyDynamicRef

MedianPrice struct#

rust · ignore
pub struct MedianPrice

MfiRef struct#

rust · ignore
pub struct MfiRef

MomentumRef struct#

rust · ignore
pub struct MomentumRef

ObvRef struct#

rust · ignore
pub struct ObvRef

OpenPrice struct#

rust · ignore
pub struct OpenPrice

ParabolicSarConfig struct#

rust · ignore
pub struct ParabolicSarConfig

ParabolicSarRef struct#

rust · ignore
pub struct ParabolicSarRef

PriceChangePct struct#

rust · ignore
pub struct PriceChangePct

RelativeVolume struct#

rust · ignore
pub struct RelativeVolume

RocRef struct#

rust · ignore
pub struct RocRef

RsiRef struct#

rust · ignore
pub struct RsiRef

SmaRef struct#

rust · ignore
pub struct SmaRef

StochasticConfig struct#

rust · ignore
pub struct StochasticConfig

StochasticDRef struct#

rust · ignore
pub struct StochasticDRef

StochasticKRef struct#

rust · ignore
pub struct StochasticKRef

StochasticRsiConfig struct#

rust · ignore
pub struct StochasticRsiConfig

StochasticRsiDRef struct#

rust · ignore
pub struct StochasticRsiDRef

StochasticRsiRef struct#

rust · ignore
pub struct StochasticRsiRef

SupertrendConfig struct#

rust · ignore
pub struct SupertrendConfig

SupertrendUptrendRef struct#

rust · ignore
pub struct SupertrendUptrendRef

SupertrendValueRef struct#

rust · ignore
pub struct SupertrendValueRef

TemaRef struct#

rust · ignore
pub struct TemaRef

TrueRangeRef struct#

rust · ignore
pub struct TrueRangeRef

TypicalPrice struct#

rust · ignore
pub struct TypicalPrice

VolumeRef struct#

rust · ignore
pub struct VolumeRef

VwapRef struct#

rust · ignore
pub struct VwapRef

VwmaRef struct#

rust · ignore
pub struct VwmaRef

WilliamsRRef struct#

rust · ignore
pub struct WilliamsRRef

WmaRef struct#

rust · ignore
pub struct WmaRef

accumulation_distribution function#

rust · ignore
pub fn accumulation_distribution() -> AccumulationDistributionRef
measured as `finance_query::ref_bench_accumulation_distribution`
instructions/iter575870
callgrind Ir/iter575870
median walltime (ns)53046
p99 walltime (ns)53510
allocations/iter23
allocated bytes/iter73469

adx function#

rust · ignore
pub fn adx(period: usize) -> AdxRef
measured as `finance_query::ref_bench_adx`
instructions/iter5311496
callgrind Ir/iter5311496
median walltime (ns)553228
p99 walltime (ns)562752
allocations/iter4930
allocated bytes/iter1765123

alma function#

rust · ignore
pub fn alma(period: usize, offset: f64, sigma: f64) -> AlmaRef
measured as `finance_query::ref_bench_alma`
instructions/iter5899254
callgrind Ir/iter5899254
median walltime (ns)588530
p99 walltime (ns)614224
allocations/iter5019
allocated bytes/iter1772359

aroon function#

rust · ignore
pub fn aroon(period: usize) -> AroonConfig
measured as `finance_query::ref_bench_aroon`
instructions/iter5641623
callgrind Ir/iter5641623
median walltime (ns)553772
p99 walltime (ns)576546
allocations/iter4950
allocated bytes/iter1795683

atr function#

rust · ignore
pub fn atr(period: usize) -> AtrRef
measured as `finance_query::ref_bench_atr`
instructions/iter5548467
callgrind Ir/iter5548467
median walltime (ns)553862
p99 walltime (ns)575704
allocations/iter4996
allocated bytes/iter1773994

awesome_oscillator function#

rust · ignore
pub fn awesome_oscillator(fast: usize, slow: usize) -> AwesomeOscillatorRef
measured as `finance_query::ref_bench_awesome_oscillator`
instructions/iter3090697
callgrind Ir/iter3090697
median walltime (ns)340680
p99 walltime (ns)343994
allocations/iter2636
allocated bytes/iter1742627

balance_of_power function#

rust · ignore
pub fn balance_of_power(period: Option<usize>) -> BalanceOfPowerRef
measured as `finance_query::ref_bench_balance_of_power`
instructions/iter574481
callgrind Ir/iter574481
median walltime (ns)54094
p99 walltime (ns)55847
allocations/iter25
allocated bytes/iter81476

bear_power function#

rust · ignore
pub fn bear_power(period: usize) -> BearPowerRef
measured as `finance_query::ref_bench_bear_power`
instructions/iter1539698
callgrind Ir/iter1539698
median walltime (ns)150849
p99 walltime (ns)153323
allocations/iter806
allocated bytes/iter516030

bollinger function#

rust · ignore
pub fn bollinger(period: usize, std_dev: f64) -> BollingerConfig
measured as `finance_query::ref_bench_bollinger`
instructions/iter6100701
callgrind Ir/iter6100701
median walltime (ns)583279
p99 walltime (ns)622607
allocations/iter4968
allocated bytes/iter1834706

bull_power function#

rust · ignore
pub fn bull_power(period: usize) -> BullPowerRef
measured as `finance_query::ref_bench_bull_power`
instructions/iter5302891
callgrind Ir/iter5302891
median walltime (ns)509924
p99 walltime (ns)533816
allocations/iter4238
allocated bytes/iter1792914

candle_body function#

rust · ignore
pub fn candle_body() -> CandleBody
measured as `finance_query::ref_bench_candle_body`
instructions/iter254396
callgrind Ir/iter254396
median walltime (ns)25024
p99 walltime (ns)25743
allocations/iter6
allocated bytes/iter24257

candle_range function#

rust · ignore
pub fn candle_range() -> CandleRange
measured as `finance_query::ref_bench_candle_range`
instructions/iter5165265
callgrind Ir/iter5165265
median walltime (ns)538944
p99 walltime (ns)556226
allocations/iter5043
allocated bytes/iter1743801

cci function#

rust · ignore
pub fn cci(period: usize) -> CciRef
measured as `finance_query::ref_bench_cci`
instructions/iter3255675
callgrind Ir/iter3255675
median walltime (ns)331121
p99 walltime (ns)337072
allocations/iter2605
allocated bytes/iter927343

chaikin_oscillator function#

rust · ignore
pub fn chaikin_oscillator() -> ChaikinOscillatorRef
measured as `finance_query::ref_bench_chaikin_oscillator`
instructions/iter646841
callgrind Ir/iter646841
median walltime (ns)71819
p99 walltime (ns)72336
allocations/iter26
allocated bytes/iter97417

choppiness_index function#

rust · ignore
pub fn choppiness_index(period: usize) -> ChoppinessIndexRef
measured as `finance_query::ref_bench_choppiness_index`
instructions/iter5819354
callgrind Ir/iter5819354
median walltime (ns)567759
p99 walltime (ns)596421
allocations/iter5002
allocated bytes/iter1767649

close function#

rust · ignore
pub fn close() -> ClosePrice
measured as `finance_query::ref_bench_close`
instructions/iter5190098
callgrind Ir/iter5190098
median walltime (ns)525364
p99 walltime (ns)531700
allocations/iter5043
allocated bytes/iter1724839

cmf function#

rust · ignore
pub fn cmf(period: usize) -> CmfRef
measured as `finance_query::ref_bench_cmf`
instructions/iter589599
callgrind Ir/iter589599
median walltime (ns)54396
p99 walltime (ns)55323
allocations/iter25
allocated bytes/iter81493

cmo function#

rust · ignore
pub fn cmo(period: usize) -> CmoRef
measured as `finance_query::ref_bench_cmo`
instructions/iter3082622
callgrind Ir/iter3082622
median walltime (ns)315547
p99 walltime (ns)321994
allocations/iter2598
allocated bytes/iter911276

coppock_curve function#

rust · ignore
pub fn coppock_curve(wma_period: usize, long_roc: usize, short_roc: usize) -> CoppockCurveRef
measured as `finance_query::ref_bench_coppock_curve`
instructions/iter3343042
callgrind Ir/iter3343042
median walltime (ns)331602
p99 walltime (ns)350899
allocations/iter2559
allocated bytes/iter935478

dema function#

rust · ignore
pub fn dema(period: usize) -> DemaRef
measured as `finance_query::ref_bench_dema`
instructions/iter5497724
callgrind Ir/iter5497724
median walltime (ns)544528
p99 walltime (ns)555882
allocations/iter4875
allocated bytes/iter1764809

donchian function#

rust · ignore
pub fn donchian(period: usize) -> DonchianConfig
measured as `finance_query::ref_bench_donchian`
instructions/iter5998096
callgrind Ir/iter5998096
median walltime (ns)591728
p99 walltime (ns)622573
allocations/iter4976
allocated bytes/iter1839378

elder_bear_power function#

rust · ignore
pub fn elder_bear_power(period: usize) -> ElderBearPowerRef
measured as `finance_query::ref_bench_elder_bear_power`
instructions/iter1538369
callgrind Ir/iter1538369
median walltime (ns)150595
p99 walltime (ns)153061
allocations/iter806
allocated bytes/iter516030

elder_bull_power function#

rust · ignore
pub fn elder_bull_power(period: usize) -> ElderBullPowerRef
measured as `finance_query::ref_bench_elder_bull_power`
instructions/iter5215197
callgrind Ir/iter5215197
median walltime (ns)511797
p99 walltime (ns)519779
allocations/iter4238
allocated bytes/iter1792914

ema function#

rust · ignore
pub fn ema(period: usize) -> EmaRef
measured as `finance_query::ref_bench_ema`
instructions/iter5398604
callgrind Ir/iter5398604
median walltime (ns)543944
p99 walltime (ns)595737
allocations/iter4963
allocated bytes/iter1749648

gap_pct function#

rust · ignore
pub fn gap_pct() -> GapPct
measured as `finance_query::ref_bench_gap_pct`
instructions/iter2496162
callgrind Ir/iter2496162
median walltime (ns)274995
p99 walltime (ns)280154
allocations/iter2489
allocated bytes/iter877279

high function#

rust · ignore
pub fn high() -> HighPrice
measured as `finance_query::ref_bench_high`
instructions/iter5191089
callgrind Ir/iter5191089
median walltime (ns)533569
p99 walltime (ns)539668
allocations/iter5043
allocated bytes/iter1723841

hma function#

rust · ignore
pub fn hma(period: usize) -> HmaRef
measured as `finance_query::ref_bench_hma`
instructions/iter5408150
callgrind Ir/iter5408150
median walltime (ns)554333
p99 walltime (ns)563797
allocations/iter4957
allocated bytes/iter1780946

htf function#

rust · ignore
pub fn htf<C: Condition>(interval: Interval, cond: C) -> HtfCondition<C>
measured as `finance_query::ref_bench_htf`
instructions/iter6531233
callgrind Ir/iter6531233
median walltime (ns)617456
p99 walltime (ns)645778
allocations/iter7039
allocated bytes/iter1776735

htf_region function#

rust · ignore
pub fn htf_region<C: Condition>(interval: Interval, region: Region, cond: C) -> HtfCondition<C>
measured as `finance_query::ref_bench_htf_region`
instructions/iter6423198
callgrind Ir/iter6423198
median walltime (ns)618801
p99 walltime (ns)654383
allocations/iter7039
allocated bytes/iter1776735

ichimoku function#

rust · ignore
pub fn ichimoku() -> IchimokuConfig
measured as `finance_query::ref_bench_ichimoku`
instructions/iter6249018
callgrind Ir/iter6249018
median walltime (ns)615440
p99 walltime (ns)630041
allocations/iter4836
allocated bytes/iter1915384

ichimoku_custom function#

rust · ignore
pub fn ichimoku_custom( conversion: usize, base: usize, lagging: usize, displacement: usize, ) -> IchimokuConfig
measured as `finance_query::ref_bench_ichimoku_custom`
instructions/iter6264656
callgrind Ir/iter6264656
median walltime (ns)617596
p99 walltime (ns)629337
allocations/iter4836
allocated bytes/iter1915384

is_bearish function#

rust · ignore
pub fn is_bearish() -> IsBearish
measured as `finance_query::ref_bench_is_bearish`
instructions/iter255395
callgrind Ir/iter255395
median walltime (ns)24550
p99 walltime (ns)25288
allocations/iter6
allocated bytes/iter24257

is_bullish function#

rust · ignore
pub fn is_bullish() -> IsBullish
measured as `finance_query::ref_bench_is_bullish`
instructions/iter255395
callgrind Ir/iter255395
median walltime (ns)24716
p99 walltime (ns)25047
allocations/iter6
allocated bytes/iter24257

keltner function#

rust · ignore
pub fn keltner(period: usize, multiplier: f64, atr_period: usize) -> KeltnerConfig
measured as `finance_query::ref_bench_keltner`
instructions/iter5838002
callgrind Ir/iter5838002
median walltime (ns)599830
p99 walltime (ns)608573
allocations/iter4972
allocated bytes/iter1870394

low function#

rust · ignore
pub fn low() -> LowPrice
measured as `finance_query::ref_bench_low`
instructions/iter5194083
callgrind Ir/iter5194083
median walltime (ns)535315
p99 walltime (ns)554920
allocations/iter5043
allocated bytes/iter1722843

macd function#

rust · ignore
pub fn macd(fast: usize, slow: usize, signal: usize) -> MacdConfig
measured as `finance_query::ref_bench_macd`
instructions/iter3302016
callgrind Ir/iter3302016
median walltime (ns)343304
p99 walltime (ns)356895
allocations/iter2541
allocated bytes/iter984571

mcginley function#

rust · ignore
pub fn mcginley(period: usize) -> McginleyDynamicRef
measured as `finance_query::ref_bench_mcginley`
instructions/iter5513907
callgrind Ir/iter5513907
median walltime (ns)555197
p99 walltime (ns)578826
allocations/iter4963
allocated bytes/iter1763384

median_price function#

rust · ignore
pub fn median_price() -> MedianPrice
measured as `finance_query::ref_bench_median_price`
instructions/iter5166263
callgrind Ir/iter5166263
median walltime (ns)539822
p99 walltime (ns)549612
allocations/iter5043
allocated bytes/iter1743801

mfi function#

rust · ignore
pub fn mfi(period: usize) -> MfiRef
measured as `finance_query::ref_bench_mfi`
instructions/iter5599568
callgrind Ir/iter5599568
median walltime (ns)551909
p99 walltime (ns)564441
allocations/iter4998
allocated bytes/iter1790098

momentum function#

rust · ignore
pub fn momentum(period: usize) -> MomentumRef
measured as `finance_query::ref_bench_momentum`
instructions/iter3106471
callgrind Ir/iter3106471
median walltime (ns)310764
p99 walltime (ns)328920
allocations/iter2552
allocated bytes/iter909675

obv function#

rust · ignore
pub fn obv() -> ObvRef
measured as `finance_query::ref_bench_obv`
instructions/iter633638
callgrind Ir/iter633638
median walltime (ns)64535
p99 walltime (ns)65708
allocations/iter30
allocated bytes/iter76095

open function#

rust · ignore
pub fn open() -> OpenPrice
measured as `finance_query::ref_bench_open`
instructions/iter5191089
callgrind Ir/iter5191089
median walltime (ns)534454
p99 walltime (ns)551522
allocations/iter5043
allocated bytes/iter1723841

parabolic_sar function#

rust · ignore
pub fn parabolic_sar(step: f64, max: f64) -> ParabolicSarRef
measured as `finance_query::ref_bench_parabolic_sar`
instructions/iter5848182
callgrind Ir/iter5848182
median walltime (ns)592963
p99 walltime (ns)949809
allocations/iter5056
allocated bytes/iter1788988

price function#

rust · ignore
pub fn price() -> ClosePrice
measured as `finance_query::ref_bench_price`
instructions/iter5190098
callgrind Ir/iter5190098
median walltime (ns)525384
p99 walltime (ns)569115
allocations/iter5043
allocated bytes/iter1724839

price_change_pct function#

rust · ignore
pub fn price_change_pct() -> PriceChangePct
measured as `finance_query::ref_bench_price_change_pct`
instructions/iter2916805
callgrind Ir/iter2916805
median walltime (ns)296725
p99 walltime (ns)305181
allocations/iter2489
allocated bytes/iter893407

relative_volume function#

rust · ignore
pub fn relative_volume(period: usize) -> RelativeVolume
measured as `finance_query::ref_bench_relative_volume`
instructions/iter5672898
callgrind Ir/iter5672898
median walltime (ns)559714
p99 walltime (ns)576469
allocations/iter4949
allocated bytes/iter1765562

roc function#

rust · ignore
pub fn roc(period: usize) -> RocRef
measured as `finance_query::ref_bench_roc`
instructions/iter2913686
callgrind Ir/iter2913686
median walltime (ns)309840
p99 walltime (ns)313211
allocations/iter2587
allocated bytes/iter903142

rsi function#

rust · ignore
pub fn rsi(period: usize) -> RsiRef
measured as `finance_query::ref_bench_rsi`
instructions/iter5544097
callgrind Ir/iter5544097
median walltime (ns)550360
p99 walltime (ns)576315
allocations/iter4994
allocated bytes/iter1757986

sma function#

rust · ignore
pub fn sma(period: usize) -> SmaRef
measured as `finance_query::ref_bench_sma`
instructions/iter5402520
callgrind Ir/iter5402520
median walltime (ns)544952
p99 walltime (ns)565329
allocations/iter4963
allocated bytes/iter1749648

stochastic function#

rust · ignore
pub fn stochastic(k_period: usize, k_slow: usize, d_period: usize) -> StochasticConfig
measured as `finance_query::ref_bench_stochastic`
instructions/iter6151709
callgrind Ir/iter6151709
median walltime (ns)602594
p99 walltime (ns)616625
allocations/iter4987
allocated bytes/iter1851282

stochastic_rsi function#

rust · ignore
pub fn stochastic_rsi( rsi_period: usize, stoch_period: usize, k_period: usize, d_period: usize, ) -> StochasticRsiConfig
measured as `finance_query::ref_bench_stochastic_rsi`
instructions/iter6005086
callgrind Ir/iter6005086
median walltime (ns)589622
p99 walltime (ns)605598
allocations/iter4831
allocated bytes/iter1846555

supertrend function#

rust · ignore
pub fn supertrend(period: usize, multiplier: f64) -> SupertrendConfig
measured as `finance_query::ref_bench_supertrend`
instructions/iter6007194
callgrind Ir/iter6007194
median walltime (ns)601412
p99 walltime (ns)632561
allocations/iter5021
allocated bytes/iter1860896

tema function#

rust · ignore
pub fn tema(period: usize) -> TemaRef
measured as `finance_query::ref_bench_tema`
instructions/iter5404246
callgrind Ir/iter5404246
median walltime (ns)539775
p99 walltime (ns)547853
allocations/iter4781
allocated bytes/iter1770909

true_range function#

rust · ignore
pub fn true_range() -> TrueRangeRef
measured as `finance_query::ref_bench_true_range`
instructions/iter5341934
callgrind Ir/iter5341934
median walltime (ns)563436
p99 walltime (ns)598414
allocations/iter5059
allocated bytes/iter1777061

typical_price function#

rust · ignore
pub fn typical_price() -> TypicalPrice
measured as `finance_query::ref_bench_typical_price`
instructions/iter5607537
callgrind Ir/iter5607537
median walltime (ns)559574
p99 walltime (ns)582157
allocations/iter5043
allocated bytes/iter1747793

volume function#

rust · ignore
pub fn volume() -> VolumeRef
measured as `finance_query::ref_bench_volume`
instructions/iter5191089
callgrind Ir/iter5191089
median walltime (ns)531075
p99 walltime (ns)562795
allocations/iter5043
allocated bytes/iter1725837

vwap function#

rust · ignore
pub fn vwap() -> VwapRef
measured as `finance_query::ref_bench_vwap`
instructions/iter5632132
callgrind Ir/iter5632132
median walltime (ns)569088
p99 walltime (ns)580862
allocations/iter5060
allocated bytes/iter1773061

vwma function#

rust · ignore
pub fn vwma(period: usize) -> VwmaRef
measured as `finance_query::ref_bench_vwma`
instructions/iter5367656
callgrind Ir/iter5367656
median walltime (ns)543834
p99 walltime (ns)570366
allocations/iter4964
allocated bytes/iter1758633

williams_r function#

rust · ignore
pub fn williams_r(period: usize) -> WilliamsRRef
measured as `finance_query::ref_bench_williams_r`
instructions/iter748884
callgrind Ir/iter748884
median walltime (ns)64525
p99 walltime (ns)67468
allocations/iter29
allocated bytes/iter65983

wma function#

rust · ignore
pub fn wma(period: usize) -> WmaRef
measured as `finance_query::ref_bench_wma`
instructions/iter5488240
callgrind Ir/iter5488240
median walltime (ns)541374
p99 walltime (ns)554002
allocations/iter4969
allocated bytes/iter1772256

finance_query::backtesting::refs::oscillators::StochasticRsiConfig#

d function#

rust · ignore
pub fn d(&self) -> StochasticRsiDRef

Reference to the %D signal line (SMA of %K).

k function#

rust · ignore
pub fn k(&self) -> StochasticRsiRef

Reference to the smoothed %K line.

finance_query::backtesting::resample#

base_to_htf_index function#

rust · ignore
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).

verified claims
complexityclaimed O(n); growth drift x1.29 over sizes [1024, 4096, 16384] (limit x2.5)
measured as `finance_query::bt_base_to_htf_index`
instructions/iter321100
callgrind Ir/iter321100
median walltime (ns)26783
p99 walltime (ns)27573
allocations/iter1
allocated bytes/iter262144

resample function#

rust · ignore
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#

verified claims
complexityclaimed O(n); growth drift x0.96 over sizes [1024, 4096, 16384] (limit x2.5)
measured as `finance_query::bt_resample`
instructions/iter1451621
callgrind Ir/iter1451621
median walltime (ns)111793
p99 walltime (ns)114173
allocations/iter11
allocated bytes/iter589536

finance_query::backtesting::result::BacktestResult#

by_day_of_week function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

finance_query::backtesting::result::metrics::PerformanceMetrics#

max_drawdown_percentage function#

rust · ignore
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#

rust · ignore
pub fn exit(timestamp: i64, price: f64) -> Self

Create an exit signal

scale_in function#

rust · ignore
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#

rust,no_run
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#

rust · ignore
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#

rust,no_run
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#

rust · ignore
pub struct CustomStrategy<E: Condition, X: Condition>

finance_query::backtesting::strategy::StrategyContext#

crossed_above function#

rust · ignore
pub fn crossed_above(&self, fast_name: &str, slow_name: &str) -> bool

Check if crossover occurred (fast crosses above slow)

indicator function#

rust · ignore
pub fn indicator(&self, name: &str) -> Option<f64>

Get indicator value at current index

indicator_crossed_above function#

rust · ignore
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#

rust · ignore
pub fn indicator_prev(&self, name: &str) -> Option<f64>

Get indicator value at previous index

finance_query::backtesting::strategy::builder::StrategyBuilder#

regime_filter function#

rust · ignore
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#

rust,no_run
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#

rust · ignore
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#

rust · ignore
pub fn build(self) -> Self

Finalise the ensemble. Returns self (all configuration happens in the builder methods).

mode function#

rust · ignore
pub fn mode(mut self, mode: EnsembleMode) -> Self

Set the voting mode.

finance_query::backtesting::walk_forward::WalkForwardConfig#

new function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub async fn fetch_commitments_of_traders_response(symbol: &str) -> Result<CommitmentsOfTraders>

finance_query::constants::enums::interval::Interval#

as_str function#

rust · ignore
pub fn as_str(&self) -> &'static str

Convert interval to Yahoo Finance API format

finance_query::constants::enums::region::Region#

utc_offset_secs function#

rust · ignore
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#

rust · ignore
pub fn as_str(&self) -> &'static str

Convert time range to Yahoo Finance API format

default_interval function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub struct CoinQuote
measured as `finance_query::de_crypto_coins`
instructions/iter352875
callgrind Ir/iter352875
median walltime (ns)32826
p99 walltime (ns)33704
allocations/iter205
allocated bytes/iter28185

GlobalCryptoStats struct#

rust · ignore
pub struct GlobalCryptoStats

TrendingCoin struct#

rust · ignore
pub struct TrendingCoin

coin function#

rust · ignore
pub async fn coin(id: &str, vs_currency: &str) -> Result<CoinQuote>

coins function#

rust · ignore
pub async fn coins(vs_currency: &str, count: usize) -> Result<Vec<CoinQuote>>

global function#

rust · ignore
pub async fn fetch_crypto_global_response() -> Result<crate::models::crypto::GlobalCryptoStats>

search function#

rust · ignore
pub async fn fetch_symbol_search_response(query: &str, limit: u32) -> Result<Vec<SymbolMatch>>
rust · ignore
pub async fn fetch_crypto_trending_response() -> Result<Vec<crate::models::crypto::TrendingCoin>>

finance_query::defi#

ChainAllocation struct#

rust · ignore
pub struct ChainAllocation

ChainTvl struct#

rust · ignore
pub struct ChainTvl

ProtocolTvl struct#

rust · ignore
pub struct ProtocolTvl

StablecoinSupply struct#

rust · ignore
pub struct StablecoinSupply

TvlPoint struct#

rust · ignore
pub struct TvlPoint

chains function#

rust · ignore
pub async fn chains() -> Result<Vec<ChainTvl>>

Fetch aggregate total value locked for every chain, largest first.

stablecoins function#

rust · ignore
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#

rust · ignore
pub async fn quote(&self) -> Result<crate::models::commodities::CommodityQuote>

Fetch the current quote for this commodity.

finance_query::domains::crypto::CryptoCoin#

quote function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub async fn get(&self) -> Result<crate::models::filings::ProviderFilings>

Fetch SEC filings for this symbol.

search_all function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub async fn crypto_global(&self) -> Result<crate::models::crypto::GlobalCryptoStats>

Fetch aggregate global cryptocurrency market statistics.

Routes through Capability::CRYPTO. Currently CoinGecko only.

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub async fn company_facts(cik: u64) -> Result<CompanyFacts>

filing_index function#

rust · ignore
pub async fn filing_index(accession_number: &str) -> Result<EdgarFilingIndex>

init function#

rust · ignore
pub fn init(email: impl Into<String>) -> Result<()>

init_with_config function#

rust · ignore
pub fn init_with_config( email: impl Into<String>, app_name: impl Into<String>, timeout: Duration, ) -> Result<()>

resolve_cik function#

rust · ignore
pub async fn resolve_cik(symbol: &str) -> Result<u64>

search function#

rust · ignore
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#

rust · ignore
pub async fn submissions(cik: u64) -> Result<EdgarSubmissions>

finance_query::feeds#

FeedEntry struct#

rust · ignore
pub struct FeedEntry

A single entry from an RSS/Atom feed.

FeedSource enum#

rust · ignore
pub enum FeedSource

A named or custom RSS/Atom feed source.

fetch function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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.

measured as `finance_query::rss_parse`
instructions/iter64879
callgrind Ir/iter64879
median walltime (ns)5158
p99 walltime (ns)5517
allocations/iter48
allocated bytes/iter3714

finance_query::feeds::FeedSource#

url function#

rust · ignore
pub fn url(&self) -> String

Return the URL for this feed source.

finance_query::finance#

currencies function#

rust · ignore
pub async fn currencies() -> Result<Vec<crate::models::market::currencies::Currency>>

Get list of available currencies

Returns currency information from Yahoo Finance.

Examples#

no_run
use finance_query::finance;

# async fn example() -> Result<(), Box<dyn std::error::Error>> {
let currencies = finance::currencies().await?;
# Ok(())
# }

custom_screener function#

rust · ignore
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#

Examples#

no_run
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#

rust · ignore
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:

  1. Gets the company ID (quartrId) from the quote_type endpoint
  2. Scrapes available earnings calls
  3. Fetches the requested transcript

Arguments#

Examples#

no_run
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#

rust · ignore
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#

Examples#

no_run
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#

rust · ignore
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#

no_run
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#

rust · ignore
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#

no_run
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#

rust · ignore
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#

Examples#

no_run
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#

rust · ignore
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#

Examples#

no_run
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#

rust · ignore
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#

Examples#

no_run
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#

rust · ignore
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#

Examples#

no_run
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#

rust · ignore
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#

Examples#

no_run
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#

rust · ignore
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#

Examples#

no_run
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#

rust · ignore
pub async fn news() -> Result<Vec<crate::models::corporate::news::News>>

Get general market news

Examples#

no_run
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#

rust · ignore
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#

Examples#

no_run
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#

rust · ignore
pub async fn search(query: &str, options: &SearchOptions) -> Result<SearchResults>

Search for stock symbols and companies

Arguments#

Examples#

no_run
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#

rust · ignore
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#

Examples#

no_run
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(())
# }
rust · ignore
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#

Examples#

no_run
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#

rust · ignore
pub fn init(api_key: impl Into<String>) -> Result<()>

init_with_timeout function#

rust · ignore
pub fn init_with_timeout(api_key: impl Into<String>, timeout: Duration) -> Result<()>

finance_query::format#

Both struct#

rust · ignore
pub struct Both

Pretty struct#

rust · ignore
pub struct Pretty

Raw struct#

rust · ignore
pub struct Raw

finance_query::fred#

MacroObservation struct#

rust · ignore
pub struct MacroObservation

MacroSeries struct#

rust · ignore
pub struct MacroSeries
measured as `finance_query::de_fred_series`
instructions/iter1061290
callgrind Ir/iter1061290
median walltime (ns)109640
p99 walltime (ns)111544
allocations/iter873
allocated bytes/iter90398

ReleaseDate struct#

rust · ignore
pub struct ReleaseDate

TreasuryYield struct#

rust · ignore
pub struct TreasuryYield
measured as `finance_query::de_treasury_yields`
instructions/iter779612
callgrind Ir/iter779612
median walltime (ns)82423
p99 walltime (ns)84758
allocations/iter119
allocated bytes/iter59594

release_dates function#

rust · ignore
pub async fn release_dates() -> Result<Vec<ReleaseDate>>

series function#

rust · ignore
pub async fn series(series_id: &str) -> Result<MacroSeries>

treasury_yields function#

rust · ignore
pub async fn treasury_yields(year: u32) -> Result<Vec<TreasuryYield>>

finance_query::gdelt#

news function#

rust · ignore
pub async fn fetch_news_response(symbol: &str) -> Result<Vec<News>>

finance_query::indicators#

AroonResult struct#

rust · ignore
pub struct AroonResult

DonchianChannelsResult struct#

rust · ignore
pub struct DonchianChannelsResult

ElderRayResult struct#

rust · ignore
pub struct BullBearPowerResult

FibonacciLevels struct#

rust · ignore
pub struct FibonacciLevels

IchimokuResult struct#

rust · ignore
pub struct IchimokuResult

KeltnerChannelsResult struct#

rust · ignore
pub struct KeltnerChannelsResult

PivotPoints struct#

rust · ignore
pub struct PivotPoints

Result type_alias#

rust · ignore
pub type Result<T> = std::result::Result<T, IndicatorError>

Result type for indicator calculations

StochasticResult struct#

rust · ignore
pub struct StochasticResult

SuperTrendResult struct#

rust · ignore
pub struct SuperTrendResult

ZigZagPoint struct#

rust · ignore
pub struct ZigZagPoint

accumulation_distribution function#

rust · ignore
pub fn accumulation_distribution( highs: &[f64], lows: &[f64], closes: &[f64], volumes: &[f64], ) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_accumulation_distribution`
instructions/iter27672
callgrind Ir/iter27672
median walltime (ns)4327
p99 walltime (ns)4508
allocations/iter1
allocated bytes/iter16000

adx function#

rust · ignore
pub fn adx(highs: &[f64], lows: &[f64], closes: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_trend`
instructions/iter1045401
callgrind Ir/iter1045401
median walltime (ns)91847
p99 walltime (ns)95229
allocations/iter48
allocated bytes/iter267808

alma function#

rust · ignore
pub fn alma(data: &[f64], period: usize, offset: f64, sigma: f64) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_alma`
instructions/iter107851
callgrind Ir/iter107851
median walltime (ns)6945
p99 walltime (ns)7251
allocations/iter2
allocated bytes/iter16072

aroon function#

rust · ignore
pub fn aroon(highs: &[f64], lows: &[f64], period: usize) -> Result<AroonResult>
measured as `finance_query::ind_aroon`
instructions/iter194710
callgrind Ir/iter194710
median walltime (ns)12158
p99 walltime (ns)12503
allocations/iter9
allocated bytes/iter32704

awesome_oscillator function#

rust · ignore
pub fn awesome_oscillator( highs: &[f64], lows: &[f64], fast: usize, slow: usize, ) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_awesome_oscillator`
instructions/iter52496
callgrind Ir/iter52496
median walltime (ns)9492
p99 walltime (ns)9580
allocations/iter4
allocated bytes/iter39704

balance_of_power function#

rust · ignore
pub fn balance_of_power( opens: &[f64], highs: &[f64], lows: &[f64], closes: &[f64], period: Option<usize>, ) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_balance_of_power`
instructions/iter23362
callgrind Ir/iter23362
median walltime (ns)2223
p99 walltime (ns)2249
allocations/iter2
allocated bytes/iter24000

bollinger_bands function#

rust · ignore
pub fn bollinger_bands( data: &[f64], period: usize, std_dev_multiplier: f64, ) -> Result<BollingerBands>
measured as `finance_query::ind_volatility`
instructions/iter675327
callgrind Ir/iter675327
median walltime (ns)71026
p99 walltime (ns)72616
allocations/iter28
allocated bytes/iter216680

bull_bear_power function#

rust · ignore
pub fn bull_bear_power( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, ) -> Result<BullBearPowerResult>
measured as `finance_query::ind_bull_bear_power`
instructions/iter29581
callgrind Ir/iter29581
median walltime (ns)7785
p99 walltime (ns)7945
allocations/iter3
allocated bytes/iter39904

cci function#

rust · ignore
pub fn cci(highs: &[f64], lows: &[f64], closes: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_cci`
instructions/iter149203
callgrind Ir/iter149203
median walltime (ns)18409
p99 walltime (ns)18641
allocations/iter2
allocated bytes/iter24000

chaikin_oscillator function#

rust · ignore
pub fn chaikin_oscillator( highs: &[f64], lows: &[f64], closes: &[f64], volumes: &[f64], ) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_chaikin_oscillator`
instructions/iter66908
callgrind Ir/iter66908
median walltime (ns)17973
p99 walltime (ns)18061
allocations/iter4
allocated bytes/iter39912

choppiness_index function#

rust · ignore
pub fn choppiness_index( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, ) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_choppiness_index`
instructions/iter281356
callgrind Ir/iter281356
median walltime (ns)21556
p99 walltime (ns)21968
allocations/iter8
allocated bytes/iter16560

cmf function#

rust · ignore
pub fn cmf( highs: &[f64], lows: &[f64], closes: &[f64], volumes: &[f64], period: usize, ) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_cmf`
instructions/iter50390
callgrind Ir/iter50390
median walltime (ns)4146
p99 walltime (ns)4196
allocations/iter2
allocated bytes/iter24000

cmo function#

rust · ignore
pub fn cmo(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_cmo`
instructions/iter61742
callgrind Ir/iter61742
median walltime (ns)5775
p99 walltime (ns)5864
allocations/iter2
allocated bytes/iter24000

coppock_curve function#

rust · ignore
pub fn coppock_curve( data: &[f64], long_roc: usize, short_roc: usize, wma_period: usize, ) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_coppock_curve`
instructions/iter74202
callgrind Ir/iter74202
median walltime (ns)8905
p99 walltime (ns)9010
allocations/iter3
allocated bytes/iter31704

dema function#

rust · ignore
pub fn dema(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_dema`
instructions/iter40936
callgrind Ir/iter40936
median walltime (ns)13273
p99 walltime (ns)13432
allocations/iter3
allocated bytes/iter31544

donchian_channels function#

rust · ignore
pub fn donchian_channels( highs: &[f64], lows: &[f64], period: usize, ) -> Result<DonchianChannelsResult>
measured as `finance_query::ind_donchian_channels`
instructions/iter181271
callgrind Ir/iter181271
median walltime (ns)10860
p99 walltime (ns)11165
allocations/iter9
allocated bytes/iter48448

elder_ray function#

rust · ignore
pub fn elder_ray( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, ) -> Result<ElderRayResult>
measured as `finance_query::ind_elder_ray`
instructions/iter29582
callgrind Ir/iter29582
median walltime (ns)7785
p99 walltime (ns)8042
allocations/iter3
allocated bytes/iter39904

ema function#

rust · ignore
pub fn ema(data: &[f64], period: usize) -> Vec<Option<f64>>
measured as `finance_query::ind_moving_averages`
instructions/iter488120
callgrind Ir/iter488120
median walltime (ns)96785
p99 walltime (ns)97857
allocations/iter27
allocated bytes/iter268760

fibonacci_pivot_points function#

rust · ignore
pub fn fibonacci_pivot_points( highs: &[f64], lows: &[f64], closes: &[f64], ) -> Result<Vec<Option<PivotPoints>>>
measured as `finance_query::ind_fibonacci_pivot_points`
instructions/iter24550
callgrind Ir/iter24550
median walltime (ns)2823
p99 walltime (ns)2868
allocations/iter1
allocated bytes/iter64000

fibonacci_retracement function#

rust · ignore
pub fn fibonacci_retracement( highs: &[f64], lows: &[f64], period: usize, ) -> Result<Vec<Option<FibonacciLevels>>>
measured as `finance_query::ind_fibonacci_retracement`
instructions/iter184891
callgrind Ir/iter184891
median walltime (ns)11239
p99 walltime (ns)11721
allocations/iter9
allocated bytes/iter64960

heikin_ashi function#

rust · ignore
pub fn heikin_ashi(candles: &[Candle]) -> Result<Vec<Candle>>
measured as `finance_query::ind_heikin_ashi`
instructions/iter133768
callgrind Ir/iter133768
median walltime (ns)15643
p99 walltime (ns)16385
allocations/iter9
allocated bytes/iter136000

hma function#

rust · ignore
pub fn hma(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_hma`
instructions/iter103233
callgrind Ir/iter103233
median walltime (ns)14679
p99 walltime (ns)14868
allocations/iter5
allocated bytes/iter47448

ichimoku function#

rust · ignore
pub fn ichimoku( highs: &[f64], lows: &[f64], closes: &[f64], conversion: usize, base: usize, lagging: usize, displacement: usize, ) -> Result<IchimokuResult>
measured as `finance_query::ind_ichimoku`
instructions/iter535303
callgrind Ir/iter535303
median walltime (ns)33363
p99 walltime (ns)35159
allocations/iter27
allocated bytes/iter82368

keltner_channels function#

rust · ignore
pub fn keltner_channels( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, atr_period: usize, multiplier: f64, ) -> Result<KeltnerChannelsResult>
measured as `finance_query::ind_keltner_channels`
instructions/iter98514
callgrind Ir/iter98514
median walltime (ns)19122
p99 walltime (ns)19323
allocations/iter5
allocated bytes/iter63776

last_value function#

rust · ignore
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));
measured as `finance_query::ind_last_value`
instructions/iter23
callgrind Ir/iter23
median walltime (ns)2
p99 walltime (ns)2
allocations/iter0
allocated bytes/iter0

macd function#

rust · ignore
pub fn macd( data: &[f64], fast_period: usize, slow_period: usize, signal_period: usize, ) -> Result<MacdResult>
measured as `finance_query::ind_macd`
instructions/iter82597
callgrind Ir/iter82597
median walltime (ns)21968
p99 walltime (ns)22129
allocations/iter7
allocated bytes/iter79248

mcginley_dynamic function#

rust · ignore
pub fn mcginley_dynamic(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_mcginley_dynamic`
instructions/iter21714
callgrind Ir/iter21714
median walltime (ns)13810
p99 walltime (ns)13925
allocations/iter1
allocated bytes/iter16000

mfi function#

rust · ignore
pub fn mfi( highs: &[f64], lows: &[f64], closes: &[f64], volumes: &[f64], period: usize, ) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_mfi`
instructions/iter94264
callgrind Ir/iter94264
median walltime (ns)7113
p99 walltime (ns)7691
allocations/iter3
allocated bytes/iter32000

momentum function#

rust · ignore
pub fn momentum(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_momentum_single`
instructions/iter8020
callgrind Ir/iter8020
median walltime (ns)583
p99 walltime (ns)592
allocations/iter1
allocated bytes/iter16000

obv function#

rust · ignore
pub fn obv(closes: &[f64], volumes: &[f64]) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_volume`
instructions/iter313454
callgrind Ir/iter313454
median walltime (ns)44411
p99 walltime (ns)44793
allocations/iter14
allocated bytes/iter167912

parabolic_sar function#

rust · ignore
pub fn parabolic_sar( highs: &[f64], lows: &[f64], closes: &[f64], acceleration: f64, maximum: f64, ) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_parabolic_sar`
instructions/iter24998
callgrind Ir/iter24998
median walltime (ns)2298
p99 walltime (ns)2384
allocations/iter1
allocated bytes/iter16000

pivot_points function#

rust · ignore
pub fn pivot_points( highs: &[f64], lows: &[f64], closes: &[f64], ) -> Result<Vec<Option<PivotPoints>>>
measured as `finance_query::ind_pivot_points`
instructions/iter26053
callgrind Ir/iter26053
median walltime (ns)3223
p99 walltime (ns)3272
allocations/iter1
allocated bytes/iter64000

roc function#

rust · ignore
pub fn roc(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_roc`
instructions/iter16876
callgrind Ir/iter16876
median walltime (ns)1894
p99 walltime (ns)1931
allocations/iter1
allocated bytes/iter16000

rsi function#

rust · ignore
pub fn rsi(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_momentum`
instructions/iter1190431
callgrind Ir/iter1190431
median walltime (ns)130251
p99 walltime (ns)135067
allocations/iter52
allocated bytes/iter390856

sma function#

rust · ignore
pub fn sma(data: &[f64], period: usize) -> Vec<Option<f64>>
verified claims
allocallocs 1 <= 1
p99p99 427825ns <= 1000000ns
complexityclaimed O(n); growth drift x1.01 over sizes [1000, 10000, 100000] (limit x2.5)
measured as `finance_query::ind_sma`
instructions/iter2200136
callgrind Ir/iter2200136
median walltime (ns)425426
p99 walltime (ns)427825
allocations/iter1
allocated bytes/iter1600000

stochastic function#

rust · ignore
pub fn stochastic( highs: &[f64], lows: &[f64], closes: &[f64], k_period: usize, k_slow: usize, d_period: usize, ) -> Result<StochasticResult>
measured as `finance_query::ind_stochastic`
instructions/iter226828
callgrind Ir/iter226828
median walltime (ns)16322
p99 walltime (ns)17685
allocations/iter11
allocated bytes/iter56224

stochastic_rsi function#

rust · ignore
pub fn stochastic_rsi( data: &[f64], rsi_period: usize, stoch_period: usize, k_period: usize, d_period: usize, ) -> Result<StochasticResult>
measured as `finance_query::ind_stochastic_rsi`
instructions/iter288917
callgrind Ir/iter288917
median walltime (ns)27566
p99 walltime (ns)28338
allocations/iter12
allocated bytes/iter63640

supertrend function#

rust · ignore
pub fn supertrend( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, multiplier: f64, ) -> Result<SuperTrendResult>
measured as `finance_query::ind_supertrend`
instructions/iter118930
callgrind Ir/iter118930
median walltime (ns)15055
p99 walltime (ns)15233
allocations/iter4
allocated bytes/iter40928

tema function#

rust · ignore
pub fn tema(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_tema`
instructions/iter58081
callgrind Ir/iter58081
median walltime (ns)19554
p99 walltime (ns)19700
allocations/iter4
allocated bytes/iter39088

true_range function#

rust · ignore
pub fn true_range(highs: &[f64], lows: &[f64], closes: &[f64]) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_true_range`
instructions/iter18089
callgrind Ir/iter18089
median walltime (ns)1329
p99 walltime (ns)1387
allocations/iter1
allocated bytes/iter16000

vwap function#

rust · ignore
pub fn vwap( highs: &[f64], lows: &[f64], closes: &[f64], volumes: &[f64], ) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_vwap`
instructions/iter31671
callgrind Ir/iter31671
median walltime (ns)4340
p99 walltime (ns)4371
allocations/iter1
allocated bytes/iter16000

vwma function#

rust · ignore
pub fn vwma(data: &[f64], volumes: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_vwma`
instructions/iter49541
callgrind Ir/iter49541
median walltime (ns)3270
p99 walltime (ns)3300
allocations/iter1
allocated bytes/iter16000

williams_r function#

rust · ignore
pub fn williams_r( highs: &[f64], lows: &[f64], closes: &[f64], period: usize, ) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_williams_r`
instructions/iter180141
callgrind Ir/iter180141
median walltime (ns)10800
p99 walltime (ns)12094
allocations/iter7
allocated bytes/iter16448

wma function#

rust · ignore
pub fn wma(data: &[f64], period: usize) -> Result<Vec<Option<f64>>>
measured as `finance_query::ind_wma`
instructions/iter31001
callgrind Ir/iter31001
median walltime (ns)4981
p99 walltime (ns)5063
allocations/iter7
allocated bytes/iter38608

zigzag function#

rust · ignore
pub fn zigzag(highs: &[f64], lows: &[f64], deviation_pct: f64) -> Result<Vec<ZigZagPoint>>
measured as `finance_query::ind_zigzag`
instructions/iter19859
callgrind Ir/iter19859
median walltime (ns)1529
p99 walltime (ns)1637
allocations/iter4
allocated bytes/iter1440

finance_query::indicators::Indicator#

warmup_bars function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub struct EarningsCalendar

Earnings calendar information

finance_query::models::corporate::earnings#

EarningsChart struct#

rust · ignore
pub struct EarningsChart

Earnings chart showing quarterly data

FinancialsChart struct#

rust · ignore
pub struct FinancialsChart

Financial chart showing revenue and earnings over time

QuarterlyEarnings struct#

rust · ignore
pub struct QuarterlyEarnings

Quarterly earnings entry

QuarterlyFinancials struct#

rust · ignore
pub struct QuarterlyFinancials

Quarterly financial data entry

YearlyFinancials struct#

rust · ignore
pub struct YearlyFinancials

Yearly financial data entry

finance_query::models::corporate::earnings_history#

EarningsHistoryEntry struct#

rust · ignore
pub struct EarningsHistoryEntry

Single historical earnings entry

finance_query::models::corporate::earnings_trend#

EarningsEstimate struct#

rust · ignore
pub struct EarningsEstimate

Earnings estimate data

EarningsTrendPeriod struct#

rust · ignore
pub struct EarningsTrendPeriod

Earnings trend for a specific period

EpsRevisions struct#

rust · ignore
pub struct EpsRevisions

EPS revision data

EpsTrend struct#

rust · ignore
pub struct EpsTrend

EPS trend over time

RevenueEstimate struct#

rust · ignore
pub struct RevenueEstimate

Revenue estimate data

finance_query::models::corporate::equity_performance#

Benchmark struct#

rust · ignore
pub struct Benchmark

Benchmark information

PerformanceOverview struct#

rust · ignore
pub struct PerformanceOverview

Performance metrics across multiple time periods

finance_query::models::corporate::fund_ownership#

FundOwner struct#

rust · ignore
pub struct FundOwner

Individual fund owner

finance_query::models::corporate::fund_performance#

AnnualReturn struct#

rust · ignore
pub struct AnnualReturn

Single year's return data

AnnualTotalReturns struct#

rust · ignore
pub struct AnnualTotalReturns

Annual total returns by year

PastQuarterlyReturns struct#

rust · ignore
pub struct PastQuarterlyReturns

Past quarterly returns

PerformanceOverview struct#

rust · ignore
pub struct PerformanceOverview

Performance overview with key return metrics

PerformanceOverviewCat struct#

rust · ignore
pub struct PerformanceOverviewCat

Category average performance overview

RiskOverviewStatistics struct#

rust · ignore
pub struct RiskOverviewStatistics

Risk overview statistics

RiskOverviewStatisticsCat struct#

rust · ignore
pub struct RiskOverviewStatisticsCat

Category average risk overview statistics

RiskStatistic struct#

rust · ignore
pub struct RiskStatistic

Risk statistics for a specific time period

TrailingReturns struct#

rust · ignore
pub struct TrailingReturns

Trailing returns at market price

TrailingReturnsCat struct#

rust · ignore
pub struct TrailingReturnsCat

Category average trailing returns

TrailingReturnsNav struct#

rust · ignore
pub struct TrailingReturnsNav

Trailing returns at NAV (Net Asset Value)

finance_query::models::corporate::fund_profile#

FeesExpenses struct#

rust · ignore
pub struct FeesExpenses

Fees and expenses for a fund

FeesExpensesCat struct#

rust · ignore
pub struct FeesExpensesCat

Average fees and expenses for funds in the same category

ManagementInfo struct#

rust · ignore
pub struct ManagementInfo

Fund management information

finance_query::models::corporate::insider_holders#

InsiderHolder struct#

rust · ignore
pub struct InsiderHolder

Individual insider holder information

finance_query::models::corporate::insider_transactions#

InsiderTransaction struct#

rust · ignore
pub struct InsiderTransaction

Individual insider transaction

finance_query::models::corporate::institution_ownership#

InstitutionOwner struct#

rust · ignore
pub struct InstitutionOwner

Individual institutional owner

finance_query::models::corporate::recommendation_trend#

RecommendationPeriod struct#

rust · ignore
pub struct RecommendationPeriod

Recommendations for a specific time period

finance_query::models::corporate::sec_filings#

SecExhibit struct#

rust · ignore
pub struct SecExhibit

SEC filing exhibit

SecFiling struct#

rust · ignore
pub struct SecFiling

Individual SEC filing

finance_query::models::corporate::top_holdings#

BondRating struct#

rust · ignore
pub struct BondRating

Bond rating distribution

EquityHoldings struct#

rust · ignore
pub struct EquityHoldings

Equity holdings valuation metrics

Holding struct#

rust · ignore
pub struct Holding

Individual holding in the fund

SectorWeighting struct#

rust · ignore
pub struct SectorWeighting

Sector weighting distribution (single sector from Yahoo's array format)

finance_query::models::corporate::transcript#

Paragraph struct#

rust · ignore
pub struct Paragraph

A paragraph (section spoken by one speaker).

Sentence struct#

rust · ignore
pub struct Sentence

A sentence within a paragraph.

SpeakerData struct#

rust · ignore
pub struct SpeakerData

Information about a speaker.

SpeakerMapping struct#

rust · ignore
pub struct SpeakerMapping

Mapping of a speaker ID to speaker information.

TranscriptContent struct#

rust · ignore
pub struct TranscriptContent

Transcript content including speakers and full transcript.

TranscriptData struct#

rust · ignore
pub struct TranscriptData

Full transcript data with paragraphs.

TranscriptMetadata struct#

rust · ignore
pub struct TranscriptMetadata

Metadata about the transcript.

Word struct#

rust · ignore
pub struct Word

A word with timing and confidence information.

finance_query::models::corporate::upgrade_downgrade_history#

GradeChange struct#

rust · ignore
pub struct GradeChange

Individual analyst rating change

finance_query::models::discovery::reference::ScreenerFilters#

new function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub struct NewsThumbnail

Thumbnail image with multiple resolutions

ThumbnailResolution struct#

rust · ignore
pub struct ThumbnailResolution

Individual thumbnail resolution

finance_query::models::filings::filing_index#

EdgarFilingIndexDirectory struct#

rust · ignore
pub struct EdgarFilingIndexDirectory

Directory metadata for an EDGAR filing.

finance_query::models::filings::submissions::EdgarFilingRecent#

to_filings function#

rust · ignore
pub fn to_filings(&self) -> Vec<EdgarFiling>

Convert parallel arrays into a vector of individual filings.

Example#

no_run
# 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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub struct BalanceSheetHistory

Balance sheet history (annual statements)

BalanceSheetHistoryQuarterly struct#

rust · ignore
pub struct BalanceSheetHistoryQuarterly

Balance sheet history (quarterly statements)

finance_query::models::fundamentals::cashflow_statement_history#

CashflowStatementHistory struct#

rust · ignore
pub struct CashflowStatementHistory

Cash flow statement history (annual statements)

CashflowStatementHistoryQuarterly struct#

rust · ignore
pub struct CashflowStatementHistoryQuarterly

Cash flow statement history (quarterly statements)

finance_query::models::fundamentals::income_statement_history#

IncomeStatementHistory struct#

rust · ignore
pub struct IncomeStatementHistory

Income statement history (annual statements)

IncomeStatementHistoryQuarterly struct#

rust · ignore
pub struct IncomeStatementHistoryQuarterly

Income statement history (quarterly statements)

finance_query::models::market::index_trend#

TrendEstimate struct#

rust · ignore
pub struct TrendEstimate

Growth estimate for a specific period

finance_query::models::market::industries::response#

BenchmarkPerformance struct#

rust · ignore
pub struct BenchmarkPerformance

Benchmark performance for comparison

GrowthCompany struct#

rust · ignore
pub struct GrowthCompany

Top growth company by growth estimate

IndustryCompany struct#

rust · ignore
pub struct IndustryCompany

Company within an industry

IndustryOverview struct#

rust · ignore
pub struct IndustryOverview

Industry overview statistics

IndustryPerformance struct#

rust · ignore
pub struct IndustryPerformance

Industry performance metrics

PerformingCompany struct#

rust · ignore
pub struct PerformingCompany

Top performing company by YTD return

ResearchReport struct#

rust · ignore
pub struct ResearchReport

Research report

finance_query::models::market::sectors::response#

ResearchReport struct#

rust · ignore
pub struct ResearchReport

A research report about the sector

SectorCompany struct#

rust · ignore
pub struct SectorCompany

A company in the sector's top companies list

SectorETF struct#

rust · ignore
pub struct SectorETF

An ETF tracking the sector

SectorIndustry struct#

rust · ignore
pub struct SectorIndustry

An industry within the sector

SectorMutualFund struct#

rust · ignore
pub struct SectorMutualFund

A mutual fund in the sector

SectorOverview struct#

rust · ignore
pub struct SectorOverview

Sector overview statistics

SectorPerformance struct#

rust · ignore
pub struct SectorPerformance

Sector performance metrics

finance_query::models::quote::data::Quote#

as_raw function#

rust · ignore
#[derive(Debug, Clone, Serialize, Deserialize, FormatConvert)]

Clone and convert into a Raw view.

finance_query::models::sentiment::score::Sentiment#

neutral function#

rust · ignore
pub fn neutral() -> Self

A neutral, zero-confidence score (used as the empty aggregate).

finance_query::openfigi#

SecurityIdKind enum#

rust · ignore
pub enum SecurityIdKind

SecurityMapping struct#

rust · ignore
pub struct SecurityMapping

resolve function#

rust · ignore
pub async fn resolve(kind: SecurityIdKind, id: &str) -> Result<Vec<SecurityMapping>>

Resolve an identifier of any supported [SecurityIdKind].

resolve_cusip function#

rust · ignore
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#

rust · ignore
pub async fn resolve_isin(isin: &str) -> Result<Vec<SecurityMapping>>

Resolve an ISIN to every instrument carrying it.

resolve_many function#

rust · ignore
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#

rust · ignore
pub async fn resolve_sedol(sedol: &str) -> Result<Vec<SecurityMapping>>

Resolve a SEDOL to every instrument carrying it.

finance_query::providers::adapter#

ProviderCore trait#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub trait ChartProvider: ProviderCore

[crate::Capability::CHART] — historical OHLCV candles and sparklines.

CorporateProvider trait#

rust · ignore
pub trait CorporateProvider: ProviderCore

[crate::Capability::CORPORATE] — news, corporate events, similar-symbol recommendations.

FilingsProvider trait#

rust · ignore
pub trait FilingsProvider: ProviderCore

[crate::Capability::FILINGS] — SEC filing data.

FundamentalsProvider trait#

rust · ignore
pub trait FundamentalsProvider: ProviderCore

[crate::Capability::FUNDAMENTALS] — financial statements and share-supply data.

OptionsProvider trait#

rust · ignore
pub trait OptionsProvider: ProviderCore

[crate::Capability::OPTIONS] — options chains.

QuoteProvider trait#

rust · ignore
pub trait QuoteProvider: ProviderCore

[crate::Capability::QUOTE] — single and batch equity quotes.

finance_query::providers::adapter::markets#

CalendarProvider trait#

rust · ignore
pub trait CalendarProvider: ProviderCore

[crate::Capability::CALENDAR] — market-wide calendars.

CommoditiesProvider trait#

rust · ignore
pub trait CommoditiesProvider: ProviderCore

[crate::Capability::COMMODITIES] — commodity price quotes.

DiscoveryProvider trait#

rust · ignore
pub trait DiscoveryProvider: ProviderCore

[crate::Capability::DISCOVERY] — symbol search, reference data, exchanges, screeners.

FuturesProvider trait#

rust · ignore
pub trait FuturesProvider: ProviderCore

[crate::Capability::FUTURES] — futures contract quotes.

IndicesProvider trait#

rust · ignore
pub trait IndicesProvider: ProviderCore

[crate::Capability::INDICES] — stock market index quotes.

MarketProvider trait#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub fn builder() -> ProvidersBuilder

Create a builder for configuring providers.

calendar function#

rust · ignore
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#

rust · ignore
pub fn commodity(&self, symbol: impl Into<String>) -> crate::domains::Commodity

Create a Commodity handle backed by this provider set.

crypto function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub fn futures(&self, symbol: impl Into<String>) -> crate::domains::FuturesContract

Create a FuturesContract handle backed by this provider set.

health function#

rust · ignore
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#

no_run
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#

rust · ignore
pub fn index(&self, symbol: impl Into<String>) -> crate::domains::Index

Create an Index handle backed by this provider set.

market function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub fn fetch(mut self, mode: Fetch) -> Self

Configure how providers are queried. Default: Sequential.

Use [Fetch::Sequential] or [Fetch::Parallel].

lang function#

rust · ignore
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#

rust · ignore
pub fn region(mut self, region: crate::constants::Region) -> Self

Set the region (automatically sets lang and region code).

retry function#

rust · ignore
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#

rust · ignore
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.

no_run
# 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#

rust · ignore
pub fn capability(self) -> Capability

The coarser [Capability] bit this operation falls under.

finance_query::providers::provider::Provider#

capabilities function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub fn base_delay(mut self, delay: Duration) -> Self

Override the base delay (see [RetryPolicy::base_delay] field docs).

jitter function#

rust · ignore
pub fn jitter(mut self, jitter: f64) -> Self

Override the jitter fraction (see [RetryPolicy::jitter] field docs).

max_delay function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub fn multiplier(mut self, multiplier: f64) -> Self

Override the backoff multiplier (see [RetryPolicy::multiplier] field docs).

finance_query::quote#

AssetProfile struct#

rust · ignore
pub struct AssetProfile

CalendarEvents struct#

rust · ignore
pub struct CalendarEvents

CompanyOfficer struct#

rust · ignore
pub struct CompanyOfficer

DefaultKeyStatistics struct#

rust · ignore
pub struct DefaultKeyStatistics<F: Format = Both>

Earnings struct#

rust · ignore
pub struct Earnings

EarningsHistory struct#

rust · ignore
pub struct EarningsHistory

EarningsTrend struct#

rust · ignore
pub struct EarningsTrend

EquityPerformance struct#

rust · ignore
pub struct EquityPerformance

FinancialData struct#

rust · ignore
pub struct FinancialData<F: Format = Both>

FundOwnership struct#

rust · ignore
pub struct FundOwnership

FundPerformance struct#

rust · ignore
pub struct FundPerformance

FundProfile struct#

rust · ignore
pub struct FundProfile

IndexTrend struct#

rust · ignore
pub struct IndexTrend

IndustryTrend struct#

rust · ignore
pub struct IndustryTrend

InsiderHolders struct#

rust · ignore
pub struct InsiderHolders

InsiderTransactions struct#

rust · ignore
pub struct InsiderTransactions

InstitutionOwnership struct#

rust · ignore
pub struct InstitutionOwnership

MajorHoldersBreakdown struct#

rust · ignore
pub struct MajorHoldersBreakdown

NetSharePurchaseActivity struct#

rust · ignore
pub struct NetSharePurchaseActivity

Price struct#

rust · ignore
pub struct Price<F: Format = Both>

QuoteTypeData struct#

rust · ignore
pub struct QuoteTypeData

RecommendationTrend struct#

rust · ignore
pub struct RecommendationTrend

SecFilings struct#

rust · ignore
pub struct SecFilings

SectorTrend struct#

rust · ignore
pub struct SectorTrend

SummaryDetail struct#

rust · ignore
pub struct SummaryDetail<F: Format = Both>

SummaryProfile struct#

rust · ignore
pub struct SummaryProfile

TopHoldings struct#

rust · ignore
pub struct TopHoldings

UpgradeDowngradeHistory struct#

rust · ignore
pub struct UpgradeDowngradeHistory

finance_query::risk#

RiskSummary struct#

rust · ignore
pub struct RiskSummary

Comprehensive risk summary for a symbol.

Obtain via Ticker::risk.

beta function#

rust · ignore
pub fn beta(asset_returns: &[f64], benchmark_returns: &[f64]) -> Option<f64>
verified claims
allocallocs 0 <= 0
complexityclaimed O(n); growth drift x1.02 over sizes [1024, 4096, 16384] (limit x2.5)
measured as `finance_query::risk_beta`
instructions/iter262224
callgrind Ir/iter262224
median walltime (ns)69066
p99 walltime (ns)69527
allocations/iter0
allocated bytes/iter0

calmar_ratio function#

rust · ignore
pub fn calmar_ratio(total_return: f64, years: f64, max_drawdown: f64) -> Option<f64>
verified claims
allocallocs 0 <= 0
measured as `finance_query::risk_calmar`
instructions/iter156
callgrind Ir/iter156
median walltime (ns)16
p99 walltime (ns)19
allocations/iter0
allocated bytes/iter0

historical_cvar function#

rust · ignore
pub fn historical_cvar(returns: &[f64], confidence: f64) -> Option<f64>
measured as `finance_query::risk_historical_cvar`
instructions/iter4332813
callgrind Ir/iter4332813
median walltime (ns)309916
p99 walltime (ns)336483
allocations/iter2
allocated bytes/iter262144

historical_var function#

rust · ignore
pub fn historical_var(returns: &[f64], confidence: f64) -> Option<f64>
verified claims
allocallocs 2 <= 2
complexityclaimed O(n log n); growth drift x1.20 over sizes [1000, 10000, 100000] (limit x2.5)
measured as `finance_query::risk_historical_var`
instructions/iter31167375
callgrind Ir/iter31167375
median walltime (ns)2792622
p99 walltime (ns)2840662
allocations/iter2
allocated bytes/iter1600000

information_ratio function#

rust · ignore
pub fn information_ratio( asset_returns: &[f64], benchmark_returns: &[f64], periods_per_year: f64, ) -> Option<f64>
measured as `finance_query::risk_information_ratio`
instructions/iter145879
callgrind Ir/iter145879
median walltime (ns)38949
p99 walltime (ns)39363
allocations/iter1
allocated bytes/iter131072

kelly_criterion function#

rust · ignore
pub fn kelly_criterion(win_rate: f64, avg_win_pct: f64, avg_loss_pct: f64) -> f64
measured as `finance_query::risk_kelly_criterion`
instructions/iter30925
callgrind Ir/iter30925
median walltime (ns)4158
p99 walltime (ns)4208
allocations/iter16
allocated bytes/iter16320

max_drawdown function#

rust · ignore
pub fn max_drawdown(returns: &[f64]) -> DrawdownResult
verified claims
allocallocs 1 <= 1
measured as `finance_query::risk_max_drawdown`
instructions/iter35226
callgrind Ir/iter35226
median walltime (ns)9040
p99 walltime (ns)9125
allocations/iter1
allocated bytes/iter8008

omega_ratio function#

rust · ignore
pub fn omega_ratio(returns: &[f64]) -> f64
measured as `finance_query::risk_omega_ratio`
instructions/iter139305
callgrind Ir/iter139305
median walltime (ns)34486
p99 walltime (ns)34758
allocations/iter0
allocated bytes/iter0

parametric_cvar function#

rust · ignore
pub fn parametric_cvar(returns: &[f64], confidence: f64) -> Option<f64>
measured as `finance_query::risk_parametric_cvar`
instructions/iter100416
callgrind Ir/iter100416
median walltime (ns)34537
p99 walltime (ns)34678
allocations/iter0
allocated bytes/iter0

parametric_var function#

rust · ignore
pub fn parametric_var(returns: &[f64], confidence: f64) -> Option<f64>
verified claims
allocallocs 0 <= 0
complexityclaimed O(n); growth drift x1.01 over sizes [1024, 4096, 16384] (limit x2.5)
measured as `finance_query::risk_parametric_var`
instructions/iter100412
callgrind Ir/iter100412
median walltime (ns)34533
p99 walltime (ns)34956
allocations/iter0
allocated bytes/iter0

sharpe_ratio function#

rust · ignore
pub fn sharpe_ratio(returns: &[f64], risk_free_rate: f64, periods_per_year: f64) -> Option<f64>
verified claims
allocallocs 0 <= 0
complexityclaimed O(n); growth drift x1.01 over sizes [1024, 4096, 16384] (limit x2.5)
measured as `finance_query::risk_sharpe`
instructions/iter100406
callgrind Ir/iter100406
median walltime (ns)34529
p99 walltime (ns)34786
allocations/iter0
allocated bytes/iter0

sortino_ratio function#

rust · ignore
pub fn sortino_ratio(returns: &[f64], risk_free_rate: f64, periods_per_year: f64) -> Option<f64>
verified claims
allocallocs 0 <= 0
complexityclaimed O(n); growth drift x1.02 over sizes [1024, 4096, 16384] (limit x2.5)
measured as `finance_query::risk_sortino`
instructions/iter161843
callgrind Ir/iter161843
median walltime (ns)34508
p99 walltime (ns)34776
allocations/iter0
allocated bytes/iter0

tracking_error function#

rust · ignore
pub fn tracking_error( asset_returns: &[f64], benchmark_returns: &[f64], periods_per_year: f64, ) -> Option<f64>
measured as `finance_query::risk_tracking_error`
instructions/iter145876
callgrind Ir/iter145876
median walltime (ns)38938
p99 walltime (ns)39125
allocations/iter1
allocated bytes/iter131072

ulcer_index function#

rust · ignore
pub fn ulcer_index(returns: &[f64]) -> f64
measured as `finance_query::risk_ulcer_index`
instructions/iter619414
callgrind Ir/iter619414
median walltime (ns)202733
p99 walltime (ns)204254
allocations/iter2
allocated bytes/iter262160

win_loss_stats function#

rust · ignore
pub fn win_loss_stats(returns: &[f64]) -> (f64, f64, f64)
measured as `finance_query::risk_win_loss_stats`
instructions/iter389633
callgrind Ir/iter389633
median walltime (ns)63731
p99 walltime (ns)76215
allocations/iter25
allocated bytes/iter393152

finance_query::risk::drawdown#

DrawdownResult struct#

rust · ignore
pub struct DrawdownResult

Maximum drawdown result.

finance_query::streaming#

AlertCondition enum#

rust · ignore
pub enum AlertCondition

AlertConditionKind enum#

rust · ignore
pub enum AlertConditionKind

AlertEvaluator struct#

rust · ignore
pub struct AlertEvaluator

AlertEvent struct#

rust · ignore
pub struct AlertEvent

AlertExt trait#

rust · ignore
pub trait AlertExt: Stream<Item = PriceUpdate> + Sized + Unpin

AlertRule struct#

rust · ignore
pub struct AlertRule

AlertStream struct#

rust · ignore
pub struct AlertStream<S>

AssetClass enum#

rust · ignore
pub enum AssetClass

Batched struct#

rust · ignore
pub struct Batched<S> where S: Stream,

BookLevel struct#

rust · ignore
pub struct BookLevel

DepthStream struct#

rust · ignore
stream_handle!

DepthStreamBuilder struct#

rust · ignore
pub struct DepthStreamBuilder

EconomicStream struct#

rust · ignore
stream_handle!

EconomicStreamBuilder struct#

rust · ignore
pub struct EconomicStreamBuilder

Greeks struct#

rust · ignore
pub struct Greeks

MarketHoursType enum#

rust · ignore
pub enum MarketHoursType

NewsStream struct#

rust · ignore
pub struct NewsStream

NewsStreamBuilder struct#

rust · ignore
pub struct NewsStreamBuilder

OptionContractUpdate struct#

rust · ignore
pub struct OptionContractUpdate

OptionType enum#

rust · ignore
pub enum OptionType

OptionsChainStream struct#

rust · ignore
stream_handle!

OptionsChainStreamBuilder struct#

rust · ignore
pub struct OptionsChainStreamBuilder

OrderBookUpdate struct#

rust · ignore
pub struct OrderBookUpdate

PriceSource enum#

rust · ignore
pub enum PriceSource

PriceStream struct#

rust · ignore
pub struct PriceStream

PriceStreamBuilder struct#

rust · ignore
pub struct PriceStreamBuilder

PriceUpdate struct#

rust · ignore
pub struct PriceUpdate
measured as `finance_query::stream_deserialize`
instructions/iter14643
callgrind Ir/iter14643
median walltime (ns)1155
p99 walltime (ns)1180
allocations/iter4
allocated bytes/iter20
measured as `finance_query::stream_serialize`
instructions/iter11065
callgrind Ir/iter11065
median walltime (ns)962
p99 walltime (ns)972
allocations/iter4
allocated bytes/iter1920

QuoteType enum#

rust · ignore
pub enum QuoteType

SeriesUpdate struct#

rust · ignore
pub struct SeriesUpdate

StreamBatchExt trait#

rust · ignore
pub trait StreamBatchExt: Stream + Sized + Unpin

StreamError enum#

rust · ignore
pub enum StreamError

StreamResult type_alias#

rust · ignore
pub type StreamResult<T> = std::result::Result<T, StreamError>

TradeStream struct#

rust · ignore
stream_handle!

TradeStreamBuilder struct#

rust · ignore
pub struct TradeStreamBuilder

TradeTick struct#

rust · ignore
pub struct TradeTick

finance_query::streaming::book::DepthStreamBuilder#

max_reconnect_attempts function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub enum MarketHoursTypeProto

Protobuf enum for market hours type

QuoteTypeProto enum#

rust · ignore
pub enum QuoteTypeProto

Protobuf enum for quote type

finance_query::streaming::trades::TradeStreamBuilder#

build function#

rust · ignore
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#

rust · ignore
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#

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

Creates a new builder for Ticker.

calendar function#

rust · ignore
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#

rust · ignore
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#

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

Compute dividend analytics for the requested time range.

edgar_company_facts function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub async fn financials( &self, stmt_type: StatementType, frequency: Frequency, ) -> Result<FinancialStatement>

Get financial statements.

news function#

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

Get news articles for this symbol.

price function#

rust · ignore
super::macros::define_quote_accessors!

Regular, pre- and post-market price, plus the day's range and volume.

quote function#

rust · ignore
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#

rust · ignore
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#

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

Get analyst recommendations and similar symbols.

risk function#

rust · ignore
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#

rust · ignore
pub async fn build(self) -> Result<Ticker>

Build the Ticker instance.

cache function#

rust · ignore
pub fn cache(mut self, ttl: Duration) -> Self

Cache responses for ttl instead of the default 60 seconds.

no_cache function#

rust · ignore
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#

rust · ignore
pub fn builder<S, I>(symbols: I) -> TickersBuilder where S: Into<String>, I: IntoIterator<Item = S>,

Creates a new builder for Tickers

charts function#

rust · ignore
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#

rust · ignore
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#

rust · ignore
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#

rust · ignore
pub struct Lang

Translatable trait#

rust · ignore
pub trait Translatable

TranslationBackend trait#

rust · ignore
pub trait TranslationBackend: Send + Sync

set_backend function#

rust · ignore
pub fn set_backend(backend: Arc<dyn TranslationBackend>)
measured as `finance_query::translation_set_backend`
instructions/iter244
callgrind Ir/iter244
median walltime (ns)17
p99 walltime (ns)19
allocations/iter1
allocated bytes/iter16

translate function#

rust · ignore
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.

measured as `finance_query::translation_translate`
instructions/iter53597
callgrind Ir/iter53597
median walltime (ns)3677
p99 walltime (ns)3796
allocations/iter79
allocated bytes/iter6298

translate_texts function#

rust · ignore
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.

measured as `finance_query::translate_dictionary`
instructions/iter19891
callgrind Ir/iter19891
median walltime (ns)1944
p99 walltime (ns)1989
allocations/iter49
allocated bytes/iter2880

translate_with function#

rust · ignore
pub async fn translate_with<T: Translatable + ?Sized>(value: &mut T, lang: &Lang) -> Result<()>

Like [translate], with an already-parsed [Lang].

measured as `finance_query::translation_translate_with`
instructions/iter52376
callgrind Ir/iter52376
median walltime (ns)3413
p99 walltime (ns)3520
allocations/iter77
allocated bytes/iter6294
built with cargo soothfast docs build source