Skip to content

Portfolio Optimizer

AI-driven portfolio optimizer using correlation matrix and composite signals for allocation. Framework: LangChain + Python.

Live Output Preview

If you ran this bot right now, the API would return:

# Live API output — March 13, 2026
Market Regime: Mean-Reverting
Safety Score: 90.6 (HIGH)

Composite Signals:
  BTC: strong_sell (score: -0.312)\n  ETH: sell (score: -0.222)\n  SOL: sell (score: -0.294)\n  HYPE: sell (score: -0.217)\n
# The bot would use this data to make trading decisions

Complete Source Code

Copy this code, replace YOUR_API_KEY with your key, and run:

from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain.tools import tool
from langchain_openai import ChatOpenAI
import requests
import numpy as np

API_KEY = "YOUR_API_KEY"
BASE = "https://algotick.dev"

@tool
def get_correlation_matrix() -> str:
    """Get cross-asset correlation matrix for portfolio optimization."""
    resp = requests.get(f"{{BASE}}/v1/signals/correlation", params={{"api_key": API_KEY}})
    data = resp.json()
    matrix = data.get("matrix", {{}})
    lines = []
    coins = sorted(matrix.keys())
    lines.append("     " + "  ".join(f"{{c:>5}}" for c in coins))
    for a in coins:
        row = matrix.get(a, {{}})
        vals = "  ".join(f"{{row.get(b, 0):5.2f}}" for b in coins)
        lines.append(f"{{a:>5}} {{vals}}")
    return "\n".join(lines)

@tool
def get_all_signals() -> str:
    """Get composite signals and volatility for all coins."""
    comp = requests.get(f"{{BASE}}/v1/signals/composite",
                       params={{"api_key": API_KEY}}).json()
    result = []
    for sig in comp.get("signals", []):
        coin = sig.get("coin")
        vol = requests.get(f"{{BASE}}/v1/signals/volatility",
                          params={{"coin": coin, "api_key": API_KEY}}).json()
        v = vol.get("volatility", [])
        v = v[0] if isinstance(v, list) and v else {{}}
        rv = v.get("realized_vol", {{}})
        result.append(
            f"{{coin}}: score={{sig.get('composite_score', 0):.3f}}, "
            f"regime={{sig.get('regime', '?')}}, "
            f"vol_24h={{rv.get('24h', 0):.1f}}%"
        )
    return "\n".join(result)

@tool
def get_safety_score() -> str:
    """Get cross-signal safety and coherence for risk sizing."""
    resp = requests.get(f"{{BASE}}/v3/signals/safety",
                       params={{"api_key": API_KEY}}).json()
    return (f"Coherence: {{resp.get('coherence_score', 0)}} | "
            f"Level: {{resp.get('safety_level', '?')}} | "
            f"Recommendation: {{resp.get('recommendation', '?')}}")

tools = [get_correlation_matrix, get_all_signals, get_safety_score]
llm = ChatOpenAI(model="gpt-4o", temperature=0)

agent = create_openai_functions_agent(llm, tools, prompt=...)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

result = executor.invoke({{
    "input": "Optimize my crypto portfolio. Check correlations between all assets, "
    "get their composite signals and volatility, and check the safety score. "
    "Then recommend an optimal allocation that maximizes risk-adjusted returns "
    "while minimizing correlation-based concentration risk."
}})
print(result["output"])

Setup Instructions

  1. Get an API key from the API page
  2. Replace YOUR_API_KEY in the code above
  3. Install dependencies: pip install requests (Python) or npm install node-fetch (TypeScript)
  4. Run the script and monitor the output
  5. Connect your exchange API for live trading

API Endpoints Used

Framework
LangChain + Python
Data Source
Algo Tick API
# All endpoints used by this template:
curl -H "X-API-Key: YOUR_KEY" https://algotick.dev/v3/signals/regime
curl -H "X-API-Key: YOUR_KEY" https://algotick.dev/v1/signals/composite
curl -H "X-API-Key: YOUR_KEY" https://algotick.dev/v3/signals/safety
curl -H "X-API-Key: YOUR_KEY" https://algotick.dev/v1/signals/volatility?coin=BTC

Don't just stare at the dashboard. Automate it.

Every metric on this page is available via our sub-millisecond API.
Build trading bots, backtest strategies, and power AI agents with institutional-grade data.

Get API Key →

More Langchain Templates

Other Frameworks