Dexter Deployment and Practical Guide: Let AI Read SEC Filings and Perform DCF Valuations for You

March 27, 2026

TIP

Difficulty: β˜…β˜…β˜†β˜†β˜† | Duration: 15 minutes | Takeaway: Master the deployment of a local financial research Agent, and understand tool calling and DCF skill extension mechanisms.

Introduction

Dexter is an autonomous financial research Agent that runs in your terminal. Ask it a complex question, and it will automatically decompose tasks, invoke multiple data tools, and cross-verify results until it provides a data-backed conclusionβ€”much like having a senior analyst who never tires.

Its core capabilities include:

  • SEC Filing Retrieval: Automatically scrape disclosure documents such as 10-K, 10-Q, and 8-K.
  • Real-time Market Data: Query stock prices, financial metrics, cash flows, and balance sheets.
  • DCF Intrinsic Value Estimation: Features a built-in DCF skill driven by SKILL.md to run discounted cash flow models.
  • Self-Verification Loop: Inspects its own intermediate results and iterates until a conclusion is validated.
  • Loop Protection: Built-in step limits to prevent the Agent from running out of control.

The entire project is written in TypeScript, centered around LangChain + Ink (React for CLI), and runs on the Bun 1.0+ environment. If you wish to utilize these capabilities at a lower cost, you can switch your LLM provider to Defapi, where API pricing is roughly half that of official rates.


Target Audience Profile

  • Developers with 1–5 years of experience and a basic understanding of AI Agent architectures (tool calling, Agentic Loops).
  • Independent investors or fintech professionals looking to use AI tools for fundamental research.
  • Engineers wanting to learn how to integrate multiple data sources (SEC, Financial Datasets, Exa) into real-world projects.
  • Users interested in quantitative financial research who want to build a local research pipeline.

Core Dependencies and Environment

DependencyDescriptionSource
Bun 1.0+JavaScript/TypeScript Runtimebun.sh
Financial Datasets API KeyInstitutional-grade market data (free for select stocks)financialdatasets.ai
OpenAI API KeyDefault LLM providerplatform.openai.com
Exa API KeyWeb search (optional, Tavily as fallback)exa.ai
Defapi API KeyReduce OpenAI costs (optional)defapi.org

WARNING

Data for AAPL, NVDA, and MSFT on Financial Datasets is free; other stocks require a subscription. It is recommended to verify your workflow using free tickers before starting.


Project Structure Tree

dexter/
β”œβ”€β”€ .dexter/
β”‚   └── settings.json          # Agent runtime configuration (model/provider selection)
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ agent/                  # Agent Core: Loop logic, prompts, scratchpad
β”‚   β”‚   β”œβ”€β”€ agent.ts           # Main Agentic Loop
β”‚   β”‚   β”œβ”€β”€ prompts.ts         # System prompts
β”‚   β”‚   └── scratchpad.ts      # Tool call history records
β”‚   β”œβ”€β”€ cli.tsx                # Ink/React CLI rendering entry point
β”‚   β”œβ”€β”€ index.tsx              # Program entry point
β”‚   β”œβ”€β”€ components/            # CLI UI components (Ink)
β”‚   β”œβ”€β”€ hooks/                 # React hooks (AgentRunner, ModelSelector)
β”‚   β”œβ”€β”€ model/
β”‚   β”‚   └── llm.ts            # Multi-provider LLM abstraction layer
β”‚   β”œβ”€β”€ tools/
β”‚   β”‚   β”œβ”€β”€ registry.ts       # Tool registry
β”‚   β”‚   β”œβ”€β”€ finance/          # Financial tools: Quotes, financials, filings, insider trades
β”‚   β”‚   β”œβ”€β”€ search/           # Web search tools (Exa / Tavily)
β”‚   β”‚   β”œβ”€β”€ browser/          # Playwright browser automation
β”‚   β”‚   └── descriptions/     # Tool descriptions (injected into system prompts)
β”‚   β”œβ”€β”€ skills/               # SKILL.md skills directory
β”‚   β”‚   └── dcf/
β”‚   β”‚       └── SKILL.md     # DCF intrinsic value estimation skill
β”‚   β”œβ”€β”€ evals/               # LangSmith evaluation framework
β”‚   └── utils/               # Env vars, config, cache
β”œβ”€β”€ scripts/
β”‚   └── release.sh
β”œβ”€β”€ .env                     # API keys (gitignored)
└── package.json

Step-by-Step Instructions

Step 1: Install Bun and Clone Project

If you don't have Bun installed, install it first. Works for Windows/macOS/Linux:

# macOS / Linux
curl -fsSL https://bun.com/install | bash

# Windows
powershell -c "irm bun.sh/install.ps1|iex"

Verify installation:

bun --version
# Output similar to: Bun v1.2.x

Then clone the Dexter repository:

git clone https://github.com/virattt/dexter.git
cd dexter

Step 2: Configure .env Environment Variables

Copy the environment variable template file:

cp env.example .env

Open .env in an editor and enter your keys. Regarding Defapi integrationβ€”if you want to use Defapi instead of OpenAI (saving 50% in costs), configure it as follows:

# .env

# ── LLM Providers ──────────────────────────────────────
# Option A: Direct OpenAI (Default)
OPENAI_API_KEY=sk-your-openai-key

# Option B: Access OpenAI via Defapi (Recommended, saves 50%)
# OPENAI_API_KEY=sk-your-defapi-key
# OPENAI_BASE_URL=https://api.defapi.com/v1

# Other optional LLM providers
ANTHROPIC_API_KEY=sk-ant-your-anthropic-key
GOOGLE_API_KEY=your-google-key
XAI_API_KEY=your-xai-key
OPENROUTER_API_KEY=your-openrouter-key

# Local Models (OLLAMA)
OLLAMA_BASE_URL=http://127.0.0.1:11434

# ── Financial Data ───────────────────────────────────────
# Institutional market data, free for AAPL/NVDA/MSFT
FINANCIAL_DATASETS_API_KEY=your-financial-datasets-key

# ── Web Search ───────────────────────────────────────
# Exa is preferred, Tavily as fallback
EXASEARCH_API_KEY=your-exa-key
TAVILY_API_KEY=your-tavily-key

TIP

All models on Defapi are compatible with v1/chat/completions and v1/messages interfaces. Dexter requires no code changes; simply replace OPENAI_API_KEY with your Defapi Key and point OPENAI_BASE_URL to https://api.defapi.com/v1.

Install dependencies:

bun install

Step 3: Run Dexter Interactive Mode

Start the interactive CLI:

bun start

You will see a colorful interface rendered with Ink in your terminal. Type your financial questions directly, for example:

How has AAPL's revenue grown over the last 5 years? What is its current DCF intrinsic value?

Dexter will automatically begin working: decomposing the task β†’ checking financial data β†’ reading SEC filings β†’ running the DCF skill β†’ summarizing conclusions. Every round of tool calling will be displayed in real-time on the interface.

If you want to debug while changing code, use watch mode:

bun dev

Step 4: Switch Models / Providers

Type the /model command within the CLI to switch LLM providers and models. Dexter supports automatic identification via the following prefixes:

PrefixProviderExample Model
No prefixOpenAI (Default)gpt-5.4
claude-Anthropicclaude-sonnet-4-7
gemini-Googlegemini-2.5-pro
ollama:Ollama (Local)ollama:qwen2.5
deepseek:DeepSeekdeepseek-chat

For example, to switch to Claude:

/model claude-sonnet-4-7

TIP

If you have integrated Defapi, you can use the default gpt-5.4. Traffic will automatically route through Defapi without consuming your official OpenAI quota.

Step 5: Use Financial Tools to Query Stocks

At the heart of Dexter is the financial_search tool, which automatically delegates to the most appropriate sub-tools based on your question. Here are some typical query examples:

Querying Revenue and Profits:

Query TSLA's revenue, net income, and free cash flow for the last 3 years.

Dexter will call get_income_statements and get_cash_flow_statements, returning the data organized in a table.

Querying Balance Sheets:

What is NVDA's latest debt-to-asset ratio? How much cash and equivalents do they have?

Reading SEC Filings:

Help me read the "Risk Factors" section in AAPL's latest 10-K.

Dexter will call the read_filings tool to fetch the 10-K content and locate the corresponding section.

Checking Insider Trades:

What was the insider trading activity for FAANG stocks in the last quarter?

Raw data from all tool calls is recorded in JSONL files within the .dexter/scratchpad/ directory for post-audit.

Step 6: Trigger DCF Valuation Skill

DCF (Discounted Cash Flow) valuation is one of Dexter's built-in skills. When your question involves "intrinsic value" or "valuation," the Agent automatically calls the skill tool to load src/skills/dcf/SKILL.md and proceeds step-by-step:

  1. Retrieve historical Free Cash Flow (FCF).
  2. Estimate growth rate assumptions for the next 5–10 years.
  3. Calculate the Weighted Average Cost of Capital (WACC).
  4. Discount to the present value.
  5. Output final valuation ranges + sensitivity analysis.

Example query:

What is MSFT's DCF intrinsic value? Please provide results for conservative, base, and optimistic scenarios.

WARNING

DCF outputs are reference ranges, not investment advice. Dexter clearly labels the confidence level of each assumption, aligning with its design philosophy: do not package certainty, do not avoid uncertainty.

Step 7: Debugging and Viewing Scratchpad Logs

Every query in Dexter generates a JSONL file in .dexter/scratchpad/, with the filename format:

YYYY-MM-DD-HHMMSS_<session_id>.jsonl

Each line is a structured record:

{"type":"init","timestamp":"2026-03-27T10:00:00.000Z","query":"What is AAPL's DCF intrinsic value?"}
{"type":"tool_start","timestamp":"2026-03-27T10:00:01.000Z","toolName":"get_cash_flow_statements","args":{"ticker":"AAPL","period":"annual","limit":5}}
{"type":"tool_result","timestamp":"2026-03-27T10:00:03.000Z","toolName":"get_cash_flow_statements","result":{"freeCashFlow":[67800000000, 73000000000, ...]},"llmSummary":"AAPL's FCF has grown steadily over the last 5 years at a CAGR of ~9.2%"}
{"type":"thinking","timestamp":"2026-03-27T10:00:05.000Z","content":"FCF data retrieved. Now need analyst growth expectations and WACC parameters..."}

If you find a tool call result is incorrect, open this file to locate the issue. You can also use jq for quick filtering:

# View only tool call results
cat .dexter/scratchpad/2026-03-27-*.jsonl | jq 'select(.type == "tool_result")'

# View the Agent's reasoning process
cat .dexter/scratchpad/2026-03-27-*.jsonl | jq 'select(.type == "thinking")'

Troubleshooting

1. Runtime error: OPENAI_API_KEY not found

This is the most common error. Check if the .env file exists and the path is correct:

ls -la .env

Ensure OPENAI_API_KEY=... or the OPENAI_API_KEY + OPENAI_BASE_URL combination is present. If using Defapi, both must exist.

2. Financial data returns empty results

Free data from Financial Datasets is limited to AAPL, NVDA, and MSFT. Queries for other stocks will return empty results. You can:

  • Check your subscription plan at financialdatasets.ai.
  • Confirm FINANCIAL_DATASETS_API_KEY is correctly entered in .env.

3. Model call timeout

Anthropic and Google API timeouts default to 60 seconds. If your network connection to overseas services is unstable, adjust maxAttempts and retry wait times in src/model/llm.ts. For long-term use, integrating via Defapi is recommended for more stable optimized routing.

4. Agent stuck in an infinite loop

Dexter has a built-in maxIterations protection (default 10 steps). If a task requires more steps, you can adjust this in src/agent/agent.ts. When steps are exhausted, the Agent will return current intermediate conclusions as the final result instead of idling.

5. Tool calls return incomplete data

The limit parameter in Financial Datasets controls the number of years returned; the default might be only 1 year. When querying, you can have Dexter explicitly specify limit=5 or limit=10.

6. Scratchpad file is empty or not generated

The scratchpad is managed by src/agent/scratchpad.ts. If the SKIP_SCRATCHPAD=true environment variable is set, files will not be written. Confirm this variable is not in .env. Note that every new query creates a new file; old query files are not appended.


Further Reading / Advanced Directions

Integrate WhatsApp for a Mobile Research Assistant

Dexter supports receiving messages via a WhatsApp Gateway. As long as your phone and Dexter are on the same network:

# Scan QR code to link WhatsApp account
bun run gateway:login

# Start Gateway
bun run gateway

Then, send a message to yourself on WhatsApp, and Dexter will reply. This allows you to check the latest financials of your holdings during a commute.

For detailed configuration, refer to src/gateway/channels/whatsapp/README.md.

Run Evaluation Suite to Verify Agent Accuracy

Dexter includes a LangSmith-driven evaluation framework:

# Run evaluation on all test questions
bun run src/evals/run.ts

# Randomly sample 10 questions
bun run src/evals/run.ts --sample 10

Evaluations use an LLM-as-Judge scoring method, and results are uploaded to the LangSmith Dashboard. If you modify financial metric calculations, use this suite to verify the quality of your changes.

Connect to Ollama for Local Models

If you prefer to be completely independent of external APIs:

# Start Ollama (must be installed beforehand)
ollama serve

# Configure in .env
OLLAMA_BASE_URL=http://127.0.0.1:11434

Then switch to ollama:qwen2.5 or another local model in the CLI. Note: Local models may not be as stable at tool calling as GPT-5.4 or Claude Sonnet; they are recommended for low-latency, low-cost scenarios.

Custom SKILL.md for New Skills

Skills in Dexter are defined via SKILL.md, containing YAML frontmatter (name, description) and markdown-formatted instructions. Creating a new skill involves:

  1. Creating a new directory under src/skills/, e.g., src/skills/dupont/.
  2. Writing SKILL.md:
---
name: dupont-analysis
description: DuPont Analysis - Decomposing ROE into Net Profit Margin, Asset Turnover, and Equity Multiplier
---

# DuPont Analysis Skill

You are a financial analyst. Please perform the following steps for the input ticker:

1. Retrieve the company's Net Income, Revenue, Total Assets, and Shareholder Equity.
2. Calculate the three decomposed metrics:
   - Net Profit Margin = Net Income / Revenue
   - Asset Turnover = Revenue / Total Assets
   - Equity Multiplier = Total Assets / Shareholder Equity
3. Calculate ROE = Product of the three metrics.
4. Compare with industry averages and provide a score (1-10).
  1. Restarting Dexter; the new skill will be automatically discovered and injected into system prompts.

Use Defapi to Lower API Costs

For high-frequency LLM use cases (automated monitoring, periodic report generation), API costs are significant. Integrating via Defapi can save approximately 50%:

# .env
OPENAI_API_KEY=your-defapi-api-key
OPENAI_BASE_URL=https://api.defapi.com/v1

Defapi is compatible with all models using the v1/chat/completions interface. Dexter requires no code modificationsβ€”just replace the key and base URL.

Updated March 27, 2026
    Dexter Deployment and Practical Guide: Let AI Read SEC Filings and Perform DCF Valuations for You | OpenClaw API Documentation - Open Source AI Assistant Integration Guide