← Blog
8 min read

Build an Autonomous Trading Agent with Python in 10 Minutes

From zero to a working trading agent that screens tickers, checks sentiment, verifies claims, and sets alerts. Copy-paste Python code with the Polaris SDK.

You don't need a Bloomberg terminal to build a trading agent. With the Polaris API and Python, you can screen tickers by natural language, check sentiment, verify claims, set price alerts, and backtest strategies — all in about 50 lines of code.

This tutorial builds a complete autonomous trading agent. Every code block is copy-pasteable. You'll have a working agent in 10 minutes.

Setup

bash
pip install polaris-news httpx
python
import httpx

API_KEY = "pr_live_xxx"  # Get free at thepolarisreport.com/pricing
BASE = "https://api.thepolarisreport.com"
HEADERS = {"X-API-Key": API_KEY, "Content-Type": "application/json"}

Step 1: Screen for Opportunities

Ask in plain English. The NLP screener translates your intent into structured filters and returns matching tickers.

python
def screen(query: str):
    """Natural language screener — describe what you want."""
    resp = httpx.post(f"{BASE}/api/v1/screener/natural",
        headers=HEADERS,
        json={"query": query, "limit": 10})
    data = resp.json()
    print(f"Interpreted: {data.get('interpreted_as')}")
    for r in data.get("results", []):
        print(f"  {r['ticker']} price={r.get('price',0):.2f} RSI={r.get('rsi_14','?')} Sent={r.get('sentiment_7d','?')}")
    return data["results"]

# Find oversold semiconductors
picks = screen("oversold semiconductor stocks near earnings")

Step 2: Check Sentiment + Technicals

python
def analyze(ticker: str):
    """Get composite score + technicals for a ticker."""
    score = httpx.get(f"{BASE}/api/v1/ticker/{ticker}/score",
        headers=HEADERS).json()
    print(f"{ticker}: signal={score['signal']} score={score['composite_score']:.3f}")
    print(f"  Sentiment: {score['components']['sentiment']['current_24h']}")
    print(f"  Momentum: {score['components']['momentum']['direction']}")
    return score

for pick in picks[:3]:
    analyze(pick["ticker"])

Step 3: Verify Before Acting

python
def verify(claim: str):
    """Fact-check a claim before trading on it."""
    resp = httpx.post(f"{BASE}/api/v1/verify",
        headers=HEADERS,
        json={"claim": claim})
    result = resp.json()
    print(f"Verdict: {result['verdict']} ({result['confidence']:.0%} confidence)")
    return result

# Verify before acting
verify("NVIDIA GPU demand is accelerating")

Step 4: Set Alerts

python
def set_alert(ticker: str, alert_type: str, threshold: float):
    """Set a price or RSI alert with optional webhook."""
    resp = httpx.post(f"{BASE}/api/v1/alerts",
        headers=HEADERS,
        json={
            "ticker": ticker,
            "alert_type": alert_type,
            "threshold": threshold,
            "callback_url": "https://your-webhook.example.com/alerts"
        })
    alert = resp.json()
    print(f"Alert set: {ticker} {alert_type} at {threshold}")
    return alert

set_alert("NVDA", "price_below", 165)
set_alert("NVDA", "rsi_below", 25)

Step 5: Backtest Your Strategy

python
def backtest(sector: str, entry_rsi: int = 30, exit_rsi: int = 50):
    """Backtest a simple RSI strategy."""
    resp = httpx.post(f"{BASE}/api/v1/backtest",
        headers=HEADERS,
        json={
            "strategy": {
                "entry_filters": {"rsi_below": entry_rsi},
                "exit_filters": {"rsi_above": exit_rsi},
                "sector": sector
            },
            "period": "1y",
            "initial_capital": 10000
        })
    perf = resp.json()["performance"]
    print(f"Return: {perf['total_return_pct']:.1f}% | Win rate: {perf['win_rate_pct']:.0f}%")
    return resp.json()

backtest("Semiconductors")

Putting It Together

python
# Full autonomous loop
picks = screen("oversold tech stocks with bullish sentiment")
for pick in picks[:3]:
    score = analyze(pick["ticker"])
    if score["signal"] in ("buy", "strong_bullish"):
        verify(f"{pick.get('entity_name',pick['ticker'])} outlook is positive")
        set_alert(pick["ticker"], "price_below", pick.get("price", 0) * 0.95)
        print(f"  → Watching {pick['ticker']}")

backtest("Technology", entry_rsi=30, exit_rsi=55)

Get Started