Problem Description
Solution
To retrieve portfolio metrics in QuantConnect using the Python API (PEP8 format), you access the self.portfolio object.
Key Properties
- Total Portfolio Value:
self.portfolio.total_portfolio_value- This represents the sum of your cash, the market value of all holdings, and unrealized profit/loss.
- Specific Holding Value:
self.portfolio[symbol].holdings_value- This represents the absolute market value of a specific asset (Price $\times$ Quantity).
Code Example
The following algorithm demonstrates how to access these values inside the on_data method.
from AlgorithmImports import *
class PortfolioValueDemo(QCAlgorithm):
def initialize(self):
self.set_start_date(2023, 1, 1)
self.set_end_date(2023, 2, 1)
self.set_cash(100000)
# Add an equity and save the Symbol object
self.spy = self.add_equity("SPY", Resolution.DAILY).symbol
def on_data(self, data: Slice):
# 1. Get Total Portfolio Value (Cash + Equity)
total_value = self.portfolio.total_portfolio_value
# 2. Get the value of a specific holding (SPY)
# This returns 0.0 if you do not hold the stock
spy_holding_value = self.portfolio[self.spy].holdings_value
# Log the values
self.log(f"Total Portfolio Value: ${total_value:.2f}")
self.log(f"SPY Position Value: ${spy_holding_value:.2f}")
# Simple logic to invest so we have a value to report
if not self.portfolio.invested:
self.set_holdings(self.spy, 1.0)
Additional Portfolio Properties
You can access other useful metrics through the specific security object within the portfolio (self.portfolio[symbol]):
quantity: The number of shares/contracts held (positive for long, negative for short).average_price: The average purchase price of the holding.unrealized_profit: The unrealized PnL for that specific asset.invested: A boolean (True/False) indicating if you currently hold a position in this asset.
Q&A
Q: What is the difference between total_portfolio_value and total_holdings_value?
A: total_portfolio_value includes your Cash balance plus the market value of your assets. total_holdings_value only includes the market value of the assets you are currently invested in, excluding cash.
Q: How do I handle the naming convention if I am using an older algorithm?
A: QuantConnect recently migrated to PEP8 (snake_case). If you are using an older version of LEAN or legacy code, you may see self.Portfolio.TotalPortfolioValue and self.Portfolio[symbol].HoldingsValue. New projects should use the lowercase snake_case format.
Q: Does holdings_value return a negative number for short positions?
A: No. holdings_value returns the absolute market value of the position. If you need to determine direction, check self.portfolio[symbol].is_short or look at the sign of self.portfolio[symbol].quantity.