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 theblocking_implmodule.governor: rate-limit requests to avoid HTTP 429 responses. Defaults to 10 requests/second; configure viaYahooConnectorBuilder::rate_limit.decimal: represent prices asrust_decimal::Decimalinstead off64.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§
Structs§
- AdjClose
- Asset
Profile - Calendar
Earnings - Calendar
Events calendarEventsmodule: upcoming earnings, dividend and ex-dividend dates.- Capital
Gain - This structure simply models a capital gain which has been recorded.
- Current
Trading Period - Default
KeyStatistics - Dividend
- This structure simply models a dividend which has been recorded.
- Earnings
earningsmodule: earnings charts and current quarter estimates.- Earnings
Chart - Earnings
Chart Quarterly - Earnings
Estimate - Earnings
History earningsHistorymodule: actual vs estimated EPS per past quarter.- Earnings
History Item - Earnings
Trend earningsTrendmodule: analyst estimates (earnings, revenue, growth) per period.- Earnings
Trend Item - EpsRevisions
- EpsTrend
- Extended
Quote Summary - Financial
Data - Financial
Event - A financial event (earnings, meeting or call) returned by
crate::YahooConnector::get_financial_events.event_typeis mapped from the raw API codes: “1” -> Call, “2” -> Earnings, “11” -> Meeting. - Financials
Chart - Financials
Chart Quarterly - Financials
Chart Yearly - Fund
Fees Expenses - Fund
Management Info - Fund
Ownership fundOwnershipmodule: top mutual fund holders.- Fund
Ownership Item - Fund
Profile fundProfilemodule: fund metadata (management, fees, category).- Fund
Valuation - Growth
Estimate - Insider
Holder - Insider
Holders insiderHoldersmodule: insider position details.- Insider
Transaction - Insider
Transactions insiderTransactionsmodule: recent insider share transactions.- Institution
Ownership institutionOwnershipmodule: top institutional holders.- Institution
Ownership Item - Major
Holders Breakdown majorHoldersBreakdownmodule: aggregate insider/institution ownership percentages.- NetShare
Purchase Activity netSharePurchaseActivitymodule: aggregate insider buying/selling activity.- Period
Info - Quote
- Struct for single quote
- Quote
Block - Quote
List - Quote
Type - RawValue
- A numeric value with Yahoo’s formatted string variants (
{raw, fmt, longFmt}). - Recommendation
Trend recommendationTrendmodule: analyst recommendation counts over the last months.- Recommendation
Trend Item - Revenue
Estimate - SecFiling
- SecFiling
Exhibit - SecFilings
secFilingsmodule: SEC filings list.- Split
- This structure simply models a split that has occurred.
- Summary
Detail - TopHolding
- TopHoldings
topHoldingsmodule: fund’s top holdings and asset allocation.- Trading
Periods - Upgrade
Downgrade History upgradeDowngradeHistorymodule: analyst rating changes.- Upgrade
Downgrade Item - YChart
- YMeta
Data - YNews
Item - A news item returned alongside the search results.
- YOption
Chain - Options chain response for a ticker.
- YOption
Chain Data - Options data for one underlying symbol.
- YOption
Chain Result - Result part of the options chain, containing one entry per expiration date.
- YOption
Contract - A single option contract (call or put).
- YOption
Details - Calls and puts for one expiration date.
- YQuote
- Current market quote data for the underlying symbol.
- YQuote
Block - YQuote
Item - A single search hit with missing name fields replaced by default values.
- YQuote
Item Opt - A single search hit with optional name fields.
- YQuote
Summary - YResponse
- YSearch
Result - Search result with missing name fields replaced by default values
(e.g. empty strings). Use
YSearchResultOptto keep theOptions. - YSearch
Result Opt - Search result with optional fields (
Option<String>for names). - YSummary
Data quoteSummarymodule: 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 isNone.- Yahoo
Connector - Container for connection parameters to yahoo! finance server
- Yahoo
Connector Builder - Builder for configuring a
YahooConnector(timeout, user agent, proxy, rate limit) before the HTTP client is created. Start withYahooConnectorBuilder::neworYahooConnector::builder, then callYahooConnectorBuilder::build.
Enums§
- Yahoo
Error - Errors returned by the yahoo! finance connector.