Need stock market data for your application? Yahoo Finance provides one of the most comprehensive sources of financial data. This guide covers how to access stock quotes, historical prices, financial statements, and more.
What You Can Get from Yahoo Finance
| Data Type | Description | Use Case |
|---|---|---|
| Real-time Quotes | Current price, change, volume | Trading apps |
| Historical Data | OHLCV data for any period | Charts, backtesting |
| Company Info | Profile, sector, employees | Company research |
| Financial Statements | Income, balance sheet, cash flow | Fundamental analysis |
| Options Data | Calls, puts, Greeks | Options trading |
| Analyst Recommendations | Buy/hold/sell ratings | Investment research |
Accessing Yahoo Finance Data
Yahoo Finance doesn't offer an official public API, but there are several ways to access the data:
Option 1: yfinance (Python Library)
The most popular and reliable method:
pip install yfinance
import yfinance as yf
# Get stock info
apple = yf.Ticker("AAPL")
# Current price
print(apple.info['currentPrice']) # 178.50
# Company name
print(apple.info['longName']) # Apple Inc.
Option 2: yahoo-finance2 (JavaScript)
npm install yahoo-finance2
const yahooFinance = require('yahoo-finance2').default;
async function getStock(symbol) {
const quote = await yahooFinance.quote(symbol);
return {
symbol: quote.symbol,
price: quote.regularMarketPrice,
change: quote.regularMarketChange,
changePercent: quote.regularMarketChangePercent,
volume: quote.regularMarketVolume
};
}
const apple = await getStock('AAPL');
console.log(apple);
// { symbol: 'AAPL', price: 178.50, change: 2.35, changePercent: 1.33, volume: 52341200 }
Option 3: Direct API (Unofficial)
const axios = require('axios');
async function getQuote(symbol) {
const response = await axios.get(
`https://query1.finance.yahoo.com/v7/finance/quote`,
{
params: {
symbols: symbol,
fields: 'regularMarketPrice,regularMarketChange,regularMarketVolume'
},
headers: {
'User-Agent': 'Mozilla/5.0'
}
}
);
return response.data.quoteResponse.result[0];
}
Real-Time Stock Quotes
JavaScript Example
const yahooFinance = require('yahoo-finance2').default;
async function getMultipleQuotes(symbols) {
const quotes = await yahooFinance.quote(symbols);
return quotes.map(q => ({
symbol: q.symbol,
name: q.shortName,
price: q.regularMarketPrice,
change: q.regularMarketChange,
changePercent: q.regularMarketChangePercent?.toFixed(2),
dayHigh: q.regularMarketDayHigh,
dayLow: q.regularMarketDayLow,
volume: q.regularMarketVolume,
marketCap: q.marketCap,
peRatio: q.trailingPE
}));
}
// Get multiple stocks at once
const stocks = await getMultipleQuotes(['AAPL', 'GOOGL', 'MSFT', 'AMZN']);
console.log(stocks);
Python Example
import yfinance as yf
def get_quotes(symbols):
"""Get real-time quotes for multiple symbols."""
tickers = yf.Tickers(' '.join(symbols))
quotes = []
for symbol in symbols:
ticker = tickers.tickers[symbol]
info = ticker.info
quotes.append({
'symbol': symbol,
'name': info.get('shortName'),
'price': info.get('currentPrice') or info.get('regularMarketPrice'),
'change': info.get('regularMarketChange'),
'change_percent': info.get('regularMarketChangePercent'),
'volume': info.get('volume'),
'market_cap': info.get('marketCap'),
'pe_ratio': info.get('trailingPE')
})
return quotes
# Usage
quotes = get_quotes(['AAPL', 'GOOGL', 'MSFT'])
for q in quotes:
print(f"{q['symbol']}: ${q['price']:.2f} ({q['change_percent']:.2f}%)")
Historical Price Data
Get OHLCV (Open, High, Low, Close, Volume) data for any time period:
JavaScript Example
const yahooFinance = require('yahoo-finance2').default;
async function getHistoricalData(symbol, period1, period2) {
const history = await yahooFinance.historical(symbol, {
period1, // Start date
period2, // End date
interval: '1d' // '1d', '1wk', '1mo'
});
return history.map(day => ({
date: day.date.toISOString().split('T')[0],
open: day.open,
high: day.high,
low: day.low,
close: day.close,
volume: day.volume,
adjClose: day.adjClose
}));
}
// Get last year of data
const history = await getHistoricalData(
'AAPL',
'2025-01-01',
'2026-01-01'
);
console.log(`Retrieved ${history.length} days of data`);
console.log(history.slice(0, 3)); // First 3 days
Python Example
import yfinance as yf
import pandas as pd
def get_historical_data(symbol, start, end, interval='1d'):
"""
Get historical OHLCV data.
Intervals: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo
"""
ticker = yf.Ticker(symbol)
df = ticker.history(start=start, end=end, interval=interval)
return df
# Get daily data for the last year
df = get_historical_data('AAPL', '2025-01-01', '2026-01-01')
print(df.tail())
# Calculate simple metrics
df['Daily_Return'] = df['Close'].pct_change()
df['MA_20'] = df['Close'].rolling(window=20).mean()
df['MA_50'] = df['Close'].rolling(window=50).mean()
print(f"Average daily return: {df['Daily_Return'].mean():.4f}")
print(f"Volatility (std): {df['Daily_Return'].std():.4f}")
Intraday Data
# Get intraday data (last 7 days max for 1-minute intervals)
df_intraday = get_historical_data('AAPL', '2026-01-20', '2026-01-26', interval='5m')
print(f"Intraday data points: {len(df_intraday)}")
Company Information
Get detailed company profiles:
JavaScript Example
async function getCompanyInfo(symbol) {
const quote = await yahooFinance.quoteSummary(symbol, {
modules: ['assetProfile', 'summaryDetail', 'price']
});
const profile = quote.assetProfile;
const summary = quote.summaryDetail;
return {
name: quote.price.longName,
symbol: quote.price.symbol,
sector: profile.sector,
industry: profile.industry,
website: profile.website,
employees: profile.fullTimeEmployees,
description: profile.longBusinessSummary,
headquarters: `${profile.city}, ${profile.state}, ${profile.country}`,
marketCap: summary.marketCap,
peRatio: summary.trailingPE,
dividendYield: summary.dividendYield,
fiftyTwoWeekHigh: summary.fiftyTwoWeekHigh,
fiftyTwoWeekLow: summary.fiftyTwoWeekLow
};
}
const appleInfo = await getCompanyInfo('AAPL');
console.log(appleInfo);
Python Example
def get_company_info(symbol):
"""Get comprehensive company information."""
ticker = yf.Ticker(symbol)
info = ticker.info
return {
'name': info.get('longName'),
'symbol': info.get('symbol'),
'sector': info.get('sector'),
'industry': info.get('industry'),
'website': info.get('website'),
'employees': info.get('fullTimeEmployees'),
'description': info.get('longBusinessSummary'),
'market_cap': info.get('marketCap'),
'pe_ratio': info.get('trailingPE'),
'forward_pe': info.get('forwardPE'),
'dividend_yield': info.get('dividendYield'),
'beta': info.get('beta'),
'52_week_high': info.get('fiftyTwoWeekHigh'),
'52_week_low': info.get('fiftyTwoWeekLow')
}
info = get_company_info('MSFT')
print(f"{info['name']} ({info['symbol']})")
print(f"Sector: {info['sector']}")
print(f"Market Cap: ${info['market_cap']:,.0f}")
Financial Statements
Access income statements, balance sheets, and cash flow statements:
Python Example
def get_financials(symbol):
"""Get financial statements."""
ticker = yf.Ticker(symbol)
return {
'income_statement': ticker.financials,
'quarterly_income': ticker.quarterly_financials,
'balance_sheet': ticker.balance_sheet,
'quarterly_balance': ticker.quarterly_balance_sheet,
'cash_flow': ticker.cashflow,
'quarterly_cash_flow': ticker.quarterly_cashflow
}
# Get Apple financials
financials = get_financials('AAPL')
# Income Statement
income = financials['income_statement']
print("Annual Income Statement:")
print(income.loc[['Total Revenue', 'Gross Profit', 'Net Income']])
# Balance Sheet
balance = financials['balance_sheet']
print("\nBalance Sheet:")
print(balance.loc[['Total Assets', 'Total Liabilities Net Minority Interest', 'Total Equity Gross Minority Interest']])
JavaScript Example
async function getFinancials(symbol) {
const summary = await yahooFinance.quoteSummary(symbol, {
modules: ['incomeStatementHistory', 'balanceSheetHistory', 'cashflowStatementHistory']
});
return {
incomeStatement: summary.incomeStatementHistory.incomeStatementHistory,
balanceSheet: summary.balanceSheetHistory.balanceSheetStatements,
cashFlow: summary.cashflowStatementHistory.cashflowStatements
};
}
const financials = await getFinancials('AAPL');
// Latest annual income statement
const latestIncome = financials.incomeStatement[0];
console.log('Revenue:', latestIncome.totalRevenue);
console.log('Net Income:', latestIncome.netIncome);
Options Data
Get options chains with Greeks:
Python Example
def get_options_chain(symbol, expiration_date=None):
"""Get options chain for a symbol."""
ticker = yf.Ticker(symbol)
# Get available expiration dates
expirations = ticker.options
print(f"Available expirations: {expirations[:5]}...")
# Use first expiration if not specified
exp_date = expiration_date or expirations[0]
# Get options chain
opt = ticker.option_chain(exp_date)
return {
'expiration': exp_date,
'calls': opt.calls,
'puts': opt.puts
}
# Get options for Apple
options = get_options_chain('AAPL')
print(f"\nOptions expiring {options['expiration']}:")
print(f"Calls: {len(options['calls'])} contracts")
print(f"Puts: {len(options['puts'])} contracts")
# Show top 5 calls by volume
top_calls = options['calls'].nlargest(5, 'volume')[['strike', 'lastPrice', 'volume', 'openInterest', 'impliedVolatility']]
print("\nTop 5 calls by volume:")
print(top_calls)
Analyst Recommendations
Get analyst ratings and price targets:
Python Example
def get_analyst_data(symbol):
"""Get analyst recommendations and price targets."""
ticker = yf.Ticker(symbol)
return {
'recommendations': ticker.recommendations,
'upgrades_downgrades': ticker.upgrades_downgrades,
'analyst_price_targets': ticker.analyst_price_targets
}
data = get_analyst_data('AAPL')
# Recent recommendations
print("Recent Analyst Actions:")
print(data['recommendations'].tail(10))
# Price targets
targets = data['analyst_price_targets']
print(f"\nPrice Targets:")
print(f" Low: ${targets['low']}")
print(f" Mean: ${targets['mean']}")
print(f" High: ${targets['high']}")
print(f" Current: ${targets['current']}")
Building a Stock Dashboard API
Complete example of a stock data API:
const express = require('express');
const yahooFinance = require('yahoo-finance2').default;
const app = express();
// Get stock quote
app.get('/api/quote/:symbol', async (req, res) => {
try {
const quote = await yahooFinance.quote(req.params.symbol);
res.json({
symbol: quote.symbol,
name: quote.shortName,
price: quote.regularMarketPrice,
change: quote.regularMarketChange,
changePercent: quote.regularMarketChangePercent,
volume: quote.regularMarketVolume,
marketCap: quote.marketCap,
peRatio: quote.trailingPE,
dayRange: `${quote.regularMarketDayLow} - ${quote.regularMarketDayHigh}`,
yearRange: `${quote.fiftyTwoWeekLow} - ${quote.fiftyTwoWeekHigh}`
});
} catch (error) {
res.status(404).json({ error: 'Symbol not found' });
}
});
// Get historical data
app.get('/api/history/:symbol', async (req, res) => {
try {
const { period = '1y', interval = '1d' } = req.query;
const endDate = new Date();
const startDate = new Date();
// Parse period
const periodMap = {
'1d': 1, '5d': 5, '1mo': 30, '3mo': 90,
'6mo': 180, '1y': 365, '2y': 730, '5y': 1825
};
startDate.setDate(endDate.getDate() - (periodMap[period] || 365));
const history = await yahooFinance.historical(req.params.symbol, {
period1: startDate,
period2: endDate,
interval
});
res.json(history.map(d => ({
date: d.date.toISOString().split('T')[0],
open: d.open,
high: d.high,
low: d.low,
close: d.close,
volume: d.volume
})));
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Search stocks
app.get('/api/search', async (req, res) => {
try {
const { q } = req.query;
const results = await yahooFinance.search(q);
res.json(results.quotes.map(r => ({
symbol: r.symbol,
name: r.shortname || r.longname,
type: r.quoteType,
exchange: r.exchange
})));
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get company profile
app.get('/api/profile/:symbol', async (req, res) => {
try {
const summary = await yahooFinance.quoteSummary(req.params.symbol, {
modules: ['assetProfile', 'summaryDetail', 'price']
});
res.json({
name: summary.price.longName,
sector: summary.assetProfile.sector,
industry: summary.assetProfile.industry,
website: summary.assetProfile.website,
employees: summary.assetProfile.fullTimeEmployees,
description: summary.assetProfile.longBusinessSummary
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => console.log('Stock API running on port 3000'));
Rate Limiting and Best Practices
Implement Caching
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 60 }); // 60 second cache
async function getCachedQuote(symbol) {
const cacheKey = `quote:${symbol}`;
let quote = cache.get(cacheKey);
if (quote) return quote;
quote = await yahooFinance.quote(symbol);
cache.set(cacheKey, quote);
return quote;
}
Rate Limiting
import time
from functools import wraps
def rate_limit(max_per_second=2):
"""Decorator to rate limit function calls."""
min_interval = 1.0 / max_per_second
last_called = [0.0]
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
elapsed = time.time() - last_called[0]
wait_time = min_interval - elapsed
if wait_time > 0:
time.sleep(wait_time)
result = func(*args, **kwargs)
last_called[0] = time.time()
return result
return wrapper
return decorator
@rate_limit(max_per_second=2)
def get_stock_data(symbol):
return yf.Ticker(symbol).info
Alternative Finance APIs
| API | Free Tier | Best For |
|---|---|---|
| Alpha Vantage | 25 req/day | Technical indicators |
| Finnhub | 60 req/min | Real-time data |
| Polygon.io | 5 req/min | Options data |
| IEX Cloud | 50K msg/mo | Company data |
Conclusion
Yahoo Finance data provides comprehensive stock market information for building financial applications. Use yfinance (Python) or yahoo-finance2 (JavaScript) for reliable access to quotes, historical data, and financials.
Remember to implement caching and rate limiting to avoid being blocked, and consider paid APIs like Alpha Vantage or Finnhub for production applications requiring guaranteed uptime.
Related Resources: