AI Financial Analysis API Tutorial: Build a Python Stock Analysis Workflow

Build an AI financial analysis API in Python using daily market data, deterministic return and volatility calculations, and structured AI output.

ASOasis
6 min read
AI Financial Analysis API Tutorial: Build a Python Stock Analysis Workflow

Image used for representation purposes only.

What You’ll Build

This tutorial builds a small AI financial analysis API workflow in Python. It retrieves a stock’s recent daily prices, calculates a few transparent performance measures, and asks a language model to explain those figures in a concise, structured response.

The design deliberately separates calculation from interpretation: Python calculates returns and volatility; the AI explains the supplied results. That makes the output easier to check than asking a model to derive financial metrics from raw figures. This is an educational example—not investment advice, a price forecast, or a production-ready financial service.

Architecture and Data Choices

The workflow uses Alpha Vantage’s TIME_SERIES_DAILY endpoint for daily open, high, low, close, and volume data, and the OpenAI Responses API for the narrative analysis. Alpha Vantage documents the daily endpoint as returning raw, as-traded prices; its separate daily-adjusted endpoint provides adjusted closing prices and historical split and dividend events. Check the provider’s access, freshness, and commercial-use terms before relying on the data in an application. (alphavantage.co )

The OpenAI Python SDK supports client.responses.create(...) and exposes generated text through response.output_text. This example requests JSON-formatted model output so the application can parse it rather than treating the response as an unstructured paragraph. (github.com )

The flow is:

  1. Fetch daily prices for one ticker.
  2. Validate and sort the returned observations.
  3. Calculate the 60-session return and annualized historical volatility.
  4. Send only the ticker, date range, and calculated metrics to the model.
  5. Return the model’s structured explanation alongside the metrics.

Set Up the Project

Use Python 3.10 or later. Install the required packages:

python -m pip install openai requests

Set your API keys as environment variables rather than putting them in source code:

export ALPHA_VANTAGE_API_KEY="your_alpha_vantage_key"
export OPENAI_API_KEY="your_openai_key"
export OPENAI_MODEL="your_available_model"

On Windows PowerShell, use $env:ALPHA_VANTAGE_API_KEY="your_alpha_vantage_key" and the equivalent syntax for the other variables. Choose a model available to your API account and set its identifier in OPENAI_MODEL.

Implement the Analysis

Save the following as analyze_stock.py:

import json
import math
import os
import statistics
import sys

import requests
from openai import OpenAI

ALPHA_VANTAGE_URL = 'https://www.alphavantage.co/query'


def get_daily_prices(symbol: str) -> list[tuple[str, float]]:
    api_key = os.environ['ALPHA_VANTAGE_API_KEY']
    response = requests.get(
        ALPHA_VANTAGE_URL,
        params={
            'function': 'TIME_SERIES_DAILY',
            'symbol': symbol,
            'outputsize': 'compact',
            'apikey': api_key,
        },
        timeout=20,
    )
    response.raise_for_status()
    payload = response.json()

    series = payload.get('Time Series (Daily)')
    if not series:
        message = payload.get('Note') or payload.get('Error Message') or str(payload)
        raise RuntimeError(f'No daily price series returned: {message}')

    # Keep the most recent 61 observations to calculate 60 session-to-session returns.
    observations = sorted(series.items())[-61:]
    prices = [(date, float(values['4. close'])) for date, values in observations]
    if len(prices) < 2:
        raise RuntimeError('At least two daily prices are required.')
    return prices


def calculate_metrics(prices: list[tuple[str, float]]) -> dict:
    closes = [close for _, close in prices]
    returns = [current / previous - 1 for previous, current in zip(closes, closes[1:])]
    period_return = closes[-1] / closes[0] - 1
    daily_volatility = statistics.stdev(returns) if len(returns) > 1 else 0.0

    return {
        'first_date': prices[0][0],
        'last_date': prices[-1][0],
        'observations': len(prices),
        'period_return_pct': round(period_return * 100, 2),
        'annualized_historical_volatility_pct': round(
            daily_volatility * math.sqrt(252) * 100, 2
        ),
        'latest_close': round(closes[-1], 2),
    }


def explain_with_ai(symbol: str, metrics: dict) -> dict:
    client = OpenAI()
    response = client.responses.create(
        model=os.environ['OPENAI_MODEL'],
        input=[
            {
                'role': 'system',
                'content': (
                    'Explain the supplied historical market metrics in plain English. '
                    'Do not predict prices, recommend trades, or invent facts. '
                    'Treat volatility as a measure of observed variability, not direction. '
                    'Return a JSON object with keys summary, observations, and caveats. '
                    'Make observations and caveats arrays of strings.'
                ),
            },
            {
                'role': 'user',
                'content': json.dumps({'symbol': symbol, 'metrics': metrics}),
            },
        ],
        text={'format': {'type': 'json_object'}},
    )
    return json.loads(response.output_text)


def main() -> None:
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python analyze_stock.py TICKER')

    symbol = sys.argv[1].strip().upper()
    prices = get_daily_prices(symbol)
    metrics = calculate_metrics(prices)
    analysis = explain_with_ai(symbol, metrics)

    print(json.dumps({
        'symbol': symbol,
        'metrics': metrics,
        'ai_analysis': analysis,
        'disclaimer': 'Educational information only; not investment advice.',
    }, indent=2))


if __name__ == '__main__':
    main()

Run it with a ticker supported by your data provider:

python analyze_stock.py IBM

The script requests the compact daily series, sorts observations chronologically, and uses up to 61 closes to calculate 60 daily returns. The period return compares the first and last close in that selected window. Annualized historical volatility is the sample standard deviation of daily returns multiplied by the square root of 252, a common trading-day convention. It describes variability over this historical window; it is not a forecast or a measure of whether the price moved up or down.

Understand the Output

The response contains three parts:

  • metrics: values calculated by Python, including the observed date range and latest close.
  • ai_analysis: a JSON object with a short summary, observations, and caveats.
  • disclaimer: a reminder about the intended educational use.

The model should explain the supplied calculations, not silently replace them. For stronger validation, check that the returned object contains exactly the expected keys and that observations and caveats are arrays of strings before displaying it to users. JSON-formatted output helps with parsing, but applications should still validate model responses and handle API errors.

Important Data and Safety Caveats

Raw prices can distort returns across corporate actions. This example uses the raw daily close series. A stock split or dividend can affect comparisons across dates, so use a suitable adjusted-price series when your analysis requires split- or dividend-adjusted returns. Confirm your provider’s endpoint availability and licensing before deploying; Alpha Vantage documents daily adjusted data separately from raw daily data. (alphavantage.co )

Data availability and freshness vary. The script handles a missing time series, but a real service should also account for provider rate limits, delayed or unavailable data, network timeouts, and ticker lookup errors. Include the data source and timestamp in any user-facing result, and never imply that an end-of-day observation is a real-time quote.

AI output needs boundaries. Keep calculations deterministic, provide the model only the context it needs, and instruct it not to issue forecasts or personalized recommendations. Treat generated explanations as fallible text: validate the JSON, log failures safely, and make it possible to inspect the underlying dates and metrics.

Protect credentials and user information. Keep API keys on the server, use environment-based secrets management in deployment, and avoid logging credentials. If you later analyze account balances or transaction data, minimize the sensitive information sent to external services and review the applicable privacy, security, and data-provider requirements.

Production Improvements

Before turning the example into a public API, add input validation for ticker symbols, retry and backoff for transient failures, caching to avoid redundant data requests, structured logs, and tests for return and volatility calculations. Consider returning the raw metric inputs and their date range so users can reproduce the results. For a broader analysis, add separately sourced fundamentals or filings, but label each metric with its source, reporting period, and units rather than blending data with different definitions.

The main principle is simple: use APIs to retrieve traceable data, code to calculate financial measures, and AI to explain those measures with clear limitations. That separation makes the resulting analysis more transparent, testable, and maintainable.

Related Posts