Trading in India, whether in stocks, commodities, or cryptocurrencies, revolves around data. From NSE tickers to API responses from brokers handling structured and error-free data is essential for successful trades. This is where Pydantic becomes a powerful ally. It ensures that your data is validated, parsed, and reliable, saving you from costly mistakes.
In this blog, we’ll explore how Pydantic can simplify trading workflows, with examples tailored for Indian markets.
Why Pydantic Matters for Traders?
Trading in India comes with unique challenges:
1. Multiple asset classes: Equity (NSE, BSE), commodities (MCX), and cryptocurrencies (Binance, CoinDCX).
2. Complex data: Instruments like NIFTY50 options or commodity futures involve timestamps, decimals, and tickers.
3. Diverse data sources: Broker APIs , JSON data files, and CSV exports.
Pydantic:
• Automates data validation, reducing manual work.
• Handles formats like timestamps, decimals, and nested data structures.
• Ensures error-free configurations for trading bots and algorithms.
Without Pydantic, traders face inefficiencies and higher risks due to the lack of automated data validation and structured error handling. This leads to issues like inconsistent data formats, increased debugging time, and potential calculation errors, especially with financial data like trade quantities and prices. Manual validation is time-consuming, error-prone, and difficult to scale as trading setups grow. Moreover, invalid configurations in trading bots can result in operational failures. Pydantic simplifies these challenges by automating validation, ensuring data integrity, and reducing development overhead.
Installing Pydantic
Start by installing Pydantic with pip:
pip install pydantic
With this, you’re ready to unlock its capabilities.
Examples Tailored for Traders
1. Validating Trade Data
Trading data often comes from APIs, files, or databases. Let’s validate a single trade record.
from pydantic import BaseModel
from decimal import Decimal
from datetime import datetime
class Trade(BaseModel):
order_id: str
symbol: str
quantity: Decimal
price: Decimal
timestamp: datetime
# Sample data
trade_data = {
"order_id": "20443567512",
"symbol": "RELIANCE",
"quantity": "100",
"price": "1220.45",
"timestamp": "2024-11-21T14:00:00"
}
trade = Trade(**trade_data)
print(trade)
What does this do?
• Validates quantity and price as decimals (critical for trading calculations).
• Converts timestamp into a Python datetime object for easy manipulation.
• Ensures all fields are present and correctly formatted.
2. Managing a Portfolio with Indian Stocks
For a portfolio of Indian stocks, Pydantic makes handling multiple positions seamless.
from typing import List
class Position(BaseModel):
symbol: str
exchange: str
average_price: Decimal
quantity: Decimal
class Portfolio(BaseModel):
owner: str
positions: List[Position]
# Example portfolio with NSE stocks
portfolio_data = {
"owner": "Amit Sharma",
"positions": [
{"symbol": "INFY", "exchange": "NSE", "average_price": "1435.50", "quantity": "20"},
{"symbol": "TCS", "exchange": "BSE", "average_price": "3650.75", "quantity": "10"}
]
}
portfolio = Portfolio(**portfolio_data)
print(portfolio)
This ensures:
• Each position is validated for its symbol, exchange, price, and quantity.
• Errors like missing fields or incorrect data formats are flagged immediately.
3. Validating API Responses from Indian Brokers
When working with Indian brokers like Zerodha , Fyers or Upstox, validating API responses ensures the data integrity of your trading applications.
class ApiResponse(BaseModel):
status: str
data: List[Trade]
# Sample API response from the Broker
api_response_data = {
"status": "success",
"data": [
{"trade_id": "T123", "symbol": "HDFCBANK", "exchange": "NSE", "quantity": "50", "price": "1600.00", "timestamp": "2024-11-21T14:00:00"},
{"trade_id": "T124", "symbol": "ITC", "exchange": "NSE", "quantity": "100", "price": "450.20", "timestamp": "2024-11-21T14:15:00"}
]
}
response = ApiResponse(**api_response_data)
print(response)
This validates:
• The status field and ensures it matches your expectations (e.g., success or failure).
• The list of trades, checking each against the Trade model.
4. Enforcing Exchange Rules with Custom Validation
Indian traders must adhere to regulations like minimum lot sizes for options or futures. Use Pydantic to enforce such rules.
from pydantic import validator
class TradeWithRules(BaseModel):
symbol: str
quantity: Decimal
price: Decimal
segment: str
@validator("quantity")
def check_min_lot_size(cls, value, values):
if values.get("segment") == "F&O" and value < 75:
raise ValueError("Quantity must meet the minimum lot size for F&O.")
return value
# Testing with invalid data
try:
trade = TradeWithRules(symbol="NIFTY", quantity=Decimal("10"), price=Decimal("20000.50"), segment="F&O")
except ValueError as e:
print(e)
This example enforces the minimum lot size of 75 for F&O trades, as per SEBI guidelines.
5. Configuring an Algo Trading Bot
class BotConfig(BaseModel):
api_key: str
secret_key: str
trading_pairs: List[str]
max_positions: int = 5 # Default value
risk_per_trade: float
# Example configuration for a Trading bot
config_data = {
"api_key": "your_broker_api_key",
"secret_key": "your_broker_secret_key",
"trading_pairs": ["INFY", "TCS"],
"risk_per_trade": 0.02
}
bot_config = BotConfig(**config_data)
print(bot_config)
Pydantic ensures:
• Critical fields like api_key and risk_per_trade are present.
• Data is correctly formatted, reducing runtime errors.
Handling Errors Gracefully
Pydantic provides clear error messages when validation fails. For example:
{
"loc": ["quantity"],
"msg": "value is not a valid decimal",
"type": "value_error.decimal"
}
Key Benefits for Traders
1. Simplified Data Validation: Automates the validation of NSE/BSE Exchanges trade data, API responses, and bot configurations.
2. Enhanced Accuracy: Ensures your trading data meets Exchange rules and standards.
3. Scalability: Handles complex portfolios and multi-asset trading setups.
4. Error Transparency: Provides actionable error messages, saving debugging time.
Pydantic is an indispensable tool for Indian traders looking to simplify data management and ensure reliability. By automating validation for trade records, portfolios, and bot configurations, Pydantic saves time and reduces errors. Whether you’re a retail trader using Zerodha or an algo trader building strategies, Pydantic empowers you to work smarter with your data.
Start using Pydantic today, and experience its impact firsthand!