pip install yfinance★Core install. Python 3.9+.pip install "yfinance[nospam]"Adds caching + rate-limiting extras (requests_cache,requests_ratelimiter).import yfinance as yf★The universal alias. Everything hangs offyf.yf.__version__Check your version — the API moves fast (this sheet = 1.5.x).pip install -U yfinanceUpgrade often; Yahoo breaks things and fixes land quickly.
t = yf.Ticker("AAPL")★Your gateway to everything about one symbol. Cheap to make — no network yet.t = yf.Ticker("RELIANCE.NS")Non-US symbols need an exchange suffix (see the symbol card).t.tickerThe symbol string back out.t.isinThe security's ISIN (where available).t.history(...) t.info t.dividends …Each attribute below is a live, lazy fetch off this one object — reuse it.
yf.download("AAPL")★Prices for one symbol (defaults to last1mo, daily).yf.download(["AAPL","MSFT"])★Many symbols at once → MultiIndex columns. Threaded by default.yf.download(t, start="2024-01-01", end="2024-12-31")★Explicit window.endis exclusive.yf.download(t, period="1y", interval="1d")Or a rollingperiodinstead of start/end.yf.download(t, group_by="ticker")Columns become(ticker, field)instead of(field, ticker).yf.download(t, auto_adjust=False)Turn OFF adjustment to get a separateAdj Closeback.yf.download(t, progress=False)★Silence the progress bar (great in scripts/notebooks).yf.download(t, threads=True, repair=True)threadsparallelises;repairfixes known Yahoo price glitches.yf.download(t, multi_level_index=False)Flatten to plain columns for a single ticker.yf.download(t, actions=True, prepost=True)Include dividends/splits columns and pre/post-market bars.
t.history(period="1mo")★OHLCV DataFrame indexed by tz-aware date. Auto-adjusted.t.history(period="max")★Everything Yahoo has for the symbol.t.history(start="2020-01-01", end="2024-01-01")Fixed window (endexclusive).t.history(interval="1h", period="1mo")Intraday bars (mind the lookback limits — see the interval card).t.history(auto_adjust=False)Keep raw OHLC + a separateAdj Close.t.history(prepost=True)Include pre- and post-market trading.t.history(repair=True)Auto-repair suspicious 100x / currency-mixup prices.t.get_history_metadata()Exchange, tz, currency, trading periods behind the last fetch.
period = 1d 5d 1mo 3mo 6mo★…continues:1y 2y 5y 10y ytd max. A rolling lookback.interval = 1m 2m 5m 15m 30m★…then60m 90m 1h 1d 5d 1wk 1mo 3mo. Bar size.interval="1m" → last 7 days onlylimit1-minute data has a hard 7-day window.any intraday (<1d) → last 60 dayslimitSub-daily bars can't go back more than ~60 days.use period or start/endIf both given,start/endwins; don't mix expectations.
df[["Open","High","Low","Close","Volume"]]★The five core columns (+Dividends,Stock Splits).df.indexA tz-awareDatetimeIndexin the exchange's local time.df["Close"].plot()★Straight into pandas/matplotlib — it's just a DataFrame.data["Close"]["AAPL"]MultiIndex select: field first (defaultgroup_by="column").data["AAPL"]["Close"]…ticker first when you passedgroup_by="ticker".data.xs("Close", axis=1, level=0)Slice one field across every ticker cleanly.no "Adj Close" by defaultchangedauto_adjust=True is the default now — OHLC are already adjusted.
t.dividends★Series of dividend payments by date.t.splitsSeries of stock-split ratios by date.t.actions★Dividends + splits together in one DataFrame.t.capital_gainsCapital-gains distributions (mutual funds).t.get_shares_full(start="2022-01-01")Historical shares-outstanding time series.
t.options★Tuple of available expiry dates (as strings).chain = t.option_chain(t.options[0])★One expiry's chain. Omit the date for the nearest expiry.chain.callsCalls DataFrame — strike, bid/ask, IV, OI, volume.chain.putsPuts DataFrame, same columns.chain.underlyingDict of the underlying's live quote at fetch time.
t.fast_info★Fast & reliable: last_price, market_cap, currency, day_high/low, year_high/low, 50/200-day averages, shares…t.fast_info["last_price"]★Dict-like access to a single quick field.t.infoBig profile dict (sector, summary, ratios…). Slow & fragile — prefer fast_info for quick fields.t.info["marketCap"]Hundreds of keys; wrap access in.get().t.newsRecent news items (list of dicts) for the symbol.t.get_isin()Look up the ISIN identifier.
t.income_stmt★Annual income statement (DataFrame, periods as columns).t.quarterly_income_stmtQuarterly version. Alsottm_income_stmt.t.balance_sheet★Annual balance sheet;quarterly_balance_sheettoo.t.cashflow★Cash-flow statement;quarterly_cashflow,ttm_cashflow.t.calendarNext earnings date, ex-dividend date, estimates.t.get_earnings_dates(limit=12)Past & upcoming earnings dates with EPS est. vs actual.t.sec_filingsRecent SEC filings metadata.t.earningsdeprecatedGone/unreliable — read net income fromincome_stmtinstead.
t.analyst_price_targets★Dict: current, low, high, mean, median target.t.recommendationsBuy/hold/sell counts by period (DataFrame).t.recommendations_summaryRolling summary of the above.t.upgrades_downgradesRatings-change history by firm.t.earnings_estimateEPS estimates for coming periods.t.revenue_estimateRevenue estimates for coming periods.t.earnings_historyPast estimate vs actual EPS + surprise.t.eps_trend t.eps_revisionsHow estimates are trending / being revised.t.growth_estimatesProjected growth vs sector/index.
t.major_holders% insiders vs institutions summary.t.institutional_holders★Top institutional holders (DataFrame).t.mutualfund_holdersTop mutual-fund holders.t.insider_transactionsRecent insider buys/sells.t.insider_purchasesInsider purchase activity summary.t.insider_roster_holdersCurrent insider roster + holdings.t.sustainabilityESG risk scores (DataFrame).
f = yf.Ticker("SPY").funds_data★ETF/mutual-fund-specific bundle.f.descriptionProse overview of the fund.f.top_holdings★Largest positions with weights (DataFrame).f.sector_weightingsAllocation across sectors.f.asset_classesEquity / bond / cash breakdown.f.fund_overview f.fund_operationsCategory, family, expense-ratio style facts.f.equity_holdings f.bond_holdingsValuation/quality metrics; alsobond_ratings.
ts = yf.Tickers("MSFT AAPL GOOG")★Space-separated string → a bundle of Ticker objects.ts.tickers["MSFT"].info★Reach any member and use the full Ticker API.ts.tickers["AAPL"].history(period="1mo")Per-symbol calls, one object each.yf.download(["AAPL","MSFT"], group_by="ticker")Bulk prices — usually simpler than Tickers for OHLCV.ts.live()newOpen a streaming feed for the whole bundle.
s = yf.Search("apple", max_results=8)★Free-text search across Yahoo Finance.s.quotesMatching securities; alsos.news,s.lists,s.research,s.all.lk = yf.Lookup("AAPL")newResolve a query into typed results.lk.stock lk.etf lk.currencyAlsocryptocurrency,future,index,mutualfund,all.
sec = yf.Sector("technology")newA whole GICS-style sector as an object.sec.top_companies sec.top_etfsLeaders in the sector; alsotop_mutual_funds,industries.sec.overview sec.research_reportsSummary stats + linked research.ind = yf.Industry("software-infrastructure")top_companies,top_growth_companies,sector_key…m = yf.Market("US")m.status(open/closed) &m.summary(indices snapshot).
yf.screen("day_gainers")★newRun a predefined screen by name.yf.PREDEFINED_SCREENER_QUERIES.keys()most_actives,day_losers,undervalued_growth_stocks,top_etfs_us…q = yf.EquityQuery("gt", ["intradaymarketcap", 1e9])A single filter clause.yf.EquityQuery("and", [q1, q2])Combine withand/or; ops:eq is-in btwn gt lt gte lte.yf.screen(q, size=50, sortField="ticker")Custom screens; alsoFundQuery,ETFQuery.
t.live()newQuickest way to stream a Ticker's live prices.ws = yf.WebSocket()Explicit real-time client (useswebsocketsunder the hood).ws.subscribe(["AAPL","BTC-USD"])★Register symbols for the live feed.ws.listen(handler)Blocking loop;handler(msg)gets each tick as a dict.yf.AsyncWebSocket()async/awaitvariant for asyncio apps.ws.unsubscribe(...) ws.close()Drop symbols / tear the connection down.
from curl_cffi import requests★yfinance runs on curl_cffi now — build sessions from it, notrequests.sess = requests.Session(impersonate="chrome")Reuse one session to look like a browser & cut throttling.yf.Ticker("AAPL", session=sess)Pass your session (caching / rate-limiting) into any call.yf.set_config(proxy="http://…")newGlobal proxy — replaces the deprecated per-callproxy=.yf.enable_debug_mode()Verbose logging when a fetch misbehaves.yf.set_tz_cache_location("~/.yf")Where the timezone cache (peewee/SQLite) lives.time.sleep(...) between callsthrottleYahoo rate-limits — cache, batch, and slow down to avoid 429s.
AAPL MSFT TSLAUS stocks — plain exchange symbol.^GSPC ^NSEI ^BSESN ^DJI★^ = index (S&P 500 · NIFTY 50 · SENSEX · Dow).RELIANCE.NS TCS.NS★.NS = NSE India · .BO = BSE (e.g.RELIANCE.BO).EURUSD=X INR=X=X = forex pair (USD/INR =INR=X).BTC-USD ETH-USD-USD = crypto priced in dollars.GC=F CL=F=F = futures (gold · crude). London =.L, Toronto =.TO.