Skip to main content

Crate yahoo_finance_api

Crate yahoo_finance_api 

Source
Expand description

§yahoo! finance API

This project provides a set of functions to receive data from the yahoo! finance website via their API. This project is licensed under Apache 2.0 or MIT license (see files LICENSE-Apache2.0 and LICENSE-MIT).

Since version 0.3, all requests to the yahoo API return futures, using async features (the upgrade to reqwest 0.13 arrived in 4.1.1). Therefore, the functions need to be called from within another async function with .await (e.g. via #[tokio::main]). The examples below are based on the tokio runtime.

Use the blocking feature to get the previous behavior back: i.e. yahoo_finance_api = {"version": "5", features = ["blocking"]}.

§Features

  • blocking: provide a blocking (non-async) API via the blocking_impl module.
  • governor: rate-limit requests to avoid HTTP 429 responses. Defaults to 10 requests/second; configure via YahooConnectorBuilder::rate_limit.
  • decimal: represent prices as rust_decimal::Decimal instead of f64.
  • debug: include the full response body (truncated) in deserialization error messages.

§Get the latest available quote:

use yahoo_finance_api as yahoo;
use time::OffsetDateTime;
use tokio;

#[tokio::main]
async fn main() {
    let provider = yahoo::YahooConnector::new().unwrap();
    // get the latest quotes with the given interval
    let response = provider.get_latest_quotes("AAPL", "1d").await.unwrap();
    // extract just the latest valid quote summary
    // including timestamp,open,close,high,low,volume
    let quote = response.last_quote().unwrap();
    let time: OffsetDateTime =
        OffsetDateTime::from_unix_timestamp(quote.timestamp).unwrap();
    println!("At {} quote price of Apple was {}", time, quote.close);
}

§Get history of quotes for given time period:

use yahoo_finance_api as yahoo;
use time::macros::datetime;
use tokio;

#[tokio::main]
async fn main() {
    let provider = yahoo::YahooConnector::new().unwrap();
    let start = datetime!(2020-1-1 0:00:00.00 UTC);
    let end = datetime!(2020-1-31 23:59:59.99 UTC);
    // returns historic quotes with daily interval
    let resp = provider.get_quote_history("AAPL", start, end).await.unwrap();
    let quotes = resp.quotes().unwrap();
    println!("Apple's quotes in January: {:?}", quotes);
}

§Get the history of quotes for time range

Another method to retrieve a range of quotes is by requesting the quotes for a given period and lookup frequency. Here is an example retrieving the daily quotes for the last month:

use yahoo_finance_api as yahoo;
use tokio;

#[tokio::main]
async fn main() {
    let provider = yahoo::YahooConnector::new().unwrap();
    let response = provider.get_quote_range("AAPL", "1d", "1mo").await.unwrap();
    let quotes = response.quotes().unwrap();
    println!("Apple's quotes of the last month: {:?}", quotes);
}

§Search for a ticker given a search string (e.g. company name):

use yahoo_finance_api as yahoo;
use tokio;

#[tokio::main]
async fn main() {
    let provider = yahoo::YahooConnector::new().unwrap();
    let resp = provider.search_ticker("Apple").await.unwrap();

    println!("All tickers found while searching for 'Apple':");
    for item in resp.quotes
    {
        println!("{}", item.symbol)
    }
}

Some fields like longname are only optional and will be replaced by default values if missing (e.g. empty string). If you do not like this behavior, use search_ticker_opt instead which contains Option<String> fields, returning None if the field found missing in the response.

Re-exports§

pub use time;

Modules§

async_impl

Structs§

AdjClose
AssetProfile
CalendarEarnings
CalendarEvents
calendarEvents module: upcoming earnings, dividend and ex-dividend dates.
CapitalGain
This structure simply models a capital gain which has been recorded.
CurrentTradingPeriod
DefaultKeyStatistics
Dividend
This structure simply models a dividend which has been recorded.
Earnings
earnings module: earnings charts and current quarter estimates.
EarningsChart
EarningsChartQuarterly
EarningsEstimate
EarningsHistory
earningsHistory module: actual vs estimated EPS per past quarter.
EarningsHistoryItem
EarningsTrend
earningsTrend module: analyst estimates (earnings, revenue, growth) per period.
EarningsTrendItem
EpsRevisions
EpsTrend
ExtendedQuoteSummary
FinancialData
FinancialEvent
A financial event (earnings, meeting or call) returned by crate::YahooConnector::get_financial_events. event_type is mapped from the raw API codes: “1” -> Call, “2” -> Earnings, “11” -> Meeting.
FinancialsChart
FinancialsChartQuarterly
FinancialsChartYearly
FundFeesExpenses
FundManagementInfo
FundOwnership
fundOwnership module: top mutual fund holders.
FundOwnershipItem
FundProfile
fundProfile module: fund metadata (management, fees, category).
FundValuation
GrowthEstimate
InsiderHolder
InsiderHolders
insiderHolders module: insider position details.
InsiderTransaction
InsiderTransactions
insiderTransactions module: recent insider share transactions.
InstitutionOwnership
institutionOwnership module: top institutional holders.
InstitutionOwnershipItem
MajorHoldersBreakdown
majorHoldersBreakdown module: aggregate insider/institution ownership percentages.
NetSharePurchaseActivity
netSharePurchaseActivity module: aggregate insider buying/selling activity.
PeriodInfo
Quote
Struct for single quote
QuoteBlock
QuoteList
QuoteType
RawValue
A numeric value with Yahoo’s formatted string variants ({raw, fmt, longFmt}).
RecommendationTrend
recommendationTrend module: analyst recommendation counts over the last months.
RecommendationTrendItem
RevenueEstimate
SecFiling
SecFilingExhibit
SecFilings
secFilings module: SEC filings list.
Split
This structure simply models a split that has occurred.
SummaryDetail
TopHolding
TopHoldings
topHoldings module: fund’s top holdings and asset allocation.
TradingPeriods
UpgradeDowngradeHistory
upgradeDowngradeHistory module: analyst rating changes.
UpgradeDowngradeItem
YChart
YMetaData
YNewsItem
A news item returned alongside the search results.
YOptionChain
Options chain response for a ticker.
YOptionChainData
Options data for one underlying symbol.
YOptionChainResult
Result part of the options chain, containing one entry per expiration date.
YOptionContract
A single option contract (call or put).
YOptionDetails
Calls and puts for one expiration date.
YQuote
Current market quote data for the underlying symbol.
YQuoteBlock
YQuoteItem
A single search hit with missing name fields replaced by default values.
YQuoteItemOpt
A single search hit with optional name fields.
YQuoteSummary
YResponse
YSearchResult
Search result with missing name fields replaced by default values (e.g. empty strings). Use YSearchResultOpt to keep the Options.
YSearchResultOpt
Search result with optional fields (Option<String> for names).
YSummaryData
quoteSummary module: all 20 modules of the quoteSummary API (company profile, summary detail, financial data, recommendations, calendar, holders, fund profile, sec filings, …). Only the modules that apply to the asset type are present, the rest is None.
YahooConnector
Container for connection parameters to yahoo! finance server
YahooConnectorBuilder
Builder for configuring a YahooConnector (timeout, user agent, proxy, rate limit) before the HTTP client is created. Start with YahooConnectorBuilder::new or YahooConnector::builder, then call YahooConnectorBuilder::build.

Enums§

YahooError
Errors returned by the yahoo! finance connector.

Type Aliases§

Decimal