Download market data from Yahoo! Finance API
Comprehensive data access for individual financial instruments. The Ticker class provides access to historical prices, financial statements, ownership data, analyst recommendations, options chains, and extensive company information.
Create ticker objects and access basic information for any financial instrument supported by Yahoo Finance.
class Ticker:
def __init__(self, ticker: str, session=None, proxy=None):
"""
Create a Ticker object for accessing financial data.
Parameters:
- ticker: str, ticker symbol (e.g., "AAPL", "MSFT", "BTC-USD")
- session: requests.Session, optional session for HTTP requests
- proxy: deprecated, use yf.set_config(proxy=proxy) instead
"""import yfinance as yf
# Create ticker objects
apple = yf.Ticker("AAPL")
bitcoin = yf.Ticker("BTC-USD")
sp500 = yf.Ticker("^GSPC")
# Access basic info
print(apple.info['longName']) # "Apple Inc."
print(apple.info['sector']) # "Technology"Download historical price and volume data with flexible date ranges, intervals, and adjustment options.
def history(self, period: str = "1mo", interval: str = "1d",
start: Union[str, datetime] = None, end: Union[str, datetime] = None,
prepost: bool = False, actions: bool = True, auto_adjust: bool = True,
repair: bool = False, **kwargs) -> pd.DataFrame:
"""
Download historical market data.
Parameters:
- period: str, data period ("1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max")
- interval: str, data interval ("1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo")
- start: str/datetime, start date (YYYY-MM-DD format)
- end: str/datetime, end date (YYYY-MM-DD format)
- prepost: bool, include pre and post market data
- actions: bool, include dividend and split data
- auto_adjust: bool, adjust OHLC prices for splits and dividends
- repair: bool, repair bad data points
Returns:
pd.DataFrame with columns: Open, High, Low, Close, Volume, Dividends, Stock Splits
"""ticker = yf.Ticker("AAPL")
# Get 1 year of daily data
data = ticker.history(period="1y")
# Get specific date range with hourly data
data = ticker.history(start="2023-01-01", end="2023-12-31", interval="1h")
# Get raw data without adjustments
data = ticker.history(period="6mo", auto_adjust=False, actions=False)Access comprehensive company metadata, financial metrics, and key statistics.
# Properties
info: dict # Complete company information dictionary
fast_info: dict # Quick access to essential price metrics
history_metadata: dict # Metadata about historical data availability
isin: str # International Securities Identification NumberThe info dictionary contains extensive company data:
longName, shortName, symbol, sector, industrymarketCap, enterpriseValue, trailingPE, forwardPEcurrentPrice, dayHigh, dayLow, fiftyTwoWeekHigh, fiftyTwoWeekLowsharesOutstanding, floatShares, impliedSharesOutstandingbookValue, priceToBook, enterpriseToRevenue, enterpriseToEbitdaprofitMargins, operatingMargins, returnOnAssets, returnOnEquityrevenueGrowth, earningsGrowth, earningsQuarterlyGrowthAccess annual, quarterly, and trailing twelve months (TTM) financial statement data.
# Income Statement
income_stmt: pd.DataFrame # Annual income statement
quarterly_income_stmt: pd.DataFrame # Quarterly income statement
ttm_income_stmt: pd.DataFrame # Trailing twelve months income statement
financials: pd.DataFrame # Alias for income_stmt
quarterly_financials: pd.DataFrame # Alias for quarterly_income_stmt
ttm_financials: pd.DataFrame # Alias for ttm_income_stmt
# Balance Sheet
balance_sheet: pd.DataFrame # Annual balance sheet
quarterly_balance_sheet: pd.DataFrame # Quarterly balance sheet
# Cash Flow Statement
cash_flow: pd.DataFrame # Annual cash flow statement
quarterly_cash_flow: pd.DataFrame # Quarterly cash flow statement
ttm_cash_flow: pd.DataFrame # Trailing twelve months cash flowticker = yf.Ticker("AAPL")
# Get annual financial statements
income = ticker.income_stmt
balance = ticker.balance_sheet
cashflow = ticker.cash_flow
# Access specific metrics
revenue = income.loc['Total Revenue']
total_assets = balance.loc['Total Assets']
operating_cash_flow = cashflow.loc['Operating Cash Flow']
# Get quarterly data for recent periods
quarterly_revenue = ticker.quarterly_income_stmt.loc['Total Revenue']Access earnings data, estimates, and important calendar dates.
# Earnings Data
earnings: pd.DataFrame # Annual earnings data
quarterly_earnings: pd.DataFrame # Quarterly earnings data
earnings_dates: pd.DataFrame # Upcoming and historical earnings dates
calendar: dict # Earnings and dividend calendar
# Usage Example
earnings_history = ticker.earnings
next_earnings = ticker.earnings_dates
upcoming_events = ticker.calendarAccess dividend history, stock splits, and other corporate actions.
# Corporate Actions Properties
dividends: pd.Series # Historical dividend payments
capital_gains: pd.Series # Capital gains distributions (for funds)
splits: pd.Series # Stock split history
actions: pd.DataFrame # Combined dividends and splits data
# Share Data
shares: pd.DataFrame # Basic shares outstanding data
def get_shares_full(self, start: Union[str, datetime] = None,
end: Union[str, datetime] = None) -> pd.Series:
"""
Get detailed historical shares outstanding data.
Parameters:
- start: str/datetime, start date
- end: str/datetime, end date
Returns:
pd.Series with shares outstanding over time
"""Access institutional ownership, mutual fund holdings, and insider trading information.
# Ownership Properties
major_holders: pd.DataFrame # Major institutional holders summary
institutional_holders: pd.DataFrame # Detailed institutional ownership
mutualfund_holders: pd.DataFrame # Mutual fund ownership
insider_purchases: pd.DataFrame # Recent insider purchase transactions
insider_transactions: pd.DataFrame # All insider transactions
insider_roster_holders: pd.DataFrame # Current insider positionsAccess analyst recommendations, price targets, earnings estimates, and research reports.
# Analyst Data Properties
recommendations: pd.DataFrame # Historical analyst recommendations
recommendations_summary: pd.DataFrame # Current recommendations summary
upgrades_downgrades: pd.DataFrame # Recent rating changes
analyst_price_targets: dict # Price target statistics and distribution
# Earnings Estimates
earnings_estimate: pd.DataFrame # Earnings per share estimates
revenue_estimate: pd.DataFrame # Revenue estimates
earnings_history: pd.DataFrame # Earnings surprise history
eps_trend: pd.DataFrame # EPS estimate trends over time
eps_revisions: pd.DataFrame # Recent EPS estimate revisions
growth_estimates: pd.DataFrame # Long-term growth rate estimatesAccess options chains, expiration dates, and derivatives information.
# Options Properties
options: tuple # Available options expiration dates
def option_chain(self, date: str = None, tz: str = None) -> namedtuple:
"""
Get options chain data for a specific expiration date.
Parameters:
- date: str, expiration date in YYYY-MM-DD format (if None, uses nearest expiration)
- tz: str, timezone for option data
Returns:
namedtuple with attributes:
- calls: pd.DataFrame with call options data
- puts: pd.DataFrame with put options data
- underlying: dict with underlying stock info
"""ticker = yf.Ticker("AAPL")
# Get available expiration dates
expirations = ticker.options
print(expirations) # ('2024-01-19', '2024-01-26', ...)
# Get options chain for specific date
chain = ticker.option_chain('2024-01-19')
calls = chain.calls
puts = chain.puts
underlying = chain.underlying
# Filter options by criteria
otm_calls = calls[calls['inTheMoney'] == False]
high_volume_puts = puts[puts['volume'] > 100]Access news, ESG data, SEC filings, and mutual fund specific information.
# Additional Properties
news: list # Recent news articles related to the ticker
sustainability: pd.DataFrame # ESG (Environmental, Social, Governance) scores
sec_filings: dict # SEC filing information and links
funds_data: FundsData # Mutual fund/ETF specific data (if applicable)Enable real-time data streaming for individual tickers.
def live(self, message_handler: Callable = None, verbose: bool = True):
"""
Start real-time data streaming for this ticker.
Parameters:
- message_handler: function to handle incoming messages
- verbose: bool, enable verbose logging
"""def handle_price_update(message):
print(f"Price update: {message}")
ticker = yf.Ticker("AAPL")
ticker.live(message_handler=handle_price_update)Historical Data DataFrame:
Financial Statements DataFrames:
Options DataFrames:
# Check if data exists before using
if not ticker.info:
print("No info available")
if ticker.history().empty:
print("No historical data available")
# Handle missing data gracefully
try:
financials = ticker.income_stmt
if not financials.empty:
revenue = financials.loc['Total Revenue'].iloc[0]
except (KeyError, IndexError):
print("Revenue data not available")Install with Tessl CLI
npx tessl i tessl/pypi-yfinance