Skip to content

Portfolio API Reference

The portfolio object provides access to your trading account information, positions, and performance metrics during backtesting.

Properties

Basic Account Info

python
# Current cash available
cash = portfolio.cash

# Total account equity (cash + position values)
equity = portfolio.equity

# Initial starting capital
initial_capital = portfolio.initial_capital

Position Management

python
# Get current position in a symbol
position = portfolio.position('AAPL')  # Returns number of shares

# Check if you have any position
has_position = portfolio.position('AAPL') > 0

# Get all current positions
all_positions = portfolio.positions  # Dict: {'AAPL': 100, 'GOOGL': 50}

Performance Metrics

python
# Total return in dollars
total_return = portfolio.total_return

# Total return as percentage
return_pct = portfolio.total_return_pct

# Current profit/loss on open positions
unrealized_pnl = portfolio.unrealized_pnl

# Profit from closed trades
realized_pnl = portfolio.realized_pnl

Methods

position(symbol)

Returns the current position (number of shares) for a given symbol.

Parameters:

  • symbol (str): The stock symbol to check

Returns:

  • int: Number of shares held (0 if no position)

Example:

python
def strategy(data_contexts, portfolio, state):
    current_pos = portfolio.position('AAPL')
    
    if current_pos == 0:
        # No position, consider buying
        return {'symbol': 'AAPL', 'action': 'buy', 'quantity': 100}
    elif current_pos > 0:
        # Have position, consider selling
        return {'symbol': 'AAPL', 'action': 'sell', 'quantity': 'all'}

Complete Example

python
def strategy(data_contexts, portfolio, state):
    """Example showing portfolio usage"""
    
    # Portfolio diagnostics
    print(f"Cash: ${portfolio.cash:,.2f}")
    print(f"Equity: ${portfolio.equity:,.2f}")
    print(f"Return: {portfolio.total_return_pct:.2f}%")
    
    # Position management
    aapl_pos = portfolio.position('AAPL')
    
    if aapl_pos == 0:
        # Only buy if we have enough cash
        if portfolio.cash >= 15000:  # $150/share * 100 shares
            return {'symbol': 'AAPL', 'action': 'buy', 'quantity': 100}
    
    elif aapl_pos > 0:
        # Exit if we're up 10% on total portfolio
        if portfolio.total_return_pct >= 10.0:
            return {'symbol': 'AAPL', 'action': 'sell', 'quantity': 'all'}
    
    return None

See also: DataContext API | Order Functions | Strategy Examples

Test your trading strategies risk-free with professional backtesting.