Python Stock Price API
Fetching stock price data is the foundation of any financial Python project. This tutorial covers three different APIs and methods, with complete code you can copy and run immediately.
Install Dependencies
pip install yfinance requests pandasMethod 1: yfinance (Easiest)
yfinance is the most popular library for stock data in Python. It scrapes Yahoo Finance data and provides a clean pandas DataFrame. No API key needed.
import yfinance as yf
# Get stock data for Apple
stock = yf.Ticker("AAPL")
# Current price
info = stock.info
print(f"Current Price: ${info['currentPrice']}")
print(f"Market Cap: ${info['marketCap']:,.0f}")
print(f"P/E Ratio: {info['trailingPE']:.2f}")
print(f"52W High: ${info['fiftyTwoWeekHigh']}")
print(f"52W Low: ${info['fiftyTwoWeekLow']}")Historical Data
Get OHLCV (Open, High, Low, Close, Volume) data for any time period and interval.
# Historical data
history = stock.history(period="1y")
print(history.head())
# Open High Low Close Volume
# Date
# 2024-05-15 189.51 191.05 189.26 190.90 54321000
# 2024-05-16 190.47 191.10 189.66 189.84 45678000
# ...
# Different periods: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max
# Different intervals: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1moMultiple Stocks at Once
# Multiple stocks at once
import pandas as pd
tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"]
data = yf.download(tickers, period="1y", group_by="ticker")
# Get closing prices for all stocks
closes = pd.DataFrame()
for ticker in tickers:
closes[ticker] = data[ticker]["Close"]
print(closes.tail())
# Calculate daily returns
returns = closes.pct_change().dropna()
print("\nAverage Daily Returns:")
print(returns.mean() * 252) # AnnualisedMethod 2: Alpha Vantage API
Alpha Vantage provides free API access with a key. Rate limited to 5 requests per minute on the free tier, but offers more data types including forex, crypto, and fundamentals.
# Alpha Vantage API (free, rate-limited)
import requests
API_KEY = "YOUR_API_KEY" # Get free key at alphavantage.co
symbol = "AAPL"
url = f"https://www.alphavantage.co/query"
params = {
"function": "TIME_SERIES_DAILY",
"symbol": symbol,
"apikey": API_KEY,
"outputsize": "compact" # Last 100 data points
}
response = requests.get(url, params=params)
data = response.json()
time_series = data["Time Series (Daily)"]
for date, values in list(time_series.items())[:5]:
print(f"{date}: Open={values['1. open']}, Close={values['4. close']}")Save Data to CSV
# Save to CSV for later analysis
import yfinance as yf
stock = yf.Ticker("AAPL")
history = stock.history(period="5y")
# Save to CSV
history.to_csv("aapl_5year.csv")
print(f"Saved {len(history)} rows to aapl_5year.csv")
# Read it back
import pandas as pd
df = pd.read_csv("aapl_5year.csv", index_col="Date", parse_dates=True)
print(f"\nLatest price: ${df['Close'].iloc[-1]:.2f}")
print(f"5-year return: {((df['Close'].iloc[-1] / df['Close'].iloc[0]) - 1) * 100:.1f}%")Which API Should You Use?
- yfinance: best for quick prototyping and personal projects. Free, no key needed, good enough for most use cases.
- Alpha Vantage: best for projects needing fundamental data or forex/crypto. Free tier is limited but sufficient for learning.
- Polygon.io: best for production applications needing real-time data. Free tier gives 5 API calls/min, paid plans offer websockets and tick data.