Implementation:HKUDS AI Trader Calculate Portfolio Values
| Knowledge Sources | |
|---|---|
| Domains | Quantitative_Finance, Portfolio_Management |
| Last Updated | 2026-02-09 14:00 GMT |
Overview
Concrete tool for computing daily portfolio values from position records and price data.
Description
The calculate_portfolio_values function iterates over position entries, computing the market value of held stocks via get_price_at_date() and combining with cash to produce a DataFrame of daily portfolio values. It supports both equity and crypto markets via the is_crypto flag, which adjusts price lookup behavior.
Usage
Call with position records (loaded from position.jsonl) and price data (from load_all_price_files()) to produce the portfolio value DataFrame needed by calculate_metrics().
Code Reference
Source Location
- Repository: AI-Trader
- File: tools/calculate_metrics.py
- Lines: L146-191
Signature
def calculate_portfolio_values(positions, price_data, is_crypto=False, verbose=True):
"""
Compute daily portfolio values from positions and price data.
Args:
positions: List of position dicts from position.jsonl
price_data: Dict mapping symbol to price data (from load_all_price_files)
is_crypto: If True, adjusts price lookup for crypto symbols
verbose: If True, prints progress info
Returns:
pd.DataFrame with columns: date, cash, stock_value, total_value
"""
Import
from tools.calculate_metrics import calculate_portfolio_values, load_all_price_files
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| positions | List[dict] | Yes | Position records from position.jsonl |
| price_data | Dict[str, dict] | Yes | Symbol-to-price-data mapping from load_all_price_files() |
| is_crypto | bool | No | Crypto mode flag (default False) |
| verbose | bool | No | Print progress (default True) |
Outputs
| Name | Type | Description |
|---|---|---|
| portfolio_df | pd.DataFrame | Columns: date, cash, stock_value, total_value |
Usage Examples
Compute Portfolio Values
from tools.calculate_metrics import calculate_portfolio_values, load_all_price_files
import json
# Load position log
with open("data/agent_data/gpt-4o/position/position.jsonl") as f:
positions = [json.loads(line) for line in f]
# Load all price files
price_data = load_all_price_files("data/")
# Calculate portfolio values
df = calculate_portfolio_values(positions, price_data)
print(df[["date", "total_value"]].tail())
# Output:
# date total_value
# 60 2025-03-28 11234.56
# 61 2025-03-31 11189.23