Agent Class
The base class for all trading agents. Extend this class to implement your strategy.
Class Definition
class Agent:
universe: list[str]
risk_limits: dict
schedule: str
version: intClass Attributes
universe
List of ticker symbols to analyze. Defaults to an empty list.
universe = ["AAPL", "MSFT", "GOOGL"]
risk_limits
Dictionary of risk management constraints.
risk_limits = {
"max_position_size": 0.1, # Max 10% per position
"max_drawdown": 0.2, # Stop at 20% drawdown
"daily_loss_limit": 0.05, # Stop at 5% daily loss
"max_orders_per_tick": 50, # Limit order frequency
}
schedule
Execution frequency: "daily", "hourly", or "tick". Defaults to "daily".
schedule = "daily"
Methods
analyze(context: Context) -> None
Main method called on each tick. Implement your trading logic here.
Parameters
- context: The Context object providing access to data, orders, and tools
Example
def analyze(self, context: Context) -> None:
# Get price data
prices = context.data.prices(self.universe, lookback="30d")
# Calculate indicator
sma_20 = prices["close"].rolling(20).mean()
# Generate orders
for symbol in self.universe:
current_price = prices["close"][symbol].iloc[-1]
if current_price > sma_20[symbol].iloc[-1]:
context.orders.buy(symbol, quantity=100)initialize(context: Context) -> None
Optional method called once at agent start. Use for setup and caching.
Example
def initialize(self, context: Context) -> None:
# Cache reference data
self.sector_map = context.data.reference.get_sector_mapping()
# Pre-calculate indicators
self.lookback_period = 252 # 1 year of trading dayson_error(error: Exception, context: Context) -> None
Optional error handler. Called when an exception occurs in analyze().
Example
def on_error(self, error: Exception, context: Context) -> None:
# Log the error
context.log.error(f"Error in analyze: {error}")
# Optionally close all positions
context.orders.close_all_positions()Related APIs
- Context API — Access to data, orders, and tools
- Data API — Market and fundamental data access
- Orders API — Order management and execution