How to Intermediate · 4 min read

How to analyze portfolio with AI

Quick answer
Use Python with an AI language model like gpt-4o to analyze portfolio data by feeding it asset allocations, historical returns, and risk metrics. The AI can generate insights, risk assessments, and optimization suggestions based on your input data.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the openai Python package and set your API key as an environment variable for secure access.

bash
pip install openai
output
Collecting openai
  Downloading openai-1.x.x-py3-none-any.whl (xx kB)
Installing collected packages: openai
Successfully installed openai-1.x.x

Step by step

Load your portfolio data, format it as a prompt, and send it to the gpt-4o model to get analysis and recommendations.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

portfolio_data = {
    "assets": [
        {"symbol": "AAPL", "allocation": 0.4, "return": 0.12, "volatility": 0.25},
        {"symbol": "TSLA", "allocation": 0.3, "return": 0.18, "volatility": 0.4},
        {"symbol": "BND", "allocation": 0.3, "return": 0.05, "volatility": 0.1}
    ],
    "total_value": 100000
}

prompt = f"Analyze this portfolio: {portfolio_data}. Provide risk assessment, diversification advice, and optimization suggestions."

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}]
)

print("Portfolio analysis:\n", response.choices[0].message.content)
output
Portfolio analysis:
The portfolio has a moderate risk profile due to the high volatility of TSLA (40%). The allocation to bonds (BND) at 30% helps reduce overall risk. Consider diversifying further by adding international equities or lower-volatility assets. Optimization could involve reducing TSLA allocation to 20% and increasing bonds or stable dividend stocks to improve risk-adjusted returns.

Common variations

You can use asynchronous calls for faster response handling, stream partial outputs for large analyses, or switch to other models like claude-3-5-sonnet-20241022 for different styles of financial advice.

python
import asyncio
import os
from openai import OpenAI

async def analyze_portfolio_async():
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    portfolio_data = {
        "assets": [
            {"symbol": "AAPL", "allocation": 0.4, "return": 0.12, "volatility": 0.25},
            {"symbol": "TSLA", "allocation": 0.3, "return": 0.18, "volatility": 0.4},
            {"symbol": "BND", "allocation": 0.3, "return": 0.05, "volatility": 0.1}
        ],
        "total_value": 100000
    }
    prompt = f"Analyze this portfolio: {portfolio_data}. Provide risk assessment and optimization suggestions."

    response = await client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}]
    )
    print("Async portfolio analysis:\n", response.choices[0].message.content)

asyncio.run(analyze_portfolio_async())
output
Async portfolio analysis:
The portfolio shows concentration risk in TSLA with 30% allocation and high volatility. To reduce risk, consider reallocating 10% from TSLA to bonds or diversified ETFs. Overall, the portfolio is moderately balanced but could benefit from international diversification.

Troubleshooting

  • If you get authentication errors, verify your OPENAI_API_KEY environment variable is set correctly.
  • If the response is incomplete, try increasing max_tokens in the API call.
  • For rate limits, implement exponential backoff retries.

Key Takeaways

  • Use structured portfolio data as input to AI models for meaningful financial analysis.
  • OpenAI's gpt-4o is effective for generating risk and diversification insights.
  • Async and streaming API calls improve responsiveness for large or complex portfolio queries.
  • Always secure your API key via environment variables to avoid leaks.
  • Adjust max_tokens and handle rate limits to ensure smooth API usage.
Verified 2026-04 · gpt-4o, claude-3-5-sonnet-20241022
Verify ↗