0Pricing
AI Agents · Lesson

Portfolio Analysis Agent Tools

Returns calculation, Sharpe ratio, drawdown analysis via agent-executed code.

Portfolio Analysis as Agent Tools

Financial analysis agents need a suite of calculation tools the LLM can call: returns, risk metrics, correlation, and rebalancing suggestions. Each tool is a Python function with a clear signature and returns structured JSON the agent can reason over.

Calculating Percentage Returns

The foundation of portfolio analysis. pct_change() computes day-over-day returns. From these, calculate cumulative return over the analysis period.

import pandas as pd
import yfinance as yf

def calculate_returns(ticker: str, period: str = '1y') -> dict:
    hist = yf.Ticker(ticker).history(period=period)['Close']
    if hist.empty:
        return {'error': f'No data for {ticker}'}

    daily_returns = hist.pct_change().dropna()
    cumulative    = (1 + daily_returns).cumprod() - 1

    return {
        'ticker':            ticker,
        'period':            period,
        'total_return_pct':  round(float(cumulative.iloc[-1]) * 100, 2),
        'avg_daily_return':  round(float(daily_returns.mean()) * 100, 4),
        'best_day_pct':      round(float(daily_returns.max()) * 100, 2),
        'worst_day_pct':     round(float(daily_returns.min()) * 100, 2)
    }

All lessons in this course

  1. Market Data API Integration
  2. Portfolio Analysis Agent Tools
  3. Risk and Compliance Guardrails
  4. Backtesting Agent Decisions
← Back to AI Agents