Appearance
Portfolio Context
The portfolio object provides access to your trading account state, positions, and performance metrics. It's available in all lifecycle functions.
Properties
Account State
cash(float) - Available cash for tradingequity(float) - Total portfolio value (cash + positions market value)buying_power(float) - Available buying power (same as cash currently)initial_capital(float) - Starting capital amount
Performance
total_return(float) - Total return as decimal (0.15 = 15% gain)
Methods
Position Information
position(symbol: str) -> int
Get current position size for a symbol.
python
# Check AAPL position
aapl_shares = portfolio.position('AAPL')
print(f"AAPL position: {aapl_shares} shares")
# Use in trading logic
if portfolio.position('AAPL') == 0:
# No position, can buy
return {"symbol": "AAPL", "action": "buy", "quantity": 100}positions() -> dict[str, int]
Get all current positions (only non-zero positions).
python
# Get all positions
current_positions = portfolio.positions()
print(f"Current positions: {current_positions}")
# Output: {'AAPL': 100, 'GOOGL': 50}
# Iterate over positions
for symbol, shares in portfolio.positions().items():
print(f"{symbol}: {shares} shares")Market Values
market_value(symbol: str) -> float
Get current market value of a position.
python
# Get AAPL position value
aapl_value = portfolio.market_value('AAPL')
print(f"AAPL position worth: ${aapl_value:,.2f}")
# Calculate position percentage
position_pct = aapl_value / portfolio.equity
print(f"AAPL is {position_pct*100:.1f}% of portfolio")unrealized_pnl(symbol: str = None) -> float
Get unrealized profit/loss for a symbol or total portfolio.
python
# Specific symbol P&L
aapl_pnl = portfolio.unrealized_pnl('AAPL')
if aapl_pnl < -1000:
# Stop loss triggered
return {"symbol": "AAPL", "action": "sell", "quantity": "all"}
# Total portfolio unrealized P&L
total_pnl = portfolio.unrealized_pnl()
print(f"Total unrealized P&L: ${total_pnl:,.2f}")Position Sizing
shares_for_dollars(symbol: str, dollars: float) -> int
Calculate how many shares you can buy with a given dollar amount.
python
# Buy $10,000 worth of AAPL
target_investment = 10000
aapl_shares = portfolio.shares_for_dollars('AAPL', target_investment)
return {
"symbol": "AAPL",
"action": "buy",
"quantity": aapl_shares
}
# Use all available cash
max_shares = portfolio.shares_for_dollars('AAPL', portfolio.cash)Usage Examples
Basic Position Check
python
def on_bar_close(data_contexts, portfolio, state):
aapl = data_contexts['AAPL']
# Check if we have a position
current_position = portfolio.position('AAPL')
if current_position == 0:
# No position - look for buy signal
if aapl.close > aapl.sma(20):
return {"symbol": "AAPL", "action": "buy", "quantity": 100}
else:
# Have position - look for sell signal
if aapl.close < aapl.sma(20):
return {"symbol": "AAPL", "action": "sell", "quantity": "all"}Portfolio Allocation
python
def on_bar_close(data_contexts, portfolio, state):
# Target 25% allocation to each symbol
target_allocation = 0.25
for symbol, data in data_contexts.items():
current_value = portfolio.market_value(symbol)
current_allocation = current_value / portfolio.equity
# Rebalance if allocation is off by more than 5%
if abs(current_allocation - target_allocation) > 0.05:
target_value = portfolio.equity * target_allocation
if current_value < target_value:
# Need to buy more
additional_dollars = target_value - current_value
shares_to_buy = portfolio.shares_for_dollars(symbol, additional_dollars)
return {
"symbol": symbol,
"action": "buy",
"quantity": shares_to_buy
}Risk Management
python
def on_bar_close(data_contexts, portfolio, state):
# Check all positions for stop losses
orders = []
for symbol, shares in portfolio.positions().items():
if shares > 0: # Long positions only
position_value = portfolio.market_value(symbol)
unrealized_pnl = portfolio.unrealized_pnl(symbol)
# 10% stop loss
if unrealized_pnl < -0.10 * position_value:
orders.append({
"symbol": symbol,
"action": "sell",
"quantity": "all"
})
print(f"Stop loss triggered for {symbol}: ${unrealized_pnl:.2f}")
return orders if orders else NonePerformance Monitoring
python
def on_market_close(portfolio, state, market_data):
# Daily performance summary
total_return = portfolio.total_return
daily_equity = portfolio.equity
print(f"Daily Summary:")
print(f" Total Equity: ${daily_equity:,.2f}")
print(f" Total Return: {total_return*100:.2f}%")
print(f" Cash: ${portfolio.cash:,.2f}")
print(f" Positions Value: ${daily_equity - portfolio.cash:,.2f}")
# Position breakdown
for symbol, shares in portfolio.positions().items():
value = portfolio.market_value(symbol)
pct = value / portfolio.equity
print(f" {symbol}: {shares} shares = ${value:,.2f} ({pct*100:.1f}%)")Dynamic Position Sizing
python
def on_bar_close(data_contexts, portfolio, state):
aapl = data_contexts['AAPL']
# Buy signal detected
if buy_signal(aapl):
# Size position based on portfolio size and volatility
base_allocation = 0.10 # 10% base allocation
volatility_adjustment = calculate_volatility_adjustment(aapl)
# Adjust for portfolio size (smaller positions for larger portfolios)
size_adjustment = min(1.0, 100000 / portfolio.equity)
final_allocation = base_allocation * volatility_adjustment * size_adjustment
target_dollars = portfolio.equity * final_allocation
# Make sure we have enough cash
available_dollars = min(target_dollars, portfolio.cash)
shares = portfolio.shares_for_dollars('AAPL', available_dollars)
if shares > 0:
return {
"symbol": "AAPL",
"action": "buy",
"quantity": shares
}Common Patterns
Safe Position Access
python
# Always check if position exists before using
current_pos = portfolio.position('AAPL')
if current_pos > 0:
# We have a long position
pass
elif current_pos < 0:
# We have a short position (if supported)
pass
else:
# No position
passPercentage-based Trading
python
# Trade fixed percentages of portfolio
portfolio_pct = 0.05 # 5% of portfolio
target_dollars = portfolio.equity * portfolio_pct
shares = portfolio.shares_for_dollars(symbol, target_dollars)Cash Management
python
# Always check available cash before buying
if portfolio.cash >= 10000: # Need at least $10k
shares = portfolio.shares_for_dollars(symbol, 10000)
# Safe to place orderImportant Notes
- Position values update automatically with market prices
- Cash is updated immediately when orders execute
- Unrealized P&L changes with market movement
- All monetary values are in USD
- Share quantities are always integers
- Use
"all"quantity to close entire positions