Market research desk pack

The market research desk pack (markets) runs on the pipeline engine. Give it a US stock or ETF and the news you want weighed. A scanner frames the setup, a bull and a bear analyst write their cases without seeing each other, then each rebuts the other. A portfolio manager proposes a paper decision within your desk’s risk limits, a risk manager can veto it, and in strict mode you review it. Once the run completes, Tevrin grades the decision against the prices that follow, and a post-mortem turns what it learns into lessons for the next runs.

Decisions are paper records. Nothing is traded, and nothing here is financial advice. There is no order, position or account code anywhere in Tevrin. The pack registers no tools and no external handlers, no stage lists tools:, and the Alpaca adapter only reads market data.

The pipeline

market-research is engine-controlled and runs many at once (concurrency: { runs: many }). It starts manually or from a signed webhook (input research_request). Its modes are strict, advisory (the default) and autonomous.

# Stage Kind Reads Writes Notes
1 snapshot handler markets.price-snapshot research_request and Alpaca price_snapshot needs research_request; the veto markets.universe (U1–U3) ends the run vetoed
2 scan agent scanner research_request, price_snapshot, desk_profile scan grounded (C1–C3); 3 attempts, then an escalation
3 cases parallel: bull (agent bull-analyst) and bear (agent bear-analyst) scan, price_snapshot, research_request bull_case, bear_case grounded; 3 attempts each, then the group fails; earlier lessons injected
4 rebuttals parallel: bull_rebut (agent bull-rebuttal) and bear_rebut (agent bear-rebuttal) both cases, price_snapshot, research_request bull_rebuttal, bear_rebuttal grounded; both share the markets.rebuttal prompt
5 propose agent portfolio-manager the scan, the four cases and rebuttals, price_snapshot, desk_profile, portfolio proposal the risk limits (K1–K5) are checked, 3 attempts then an escalation; the risk-manager veto ends the run vetoed
6 review gate decision_review (strict mode only) proposal   rejecting sends it back to propose (at most 3 times)
7 record handler markets.record proposal, price_snapshot, research_request decision_record  

After the run completes, two follow-ups run outside the main flow:

  • grade (handler markets.grade) checks every day for up to 45 days;
  • postmortem (agent post-mortem) runs once, 32 days after.

Artifacts

Project artifacts (set these up first)

Both are project-scope JSON, need an Owner’s approval, and are pinned when a run starts: a run keeps the versions it started with. Add a version of each on the Pipeline tab’s Project artifacts section, then lock it.

Artifact Shape Defaults
desk_profile { maxPositionPct, maxSectorPct, allowShort, minConviction, restricted[] } 5, 25, false, 3, none
portfolio { positions: [{ symbol, sector, valuePct }] }: the paper book the limits count against  
{ "maxPositionPct": 5, "maxSectorPct": 25, "allowShort": false, "minConviction": 3, "restricted": ["GME"] }
{ "positions": [ { "symbol": "AAPL", "sector": "tech", "valuePct": 3 }, { "symbol": "MSFT", "sector": "tech", "valuePct": 18 } ] }

The portfolio is what you say the desk holds. Tevrin never reads a broker.

Input (you give this to a run)

research_request: symbol (required, ^[A-Z][A-Z.]{0,9}$: a letter first), sector (the name the sector limit counts it under), news (up to 30 pasted items { id: n1…, title?, text, publishedAt? }) and notes.

Outputs

Every output is JSON and locks automatically.

Artifact Holds
price_snapshot the asset (symbol, name, exchange, class, tradable), asOf, lastClose, sma20, sma50, vol20, high52w, low52w, pctFromSma20, pctFromSma50, pctFrom52wHigh, return20d, barCount and the last 60 bars
scan setup, catalysts, keyQuestions, points
bull_case, bear_case thesis, points (2–10), risks, targetPct?
bull_rebuttal, bear_rebuttal points (1–8), concessions
proposal action (buy, short, hold or avoid), sizePct, stopPct?, horizonDays, upProbability, conviction (1–5), thesis, invalidation, rationale
decision_record action, symbol, entryClose, entryDate, sizePct, stopPct?, horizonDays, upProbability, summary, runId
grade one per check: { barsAfterEntry, returns }
postmortem { summary, calledRight, lessons: { bull[], bear[], pm[] } }

The price snapshot and the veto

snapshot reads the asset and its daily bars over the 380 calendar days before the run started (at most 252 bars). A bar counts once its session is over (from 21:00 UTC on its date), so a session still trading is never used. From the bars it computes:

  • lastClose and asOf from the last bar;
  • sma20 and sma50, the simple moving averages, to 2 places (null with too few bars);
  • vol20, the annualised volatility of the last 20 daily log returns (sample standard deviation × √252 × 100), to 1 place;
  • high52w and low52w over the bars;
  • pctFromSma20, pctFromSma50, pctFrom52wHigh and return20d (the last close against the close 19 bars before it), as percentages to 1 place.

For example, 20 closes rising from 100 to 119 give sma20 109.50 and return20d 19.0.

Then the markets.universe veto checks it. Any finding ends the run vetoed before an agent runs:

Rule Vetoes when
U1 the asset isn’t tradable, or its class isn’t us_equity (US stocks and ETFs)
U2 the symbol is on desk_profile.restricted
U3 there are fewer than 20 bars

The debate and its grounding

The bull and bear analysts write at the same time, in two branches that can’t read each other’s output. Only the rebuttals see both cases. Each rebuttal answers the other side’s case and lists what it concedes. The rebuttal agents share one prompt, and the host tells each which side it’s on.

Every point in the scan, the cases and the rebuttals is { text, refs }, and the markets.case-grounding guard checks it before the output is kept:

Rule Check
C1 every ref exists: price:<field> names a numeric price_snapshot field with a value, news:<id> a pasted news item, and (rebuttals only) case:<n> the n-th point of the other side’s case
C2 every number in the text is one of its refs’ numbers: a field’s stored value, a number in the news item’s text, or a number in the cited case point. Window lengths (50-day, 20 days, 3 months) don’t count
C3 every point has at least one ref

For example, with pctFromSma50 at 7.2, the point “Trades 9% above its 50-day average” citing price:pctFromSma50 is rejected with C2: points[0] states "9", which isn't in its refs. “Trades 7.2% above its 50-day average” passes. The findings go back to the agent, which tries again.

Risk limits and the risk manager

The markets.risk-limits guard checks the portfolio manager’s proposal. Its findings go back to the portfolio manager, which revises the size:

Rule Check (buy and short only, except K4)
K1 sizePct plus what the portfolio already holds of the symbol is at most maxPositionPct
K2 when the request names a sector: what the portfolio holds of that sector plus sizePct is at most maxSectorPct
K3 stopPct is given and 1–25
K4 hold and avoid have sizePct 0, and a conviction below minConviction must be hold or avoid
K5 short needs allowShort

For example, with limits 5 and 25, a portfolio holding AAPL (tech, 3%) and MSFT (tech, 18%), and a request for NVDA in tech: buying 8% gives K1: size 8% is over the 5% limit and K2: tech would be 29%, over 25%. Buying 4% puts tech at 25% and passes.

Then the risk-manager agent reviews the proposal with both cases, both rebuttals and the limits. It vetoes a thesis that ignores the strongest opposing point or depends on one event. A veto ends the run vetoed, and its findings stay on the propose stage in the timeline as the decision not taken. No decision record is written.

Review and the record

In strict mode, decision_review waits for a person with the proposal. Its copy, from the definition, reads “Paper decision: nothing is traded.” Approving records the decision; rejecting with a comment sends it back to the portfolio manager (at most 3 times). Advisory and autonomous runs have no gate.

record writes the decision_record: the action, the symbol, the entry close and date (the snapshot’s last close and its date), the size, stop, horizon and up probability, a summary of the rationale, and the run id.

Grading

Once the run completes, grade checks the decision every day for up to 45 days. Each check reads the bars after the entry date (one request) and counts trading days, so a Friday decision’s first day is Monday’s close. As each is reached, it records a declared outcome, once:

Metric Kind Recorded
return_1d, return_5d, return_20d number the close of the 1st, 5th and 20th bar after the entry date against the entry close, in %, to 2 places
direction_20d Brier score on propose’s upProbability at bar 20: 1 when return_20d > 0, else 0

At bar 20 the check completes and no more are queued. For example, from an entry close of 100.00, bar 1 closing 101.50, bar 5 97.20 and bar 20 108.00 record 1.5, −2.8 and 8.0, and direction_20d 1; with an up probability of 0.65 its score is (0.65 − 1)² = 0.1225. Weekend checks find no new bar and record nothing.

If Alpaca can’t be read one day, that check fails and the next day’s is still due; three failed checks in a row stop it. A run that ended vetoed decided nothing, so it gets no grade checks and no post-mortem: no follow-ups are scheduled for it. Each check also reads the entry date’s own bar: the bars are split-adjusted as of the check, so a split after the entry rescales that bar too, and its close is the basis of the returns (the recorded entryClose only when the source has no entry-date bar).

Post-mortems and feedback

32 days after the run completed, the post-mortem agent reads the decision record, the proposal, the cases and rebuttals, the newest grade and the outcome scores. It returns a summary, whether the decision was right, and at most 3 lessons (300 characters each) for each of the bull analyst, the bear analyst and the portfolio manager. If return_20d isn’t recorded yet, it works with what exists and says so.

Each lesson becomes a feedback entry for that agent, and later runs inject the newest 10 into the bull, bear and portfolio manager prompts.

A vetoed run gets no post-mortem, so nothing is spent on it and no feedback is written.

Start a run

From the UI

  1. Add and lock the desk_profile and portfolio versions (Project artifacts, on the Pipeline tab).
  2. Select Start run, pick market-research, and an approval mode.
  3. Fill in the research_request form (the symbol, the sector, and paste each news item’s text), or choose Upload a JSON file.
  4. Select Start run.

From the API

curl -X POST "$TEVRIN/api/projects/$PID/pipeline-runs" \
  -H 'Content-Type: application/json' \
  -d '{ "pipelineId": "market-research", "approvalMode": "strict", "inputs": { "research_request": {
        "symbol": "NVDA", "sector": "tech",
        "news": [ { "id": "n1", "title": "Results", "publishedAt": "2030-11-20",
                    "text": "Nvidia said data-centre revenue rose 35% from a year earlier." } ] } } }'

A success is 201 with the run. Errors: 400 INPUT_INVALID (the request fails its schema). An unknown symbol, or market data that can’t be loaded, fails the snapshot stage, not the request.

From a signed webhook

An Owner creates a webhook with { "pipelineId": "market-research" } on POST /api/projects/$PID/pipeline-webhooks. The body you post is the research_request JSON, signed as in Triggers and webhooks, and each call starts its own run (202 with { runId }).

The data source

Prices come from Alpaca’s market data API (daily bars, the IEX feed by default) and the asset lookup from Alpaca’s paper API. A paper account’s API keys are enough; see Market data for creating them and setting MarketData:Alpaca:KeyId and MarketData:Alpaca:SecretKey. The host’s read-only adapter (Tevrin.Infrastructure/MarketData/Alpaca) implements the pack’s IPriceHistorySource; the pack itself makes no network calls.

  • It sends only GET requests, to the configured data and asset hosts, with a 10 s timeout per attempt, 2 retries on a 5xx answer or a timeout, a 2 MB response cap, and no redirects.
  • It calls only /v2/stocks/{symbol}/bars and /v2/assets/{symbol}: never an order, position or account endpoint.
Stage error Means Do this
MARKET_DATA_NOT_FOUND the symbol doesn’t exist at Alpaca check the symbol, and start a new run
MARKET_DATA_UNAVAILABLE the keys aren’t set (“Alpaca market data isn’t configured”), Alpaca refused them, timed out, or failed after its retries check the market data settings, then retry the stage

Privacy and safety

  • The Alpaca keys come from configuration only. They’re sent as request headers, redacted from logs, and never put in a prompt or a stored artifact.
  • Pasted news is untrusted. The prompts put every input in delimited data blocks and tell the agents to treat it as data. No agent has tools, so an injected instruction can’t act, and C1–C3 catch numbers it makes up.
  • Your research requests, cases and portfolio are sent to the project’s configured LLM provider.
  • Decisions are paper records. Nothing is traded, and nothing here is financial advice.