Skip to content
Connect > Client Libraries > Python Client > Use Cases

Use Case: Quant Analytics with pandas

This use case builds a Python analysis that takes a price history from 3forge Enterprise into pandas and writes volatility figures back.

Prerequisites

  • Python 3.14 with the pyami-3forge package. See the Python client.
  • A client certificate the server accepts, with client.crt.pem, client.key.pem, and the server's 3forge.pub in the working directory. See Connecting and Securing a Client.

How it fits together

The program works in 4 steps:

  1. Drop any earlier QuantPrices and QuantVolatility tables, then upload a toy history of 60 trading days for 3 symbols with sql_insert, which creates QuantPrices.
  2. Read the history into a DataFrame with pandas.read_sql_query, through the SQLAlchemy dialect.
  3. Compute the statistics in pandas and upload them with sql_insert, which creates QuantVolatility.
  4. Read back the most volatile symbols with the query builder.

The day is stored as an integer, such as 20260102. A pandas datetime column would be stored as text; see Data that does not upload as expected.

1. Create the connection helper

The program connects through a helper that opens only the connections it asks for.

  1. Save the following code as connect.py in the working directory:

    from pyami.rt.ami_client import (AmiClient, AmiCluster, AmiDatabaseConfig,
                                     AmiPublicationConfig, AmiSslOptions,
                                     AmiSubscriptionConfig, Options)
    
    HOST = "localhost"
    KEYS = AmiSslOptions(trusted_server_pub_file="3forge.pub",
                         client_cert_file="client.crt.pem",
                         client_key_file="client.key.pem")
    
    
    def connect(listener, sql=False, center=False, relay=False, login_id="my_app"):
        """Return a client with cluster "N1" connected to the requested listeners."""
        cluster = AmiCluster("N1", HOST)
        if sql:
            config = AmiDatabaseConfig("3280", True, "demo", "demo123")
            config.shards[0].ssl = KEYS
            cluster.database_config = config
        if center:
            config = AmiSubscriptionConfig("3270", True)
            config.shards[0].ssl = KEYS
            cluster.subscription_config = config
        if relay:
            config = AmiPublicationConfig("3289", True, login_id, int(Options.UNIX_MODE))
            config.shards[0].ssl = KEYS
            cluster.publication_config = config
        client = AmiClient()
        client.add_listener(listener)
        client.add_cluster(cluster, sync=True)
        return client
    
  2. Confirm that the helper imports: run python -c "import connect", and the command returns with no output.

2. Write the analysis

The analysis generates the history, then does the 4 steps above in order.

  1. Save the following code as analytics.py, beside connect.py. The program runs in stage 3:

    import math
    from urllib.parse import quote
    
    import numpy as np
    import pandas as pd
    import sqlalchemy as sa
    from pyami.query import col, desc
    
    from connect import connect
    
    
    class Listener:
        def on_log(self, client, name, level, message):
            if level >= 3:
                print("error:", name, message)
    
    
    client = connect(Listener(), sql=True)
    for table in ("QuantVolatility", "QuantPrices"):
        client.sql("N1", f"DROP TABLE IF EXISTS {table}")
    
    # 1. Load a toy price history: 60 trading days for 3 symbols.
    rng = np.random.default_rng(7)
    days = pd.bdate_range("2026-01-02", periods=60)
    history = pd.DataFrame([
        {"day": int(day.strftime("%Y%m%d")), "sym": sym, "close": float(round(start * math.exp(step), 2))}
        for sym, start, vol in [("IBM", 183.0, 0.010), ("AAPL", 201.0, 0.015), ("MSFT", 412.0, 0.012)]
        for day, step in zip(days, np.cumsum(rng.normal(0, vol, len(days))))
    ])
    print(client.sql_insert("N1", "QuantPrices", history))
    
    # 2. Read it into pandas through SQLAlchemy.
    url = ("ami+jdbc://demo:demo123@localhost:3280/"
           f"?trusted_server_pub_file={quote('3forge.pub')}"
           f"&client_cert_file={quote('client.crt.pem')}"
           f"&client_key_file={quote('client.key.pem')}")
    engine = sa.create_engine(url)
    with engine.connect() as conn:
        prices = pd.read_sql_query("SELECT day, sym, close FROM QuantPrices", conn)
    
    # 3. Compute daily returns and annualized volatility per symbol.
    prices = prices.sort_values(["sym", "day"])
    prices["ret"] = prices.groupby("sym")["close"].pct_change()
    stats = (prices.groupby("sym")["ret"]
             .agg(mean_return="mean", volatility="std")
             .reset_index())
    stats["volatility"] = stats["volatility"] * math.sqrt(252)
    
    # 4. Write the results back, and read them with the query builder.
    print(client.sql_insert("N1", "QuantVolatility", stats))
    print(client.select("N1", ["sym", "volatility"], "QuantVolatility",
                        where=col("volatility") > 0.15, order_by=desc("volatility"), as_frame=True))
    
    for table in ("QuantVolatility", "QuantPrices"):
        client.sql("N1", f"DROP TABLE {table}")
    client.remove_cluster("N1", sync=True)
    

3. Run it

This stage runs the analysis and checks what it uploads and reads back.

  1. Run the program: python analytics.py.
  2. Check that it prints the 2 uploads, then the symbols whose volatility is above 15%:

    1
    2
    3
    4
    5
    {'rows_affected': 180}
    {'rows_affected': 3}
        sym  volatility
    0  AAPL    0.202342
    1  MSFT    0.173709
    

The history is generated from a fixed seed, so the figures are the same on every run.

Result

The program moved data from 3forge Enterprise into pandas and back: 180 prices out, 3 statistics in, read back with a filter. It drops both tables before it exits.