Real-Time Data for Trading
Algorithmic trading requires real-time market data. Here are the best methods in Python.
Free Data Sources
1. yfinance
import yfinance as yf
data = yf.Ticker('RELIANCE.NS')
data.info # Current price2. Alpha Vantage
import requests
url = 'https://www.alphavantage.co/query'
params = {'function': 'TIME_SERIES_INTRADAY', 'symbol': 'RELIANCE', 'interval': '1min'}
data = requests.get(url, params=params).json()Paid Data Sources
1. TrueData (Indian Markets)
from truedata import TD
td = TD('username', 'password')
td.connect()
data = td.get_live_data('RELIANCE')2. Bloomberg API
import bloomberg
session = bloomberg.Session()
data = session.get_historical('RELIANCE IN Equity')WebSocket Streaming
import websocket
import json
def on_message(ws, message):
data = json.loads(message)
print(data)
ws = websocket.WebSocketApp('wss://stream.binance.com/ws', on_message=on_message)
ws.run_forever()Recommendation
- Learning: yfinance (free, easy)
- Indian markets: TrueData (paid, real-time)
- Crypto: Binance WebSocket (free)
SEBI Disclaimer
Data feeds may have delays. Verify before trading. This article is for educational purposes only.
The Challenge of Keep Stock Data Fresh
A live trading system needs prices that arrive with minimal delay, because a stale quote is worse than none when a strategy is acting on the market's current state. Real-time data in Python spans a spectrum from simple periodic polling of a REST API to continuous streaming over a WebSocket, and the right choice depends on the strategy's horizon, the data's cost and the latency budget. Understanding that spectrum is the first step to building a robust live-data layer.
The trade-off is between simplicity and freshness. Polling a REST endpoint at fixed intervals is easy to code and reliable, but it introduces a lag equal to the polling period and can hit rate limits under heavy use. Streaming over a WebSocket pushes updates the moment they occur, giving near-instant prices at the cost of more complex handling of connection state, reconnection and message parsing. A professional system usually combines both: stream fast instruments, poll or batch others.
The Data Sources Available
- Free REST APIs: convenient for research and low-frequency charts, with rate limits and daily caps.
- Paid market-data feeds: reliable, low-latency and essential for latency-sensitive trading.
- WebSocket streams: push-to-client updates for real-time tick, trade and order book data.
- Exchange feeds: the authoritative, lowest-latency source, usually for institutions.
Polling with a REST API
For a strategy that acts on one-minute or five-minute bars, polling a REST endpoint on that cadence is a sound, simple choice. The developer requests the latest candle or quote, checks its timestamp and reacts if it is new. Because the code is straightforward and the failure mode is a manageable request error, REST polling is a low-risk way to start. The limitation is the polling latency itself and the possibility of rate limiting, so the request rate must stay within the provider's allowed window.
Streaming with WebSockets
For tick-level or order-book-driven work, a WebSocket connection is the correct tool. The client connects once, subscribes to the instruments it cares about and receives a continuous flow of messages as prices change. The developer must handle asynchronous message processing, connection drops and reconnection, and heartbeat logic, which adds complexity but delivers the fresh data a sub-second strategy demands. The payoff is that decisions are based on the market as it is now, not as it was a moment ago.
Building a Robust Streaming Client
- Connect and authenticate to the provider's WebSocket endpoint.
- Subscribe to the required symbol and message types.
- Parse each message into a structured quote or trade object.
- Handle disconnects with automatic reconnection and resubscription.
- Buffer and compute rolling statistics for features without blocking the stream.
Latency and Quality Considerations
Not all "real-time" data is equally real. Feeds delivered over the public internet add network latency and can be several hundred milliseconds behind an exchange colocated feed. For all but the fastest strategies this is acceptable, but the developer should measure the actual end-to-end delay and decide whether it fits the trading horizon. Equally important is data quality: dropped messages, gaps and out-of-order timestamps corrupt features, so a robust handler detects and reconciles such anomalies.
Choosing the Right Data Architecture
The data layer should match the strategy and not over-engineer it. A slow, mean-reverting strategy only needs periodic bars and a modest feed; a fast market-maker needs the tightest streaming feed available. Between these extremes, a hybrid works well: stream the instruments you trade and poll the rest on a schedule, storing everything to a local database for backtesting and later analysis. Matching the latency of the feed to the speed of the strategy is the practical definition of the right data architecture.
Real-time Python data is a solved problem if the layers are chosen deliberately. Poll for simplicity and low frequency, stream for speed, and connect the whole feed to a robust handler that survives reconnects and guards data quality. The trader who builds this foundation well gets decisions grounded in fresh, reliable prices rather than stale snapshots, which is the difference between a system that reacts and one that reacts late.