Strategia Invest API

Complete reference for Financial Data, Valuation Models, and Macroeconomics.

Referência completa para Dados Financeiros, Modelos de Valuation e Macroeconomia.

Base URL: https://strategiainvest.com.br

1. Authentication 1. Autenticação

The API uses JWT (JSON Web Tokens). You must first exchange your credentials for a token valid for 24 hours.

A API utiliza JWT (JSON Web Tokens). Você deve primeiro trocar suas credenciais por um token válido por 24 horas.

POST /api/v1/token
Headers
Authorization Required Basic Auth (Base64 encoded username:password)
Example Response Exemplo de Resposta
{ "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." }
Important: For all subsequent requests, include the token in the header: Importante: Para todas as requisições seguintes, inclua o token no header:
Authorization: Bearer <your_token>
Service credential (recommended for agents/MCP): long-lived ApiKey, generated by the account owner on the Account page (menu → Conta → "Chaves de API") — shown once, revocable anytime, up to 5 active keys. Inherits the owner's premium tier. Use it instead of re-authenticating every 24h: Credencial de serviço (recomendado para agentes/MCP): ApiKey de longa duração, gerada pelo dono da conta na página da Conta (menu → Conta → "Chaves de API") — exibida uma única vez, revogável a qualquer momento, até 5 chaves ativas. Herda o tier premium do dono. Use em vez de reautenticar a cada 24h:
Authorization: ApiKey <your_key>
Rate limits: 120/minute per credential for the whole API, 10/minute per IP on POST /v1/token, 5/minute per credential on POST /v1/backtest (heavier compute). Exceeding returns 429 in the same application/problem+json shape as other errors. Rate limits: 120/minuto por credencial para a API inteira, 10/minuto por IP em POST /v1/token, 5/minuto por credencial em POST /v1/backtest (compute mais caro). Ao exceder, devolve 429 no mesmo formato application/problem+json dos demais erros.

2. Discovery Endpoints 2. Endpoints de Descoberta (Discovery)

Use these endpoints to list all available assets and find out which indicators are available for them.

Use estes endpoints para listar todos os ativos disponíveis e descobrir quais indicadores existem para eles.

Asset Lists Listas de Ativos
  • GET /api/v1/companies/cnpjs
    Returns a list of all available Company CNPJs. Retorna uma lista de todos os CNPJs de empresas disponíveis.
  • GET /api/v1/stocks/codes
    Returns a list of all available Stock Tickers. Retorna uma lista de todos os Tickers de ações disponíveis.
Indicator Discovery Descoberta de Indicadores
  • GET /api/v1/macro/indicators
  • GET /api/v1/companies/{cnpj}/indicators
  • GET /api/v1/stocks/{ticker}/indicators
Response Example (Asset List) Exemplo de Resposta (Lista de Ativos)
{ "stock_codes": [ "ABEV3", "BBAS3", "PETR4", "WEGE3", ... ] }

3. Macroeconomics 3. Macroeconomia

Access historical data for global economic indicators.

Acesse dados históricos de indicadores econômicos globais.

GET /api/v1/macro/indicators/{indicator}
Parameters Parâmetros
start_date Optional YYYY-MM-DD
end_date Optional YYYY-MM-DD
Available Indicators Indicadores Disponíveis
  • cdi_interest_rate: Daily CDI rate.Taxa CDI diária.
  • ipca_inflation: Monthly official inflation.Inflação oficial (IPCA) mensal.
  • ibovespa_index: IBOVESPA daily closing points.Fechamento diário do IBOVESPA.
  • equity_risk_premium: Implied ERP for Brazil (Damodaran).ERP Implícito Brasil (Metodologia Damodaran).
  • risk_free_rate: Calculated Risk-Free Rate.Taxa Livre de Risco (Tesouro IPCA+ Spread + IPCA Acumulado).
Example Request

GET /api/v1/macro/indicators/ipca_inflation?start_date=2023-01-01

Response Format
{ "indicator": "ipca_inflation", "count": 226, "history": [ { "date": "2007-01-01", "value": 0.44 }, ... ] }

4. Full Reports (RAG) 4. Relatórios Completos (RAG)

Endpoints optimized for RAG (Retrieval-Augmented Generation) ingestion. Returns pre-formatted Markdown dossiers containing all available data.

Endpoints otimizados para ingestão em RAG (Geração Aumentada por Recuperação). Retorna dossiês pré-formatados em Markdown contendo todos os dados disponíveis.

GET /api/v1/reports/macro

Generates a complete macroeconomic context report including definitions and recent history for all indicators (Selic, IPCA, GDP, etc). Gera um relatório de contexto macroeconômico completo incluindo definições e histórico recente para todos os indicadores (Selic, IPCA, PIB, etc).

Example Request

GET /api/v1/reports/macro

Response Format
{ "report": "================================================================================\nDOSSIÊ MACROECONÔMICO: CENÁRIO DE MERCADO BRASIL\nData de Geração: 07/01/2026 14:30\n================================================================================\n\n> Este documento fornece o contexto econômico atual para análise de investimentos.\n\n## Taxa CDI (Juros de Curto Prazo)\n> **Definição:** A taxa CDI segue de perto a Taxa Selic...\n..." }
GET /api/v1/reports/dossier/{ticker}

Generates an analysis dossier for a specific stock. By default returns a compact dossier (Profile + Valuation Models); pass sections=all for the full dossier, including Fundamental Indicators, Market Data, and recent CVM Documents/Insider Trading. Gera um dossiê de análise para uma ação específica. Por padrão devolve um dossiê compacto (Perfil + Modelos de Valuation); passe sections=all para o dossiê completo, incluindo Indicadores Fundamentalistas, Dados de Mercado e Documentos CVM/Insiders recentes.

Parameters Parâmetros
ticker Required Stock symbol (e.g., WEGE3). Código da ação (ex: WEGE3).
sections Optional Comma-separated: profile, valuation, fundamentals, market, documents, adjustments; or all. Default: profile,valuation. Separado por vírgula: profile, valuation, fundamentals, market, documents, adjustments; ou all. Default: profile,valuation.
start_date Optional YYYY-MM-DD
end_date Optional YYYY-MM-DD
Example Request

GET /api/v1/reports/dossier/WEGE3?sections=all

Response Format
{ "report": "================================================================================\nDOSSIÊ COMPLETO: WEG S.A. (WEGE3)\nData: 07/01/2026 14:32\n================================================================================\n\n## 1. PERFIL E GOVERNANÇA\n**CNPJ:** 84.429.695/0001-11\n**Setor:** Bens Industriais / Máquinas e Equipamentos\n...\n## 2. VALUATION ENGINE (MODELOS)\n..." }

5. Company Profile 5. Perfil da Empresa

GET /api/v1/companies/{cnpj}/info

Retrieves static data, governance info, sector, and share structure.

Retorna dados cadastrais, governança, setor e estrutura acionária.

CNPJ Format: You can send the CNPJ encoded (84.429.695%2F0001-11) or digits only (84429695000111). Formato CNPJ: Você pode enviar o CNPJ codificado (84.429.695%2F0001-11) ou apenas dígitos (84429695000111).
Example Request

GET /api/v1/companies/84429695000111/info

Response Format
{ "legal_name": "WEG SA", "cnpj": "84.429.695/0001-11", "sector_classification": "Bens Industriais / Máquinas e Equipamentos", "governance_level": "BOLSA", "free_float": { "common_percent": 35.4, "preferred_percent": 0.0, "total_percent": 35.4 }, "tickers": ["WEGE3"], "last_financial_statement": { "delivery_timestamp": "2025-10-22T08:00:24", "download_url": "https://..." } }

6. Company Indicators (History) 6. Indicadores da Empresa (Histórico)

GET /api/v1/companies/{cnpj}/indicators/{indicator}
Parameters Parâmetros
start_date Optional YYYY-MM-DD
end_date Optional YYYY-MM-DD
Example Request

GET /api/v1/companies/84429695000111/indicators/net_revenue_annual?start_date=2010-01-01

Available Indicators Reference Referência dos Indicadores Disponíveis

  • net_revenue_annual, net_revenue_quarterly (Receita Líquida)
  • gross_revenue_annual, gross_revenue_quarterly (Receita Bruta)
  • gross_profit_annual, gross_profit_quarterly (Lucro Bruto)
  • operating_income_annual, operating_income_quarterly (EBIT/Lucro Operacional)
  • ebitda_annual, ebitda_quarterly (EBITDA)
  • net_income_annual, net_income_quarterly (Lucro Líquido)
  • financial_result_annual, financial_result_quarterly (Resultado Financeiro)
  • taxes_annual, taxes_quarterly (Impostos)
  • depreciation_annual, depreciation_quarterly (Depreciação)

  • total_equity (Patrimônio Líquido)
  • current_assets, non_current_assets (Ativo Circulante / Não Circulante)
  • current_liabilities, non_current_liabilities (Passivo Circulante / Não Circulante)
  • gross_debt, net_debt (Dívida Bruta / Líquida)
  • short_term_debt, long_term_debt (Dívida CP / LP)
  • cash_and_equivalents (Caixa e Equivalentes)
  • inventory (Estoques)

  • fcff_annual: Free Cash Flow to Firm (Fluxo de Caixa Livre da Firma).
  • net_capex_annual, net_capex_quarterly
  • working_capital_change_annual (Variação de Capital de Giro)
  • roic, roe (Rentabilidade)
  • gross_margin, net_margin, ebitda_margin, operating_margin (Margens)
  • payout_ratio (Payout)
  • current_liquidity, dry_liquidity, general_liquidity (Liquidez)
  • net_debt_to_ebitda (Dívida Líquida/EBITDA), net_debt_to_ebit

  • loss_ratio_history_20y: % of years with negative net income.Proporção de anos com prejuízo.
  • cagr_net_income_history: 1y, 3y, 5y, 10y and Weighted Avg CAGR.CAGR de Lucros (1, 3, 5, 10 anos e Média Ponderada).
  • cost_of_debt_history: Estimated Kd.Custo da Dívida estimado (Kd).
  • financial_leverage_degree_history: GAF (Grau de Alavancagem Financeira).
  • value_generation_history: Market Cap growth vs Retained Earnings.Geração de Valor (Crescimento de VM vs Lucros Retidos).
  • return_on_new_invested_capital_history: RONIC (Retorno sobre Novos Investimentos).
  • ten_year_averages_history: 10y average for ROE, ROIC, Margins.Médias de 10 anos (ROE, ROIC, Margens).
  • share_capital_history: Capital Stock (See special format below).Histórico de Capital Social (Veja formato abaixo).
Special Response: Share Capital Resposta Especial: Capital Social

Indicator: share_capital_history

{ "cnpj": "84.429.695/0001-11", "count": 5, "history": [ { "date": "2021-04-28", "total_shares": 4197317998, "common_shares": 4197317998, "preferred_shares": 0 } ] }

7. Stock Snapshot (Info) 7. Ações (Info/Snapshot)

GET /api/v1/stocks/{ticker}/info

Returns market data, multiples, and the Rights/Governance structure.

Retorna dados de mercado, múltiplos e estrutura de Direitos/Governança.

Example Request

GET /api/v1/stocks/WEGE3/info

Response Format
{ "ticker": "WEGE3", "market_data": { "price": 44.23, // Raw/Unadjusted Price "pe_ratio": 27.25, "dividend_yield": 0.019 }, "rights": { "tag_along_percent": 100.0, "voting_rights": "Pleno", "dividend_rights_description": "25% do lucro líquido..." } }

8. Stock Indicators (History) 8. Histórico da Ação (Indicadores)

GET /api/v1/stocks/{ticker}/indicators/{indicator}
Parameters Parâmetros
start_date Optional YYYY-MM-DD
end_date Optional YYYY-MM-DD
Available Indicators Indicadores Disponíveis
  • price: Raw closing price (unadjusted).Preço de fechamento bruto (sem ajustes).
  • volume: Financial volume.Volume financeiro.
  • volume_moving_avg_30d: 30-day Volume Moving Average.Média Móvel de Volume (30d).
  • pe_ratio: P/E History (Price-to-Earnings).Histórico P/L (Preço/Lucro).
  • pb_ratio: P/B History (Price-to-Book).Histórico P/VP (Preço/Valor Patrimonial).
  • dividend_yield: DY History.Histórico de Dividend Yield.
  • payouts: Dividends & JCP (Special format).Dividendos e JCP (Formato especial).
Example Usage: Payouts

GET /api/v1/stocks/WEGE3/indicators/payouts?start_date=2024-01-01

Response Format (Payouts)
{ "indicator": "payouts", "history": [ { "date": "2024-12-20", // Ex-Date (Data Com) "approval_date": "2024-12-17", "payment_date": "2025-03-12", "type": "INTEREST_ON_EQUITY", "value": 0.079764706 } ] }

9. Valuation Engine (DCF & Simple) 9. Motor de Valuation (DCF e Simples)

Run dynamic valuation models. You can use default parameters or override them to create custom scenarios.

Execute modelos de valuation dinâmicos. Você pode usar os parâmetros padrão ou sobrescrevê-los para criar cenários personalizados.

As-of Valuation (parametrized)

POST /api/v1/stocks/{code}/valuation · POST /api/v1/stocks/{code}/valuation/scenarios

Body: {model: "dcf"|"simple", as_of?, assumptions?}. assumptions accepts the engine's full contract — projection_years, growth_years, terminal_growth, growth_rate, discount_rate, base_flow, shares, tag_along. Omitted assumptions are computed by the engine; assumptions_used reports provided vs computed per assumption. base_flow/shares/tag_along are validated at the border (shares > 0, 0 ≤ tag_along ≤ 1) → 422 on violation. /scenarios runs a growth × discount grid over the same base_assumptions contract (max 100 cells).

Corpo: {model: "dcf"|"simple", as_of?, assumptions?}. assumptions aceita o contrato completo do motor — projection_years, growth_years, terminal_growth, growth_rate, discount_rate, base_flow, shares, tag_along. Premissa omitida é computada pelo motor; assumptions_used reporta provided vs computed por premissa. base_flow/shares/tag_along validam na borda (shares > 0, 0 ≤ tag_along ≤ 1) → 422 no estouro. /scenarios roda grade crescimento × desconto sobre o mesmo contrato de base_assumptions (máx. 100 células).

Discounted Cash Flow (DCF)

Available endpoints:

Endpoints disponíveis:

  • Company: intrinsic_value_dcf_history (Fair Value / Valor Justo)
  • Stock: target_price_dcf_history (Target Price / Preço Alvo)
  • Stock: margin_of_safety_dcf_history (Margin / Margem de Segurança)
Query Parameters (Filter & Modeling) Parâmetros (Filtro e Modelagem)
Parameter Type Description
start_date YYYY-MM-DD Filter history start date (Optional). Filtrar data de início do histórico (Opcional).
end_date YYYY-MM-DD Filter history end date (Optional). Filtrar data final do histórico (Opcional).
projection_years int Years for explicit cash flow projection (Default: 3). Anos de projeção explícita de caixa (Padrão: 3).
growth_years int Lookback period for historical growth (Default: 5). Período retroativo para crescimento histórico (Padrão: 5).
terminal_growth float Perpetuity growth rate (g). Example: 0.05 (5%). Crescimento na perpetuidade (g). Exemplo: 0.05 (5%).
projection_growth_rate float / dict Override: Force a specific growth rate (g_proj).
Accepts a literal (e.g., 0.10) or a JSON object.
Forçar: Impõe um crescimento específico (g_proj).
Aceita valor literal (ex: 0.10) ou objeto JSON.
discount_rate float / dict Override: Force a specific WACC/Ke rate.
Accepts a literal (e.g., 0.12) or a JSON object.
Forçar: Impõe uma taxa de desconto (WACC/Ke).
Aceita valor literal (ex: 0.12) ou objeto JSON.
Example 1: Literal Override (Valor Fixo)

Force 10% growth and 12% discount rate:

Forçar 10% de crescimento e 12% de desconto:

GET /api/v1/stocks/WEGE3/indicators/target_price_dcf_history?projection_years=10&discount_rate=0.12&projection_growth_rate=0.10
Example 2: Dictionary Override (Avançado)

Pass a JSON object to vary rates over time (URL Encoded):

Passe um objeto JSON para variar taxas no tempo (URL Encoded):

GET ...&discount_rate={"2023-01-01":0.10, "2024-01-01":0.12}
Response Format (With Meta)
{ "meta": { "params": { "projection_years": 10, "discount_rate": 0.12, "terminal_growth": 0.05 } }, "history": [ { "date": "2023-12-31", "value": 45.20 } ] }
Simple Valuation Valuation Simples (Múltiplos)

Approximation of the DCF model based on the 5-year average of Net Income, discounted by the Risk-Free Rate (Treasury IPCA+).

Aproximação do modelo DCF baseada na média de Lucro Líquido dos últimos 5 anos, descontada pela Taxa Livre de Risco (Tesouro IPCA+).

start_date Optional YYYY-MM-DD Filter history start date. Filtrar data de início do histórico.
end_date Optional YYYY-MM-DD Filter history end date. Filtrar data final do histórico.
  • intrinsic_value_simple_history: Calculated Fair Value (Company).Valor Justo Calculado (Empresa).
  • target_price_simple_history: Target Price (Stock).Preço Alvo (Ação).
  • margin_of_safety_simple_history: Margin (Stock).Margem de Segurança (Ação).

10. Screener 10. Screener

Multi-criteria filter over the whole B3 universe, with point-in-time support (as_of).

Filtro multi-critério sobre todo o universo da B3, com suporte a point-in-time (as_of).

GET /api/v1/screener/attributes

Catalog of ~62 filterable attributes (name, category, unit, observed min/max, whether the attribute is point-in-time reliable) — including the valuation anchors implied_growth and price_to_epv. Cacheable for 1 day.

Catálogo dos ~62 atributos filtráveis (nome, categoria, unidade, min/max observados, se o atributo é fidedigno point-in-time) — inclusive as âncoras de valuation implied_growth e price_to_epv. Cacheável por 1 dia.

GET /api/v1/screener/strategies

Pre-built filter sets (Graham, Buffett, Lynch, Damodaran).

Conjuntos de filtro pré-montados (Graham, Buffett, Lynch, Damodaran).

POST /api/v1/screener/run

Runs the filter and returns paginated matching stock codes with the requested attribute values.

Executa o filtro e devolve os códigos de ação encontrados, paginados, com os valores dos atributos pedidos.

Body Example Exemplo de Corpo
{ "as_of": "2024-12-31", "filters": [ { "attribute": "pe_ratio", "max": 15 }, { "attribute": "roic", "min": 0.1 } ], "sort": "-roic", "page": 1, "page_size": 50 }
Response Format Formato da Resposta
{ "results": [ { "code": "WEGE3", "values": { "pe_ratio": 14.2, "roic": 0.31 } } ], "total": 1, "page": 1, "page_size": 50, "has_next": false }

11. Portfolio (Selection, Allocation & Correlation) 11. Carteira (Seleção, Alocação e Correlação)

Compose a portfolio over a given universe of stock codes — stateless, no Portfolio is created/edited via API. The read-only routes below are the one exception: they read (never write) portfolios already saved on the site.

Compõe uma carteira sobre um universo de códigos de ação dado — stateless, nenhum Portfolio é criado/editado via API. As rotas de leitura abaixo são a única exceção: leem (nunca escrevem) carteiras já salvas no site.

POST /api/v1/portfolio/select-stocks

Body: {universe: [codes], method, num_stocks, as_of?}. method: margin_of_safety_simple / margin_of_safety_dcf / cluster_margin_of_safety_simple / cluster_margin_of_safety_dcf / implied_growth / price_to_epv / cluster_implied_growth / cluster_price_to_epv.

Corpo: {universe: [codes], method, num_stocks, as_of?}. method: margin_of_safety_simple / margin_of_safety_dcf / cluster_margin_of_safety_simple / cluster_margin_of_safety_dcf / implied_growth / price_to_epv / cluster_implied_growth / cluster_price_to_epv.

POST /api/v1/portfolio/allocate-capital

Body: {stocks: [codes], method, as_of?}{allocations: [{code, weight}]}. method: equal / sharpe_max_dcf / sharpe_max_simple.

Corpo: {stocks: [codes], method, as_of?}{allocations: [{code, weight}]}. method: equal / sharpe_max_dcf / sharpe_max_simple.

POST /api/v1/portfolio/systemic-correlation

Body: {stocks: [codes], as_of?}{value} (variance share explained by the 1st principal component — systemic risk proxy).

Corpo: {stocks: [codes], as_of?}{value} (proporção da variância explicada pelo 1º componente principal — proxy de risco sistêmico).

POST /api/v1/portfolio/x-ray

Stateless prospect X-ray. Body: {positions: [{ticker, quantity, avg_price?} | {type: "fund", name, value, annual_fee?, fund_class?, benchmark?, benchmark_rate?} | {type: "fixed_income", name, value, indexer?, rate?}], as_of?, since?, alternative_portfolio_id?} (fund return is DECLARED via benchmark, net of fee; the alternative always comes from one of the user's saved portfolios — filters, stocks, methods and equity exposure as saved there, the rest earns CDI; without alternative_portfolio_id only the diagnosis is returned) → effective bets (HHI) by position and sector level, systemic correlation with its window, share of capital above the event-adjusted fair value, weighted margin of safety (each with value_coverage), events (90d), declared fund costs, buy-and-hold of the pasted portfolio vs IBOV/CDI, and alternative_spec — submit it verbatim to POST /api/v1/backtest. Unknown tickers land in unanalyzed with a reason (not 422). Nothing is stored.

Raio-X stateless do prospect. Corpo: {positions: [{ticker, quantity, avg_price?} | {type: "fund", name, value, annual_fee?, fund_class?, benchmark?, benchmark_rate?} | {type: "fixed_income", name, value, indexer?, rate?}], as_of?, since?, alternative_portfolio_id?} (retorno de fundo é DECLARADO via benchmark, líquido de taxa; a alternativa vem sempre de um portfólio salvo do usuário — filtros, ações, métodos e exposição à renda variável como salvos lá, o resto ao CDI; sem alternative_portfolio_id só o diagnóstico volta) → apostas efetivas (HHI) por posição e por nível setorial, correlação sistêmica com janela, fração do capital acima do preço justo ajustado por evento, margem ponderada (cada um com value_coverage), eventos (90d), custo declarado de fundos, buy-and-hold da carteira colada vs IBOV/CDI e alternative_spec — submeta tal qual a POST /api/v1/backtest. Ticker desconhecido vai pra unanalyzed com motivo (não é 422). Nada é gravado.

POST /api/v1/portfolio/x-ray/simulate

Stateless what-if over a portfolio. Body: {positions: [...same as x-ray], changes: [{ticker, operation: buy|sell, quantity | value} | {type: "fund"|"fixed_income", name, operation: deposit|withdraw, value, ...}], as_of?, alternative_portfolio_id?}current and simulated (two full X-rays, no buy-and-hold), delta per indicator (total value, effective bets, weighted margin, capital above fair value, systemic correlation, equity share, estimated annual income; delta: null when one side has no number), warnings (selling more than held zeroes the line — never 422), rejected_changes with index and reason, and estimated_income: an ESTIMATE from each stock's 5-year average dividend yield and the declared return of funds/fixed income, with coverage and exclusions — labelled, not a projection. Nothing is stored.

O "e se" stateless sobre uma carteira. Corpo: {positions: [...como no raio-X], changes: [{ticker, operation: buy|sell, quantity | value} | {type: "fund"|"fixed_income", name, operation: deposit|withdraw, value, ...}], as_of?, alternative_portfolio_id?}current e simulated (dois raio-X completos, sem buy-and-hold), delta por indicador (valor total, apostas efetivas, margem ponderada, capital acima do justo, correlação sistêmica, parcela em RV, renda anual estimada; delta: null quando um lado não tem o número), warnings (vender mais do que há zera a linha — nunca 422), rejected_changes com índice e motivo, e estimated_income: ESTIMATIVA pelo DY médio de 5 anos por ação e pelo retorno declarado de fundo/RF, com cobertura e exclusões — rotulada, não é projeção. Nada é gravado.

Saved portfolios (read-only — the only stateful endpoints in this API) Carteiras salvas (somente leitura — os únicos endpoints com estado desta API)

Read the portfolios/strategies the current user already saved on the site — no write. Requires an ApiKey issued with the read:portfolios scope (a Bearer session has full access, unrestricted by scope).

Lê as carteiras/estratégias que o usuário já salvou no site — sem nenhuma escrita. Exige uma ApiKey emitida com o escopo read:portfolios (uma sessão Bearer tem acesso total, sem restrição de escopo).

GET /api/v1/portfolios

Summary list of the user's own portfolios (no filters/stocks — see the detail route).

Lista resumida das carteiras do próprio usuário (sem filtros/ações — veja a rota de detalhe).

{ "portfolios": [ { "id": 1, "name": "Carteira Value", "num_stocks": 10, "total_investment": 5000.0, "auto_allocation": true, "auto_stock_allocation": true, "last_updated": "2024-06-01T12:00:00" } ] }
GET /api/v1/portfolios/{id}

Full detail — filters and manually added stocks included, translated to English. A portfolio ID belonging to another user (or that doesn't exist) returns 404.

Detalhe completo — filtros e ações adicionadas manualmente incluídos, traduzidos para inglês. Um ID de portfolio de outro usuário (ou inexistente) devolve 404.

{ "id": 1, "name": "Carteira Value", "variable_income_method": "fixed", "distribution_method": "equal", "stock_allocation_method": "margin_of_safety_simple", "filters": [{ "attribute": "margin_of_safety_simple", "min": 0.1, "max": null, "is_active": true }], "stocks": [{ "code": "PETR4", "allocation": 1.0 }] }

12. Backtest (Async Job) 12. Backtest (Job Assíncrono)

Fully parametrized point-in-time backtest — filters, selection/allocation method, date interval, step, optional rebalancing, output series, and a rolling-window (walk-forward) mode. Runs as an async job, since a single backtest can take minutes.

Backtest point-in-time totalmente parametrizado — filtros, método de seleção/alocação, intervalo de datas, cadência de passo, rebalanceamento opcional, séries de saída, e um modo de janela móvel (walk-forward). Roda como job assíncrono, já que um único backtest pode levar minutos.

POST /api/v1/backtest

Returns 202 {"job_id": "..."} immediately — the simulation runs in the background.

Devolve 202 {"job_id": "..."} imediatamente — a simulação roda em background.

{ "filters": [{ "attribute": "pe_ratio", "max": 15 }], "num_stocks": 10, "selection_method": "margin_of_safety_simple", "allocation_method": "equal", "variable_income_method": "fixed", "start_date": "2020-01-01", "end_date": "2024-01-01", "step_days": 30, "rebalance_every_n_steps": 1, "output_series": ["cdi", "portfolio_return", "sharpe_ratio"], "output_step_days": 7, // optional — display periodicity, distinct from step_days (rebalancing) "mode": "series" }

output_step_days is optional and distinct from step_days: step_days controls how often the portfolio is rebalanced, output_step_days controls how many points come back in chart_data (default: 1 per calendar day). Neither affects sharpe_ratio/total_return, always computed on the full daily series.

output_step_days é opcional e distinto de step_days: step_days controla a cadência de rebalanceamento, output_step_days controla quantos pontos voltam em chart_data (padrão: 1 por dia corrido). Nenhum dos dois afeta sharpe_ratio/total_return, sempre calculados sobre a série diária completa.

mode: "walk_forward" requires walk_forward_window_days and returns, once SUCCESS, {windows, win_rate, average_alpha, window_returns} instead of chart_datawin_rate is the share of windows with positive return, average_alpha is the simple mean return across windows (not a CAPM-style excess return).

mode: "walk_forward" exige walk_forward_window_days e devolve, quando SUCCESS, {windows, win_rate, average_alpha, window_returns} em vez de chart_datawin_rate é a proporção de janelas com retorno positivo, average_alpha é a média aritmética simples do retorno das janelas (não é excesso sobre benchmark no sentido CAPM).

GET /api/v1/backtest/{job_id}

Poll until state is terminal. percent is computed server-side.

Faça polling até state ficar terminal. percent já vem calculado no servidor.

{ "state": "PROGRESS", "progress": { "current": 4, "total": 10, "percent": 40 }, "result": null, "error": null }
Dedicated rate limit (5/minute) and a hard cap of 50 windows in walk-forward mode — this is the heaviest endpoint in the API. Rate limit dedicado (5/minuto) e um teto duro de 50 janelas no modo walk-forward — é o endpoint mais caro da API.

13. CVM Documents & Insiders 13. Documentos e Insiders CVM

Read-only access to the CVM regulatory document archive (Material Facts, Meetings, art. 11 insider filings...) — "list → open → excerpt", each step narrower than the last. Every response carrying text embeds a citation envelope (source_url is the original CVM download link) — provenance is always verifiable outside our database.

Acesso de leitura ao acervo de documentos regulatórios da CVM (Fatos Relevantes, Assembleias, formulários de insiders art. 11...) — "listar → abrir → recortar", cada passo mais estreito que o anterior. Toda resposta com texto embute um envelope de citação (source_url é o link de download original da CVM) — a procedência é sempre conferível fora do nosso banco.

GET /api/v1/companies/{cnpj}/documents

Paginated metadata of documents the company delivered to the CVM — never the full text. Metadado paginado dos documentos que a companhia entregou à CVM — nunca o texto integral.

Parameters Parâmetros
cnpj Required Company CNPJ. CNPJ da companhia.
category Optional One of: material_fact, market_announcement, shareholders_meeting, board_meeting, insider_trading, related_party_transaction. Uma de: material_fact, market_announcement, shareholders_meeting, board_meeting, insider_trading, related_party_transaction.
start_date / end_date Optional YYYY-MM-DD
include_superseded Optional Default false — only the current version per protocol; a restatement never appears twice. Default false — só a versão vigente por protocolo; uma retificação nunca aparece duas vezes.
page / page_size Optional
Example Request

GET /api/v1/companies/84.429.695/0001-11/documents?category=material_fact

Response Format
{ "items": [{ "document_id": 918234, "protocol": "PROT-001234", "version": 1, "category": "material_fact", "delivery_date": "2024-05-10", "reference_date": "2024-05-01", "company_cnpj": "84.429.695/0001-11", "source_url": "https://www.rad.cvm.gov.br/ENET/...", "text_status": "ok", "chars": 4213 }], "total": 1, "page": 1, "page_size": 50, "has_next": false }
GET /api/v1/documents/{document_id}

Returns a single document's citation envelope and text, capped at DOCUMENTO_API_MAX_CHARS (default 2,000,000 chars). truncated/total_chars are always present, not only when truncated. Devolve o envelope de citação e o texto de um documento, sob o teto de DOCUMENTO_API_MAX_CHARS (default 2.000.000 chars). truncated/total_chars sempre presentes, não só quando truncado.

Parameters Parâmetros
document_id Required document_id from the listing above. document_id da listagem acima.
Example Request

GET /api/v1/documents/918234

Response Format
{ "document_id": 918234, "protocol": "PROT-001234", "...": "(same citation fields as above)", "text": "Comunicamos aos nossos acionistas...", "truncated": false, "total_chars": 4213 }
GET /api/v1/documents/{document_id}/excerpt

Returns a character-offset excerpt of a document's text, sliced in the database (never loads the full column into Python — the longest document measured has 1,627,451 chars). Devolve um trecho do texto do documento por offset de caracteres, fatiado no banco (nunca carrega a coluna inteira em Python — o documento mais longo medido tem 1.627.451 chars).

Parameters Parâmetros
start / end Required Character offsets. Negative or end <= start → 422; offsets beyond total_chars are clamped, not an error. Offsets de caractere. Negativo ou end <= start → 422; offset além de total_chars é clampado, não é erro.
context Optional Extra characters of context around the excerpt. Default: DOCUMENTO_API_EXCERPT_CONTEXT. Caracteres extras de contexto ao redor do trecho. Default: DOCUMENTO_API_EXCERPT_CONTEXT.
Example Request

GET /api/v1/documents/918234/excerpt?start=120&end=340&context=50

Response Format
{ "start": 70, "end": 390, "text": "...trecho recortado...", "total_chars": 4213 }
GET /api/v1/companies/{cnpj}/insider-trades

Insider trading activity (art. 11), aggregated by group × month by default — derived from balance lines, never the free-text operation column. detail=raw returns paginated raw rows. Negociação de insiders (art. 11), agregada por grupo × mês por padrão — derivada das linhas de saldo, nunca da coluna de operação (texto livre). detail=raw devolve as linhas cruas paginadas.

Parameters Parâmetros
cnpj Required Company CNPJ. CNPJ da companhia.
detail Optional aggregated (default) or raw. aggregated (default) ou raw.
start_date / end_date Optional YYYY-MM-DD
Example Request

GET /api/v1/companies/84.429.695/0001-11/insider-trades

Response Format
{ "items": [{ "group": "executive_board", "month": "2024-05-01", "security": "Ações", "initial_position": 1000.0, "final_position": 1200.0, "net_change": 200.0, "net_change_pct": 20.0, "citation": "(citation envelope)" }], "gaps": [{ "month": "2024-03-01", "parse_status": "estrutura_nao_reconhecida" }] }

14. Consolidated Analysis 14. Análise Consolidada

The four analysis layers in a single object: derived verdict, fundamentals, event timeline, the document-to-assumption bridge (same shape and ids as the valuation adjustments cascade — do not sum the two) and the critique. Every embedded citation uses the same DocumentCitation envelope: its document_id is accepted by the documents endpoints without translation.

As quatro camadas de análise num objeto único: veredito derivado, fundamento, linha do tempo de eventos, a ponte documento→premissa (mesmo shape e ids da cascata de valuation/adjustments — não some as duas) e a crítica. Toda citação embutida usa o mesmo envelope DocumentCitation: o document_id é aceito pelas rotas de documentos sem tradução.

GET /api/v1/stocks/{code}/analysis

Returns the consolidated analysis for a stock. A company with no usable target price returns 200 with verdict.label = "no_verdict" — signals and weaknesses stay visible; absence is an answer, never a 404. Devolve a análise consolidada de uma ação. Empresa sem preço-alvo utilizável devolve 200 com verdict.label = "no_verdict" — sinais e fragilidades continuam visíveis; ausência é resposta, nunca 404.

Parameters Parâmetros
code Required Stock ticker (e.g. VALE3). Ticker da ação (ex. VALE3).
as_of Optional YYYY-MM-DD — rebuilds the analysis as it was at that date (computed on demand, does not touch the event-invalidated cache). YYYY-MM-DD — remonta a análise como ela era naquela data (sob demanda, sem tocar o cache invalidado por evento).
Response shape Forma da resposta

verdict (label: bought_with_margin | neutral | thesis_under_pressure | no_verdict), fundamentals (indicators + criteria, the full fundamentals board with quarter/year deltas), events (90-day window + insider aggregate), bridge (adjustments / signals / external_price_references), critique (derived weaknesses, essay — the offline critic's long-form thesis critique with skeptic_verdict, plus suggested_assumptions — DCF assumptions suggested by the critic, pre-executed by the engine; a third reference that never replaces the engine target) and sources.total. Descriptions stay in Portuguese — editorial prose is not translated. verdict (label: bought_with_margin | neutral | thesis_under_pressure | no_verdict), fundamentals (indicadores + criteria, o quadro completo com deltas de trimestre/ano), events (janela de 90 dias + agregado de insiders), bridge (adjustments / signals / external_price_references), critique (fragilidades deriváveis, essay — o ensaio do crítico offline com skeptic_verdict, mais suggested_assumptions — premissas de DCF sugeridas pelo crítico, pré-executadas pelo motor; terceira referência que nunca substitui o alvo do motor) e sources.total. Descrições ficam em português — prosa editorial não se traduz.

GET /api/v1/stocks/VALE3/analysis

Verdicts board

GET /api/v1/analysis/verdicts?verdict=&skeptic_verdict=&page=&page_size=

Compact board over the materialized analyses: global tally for both verdict axes, coverage (materialized vs. active universe) and paginated items (ticker, verdict, margin_of_safety, skeptic_verdict, judged_at). skeptic_verdict is the critic's sealed Portuguese vocabulary — comprar | aguardar | descartar; null = not judged yet. Current state only (no as_of).

Placar compacto sobre as análises materializadas: tally global dos dois eixos de veredito, coverage (materializado vs. universo ativo) e items paginado (ticker, verdict, margin_of_safety, skeptic_verdict, judged_at). skeptic_verdict é o vocabulário PT lacrado do crítico — comprar | aguardar | descartar; null = ainda não julgada. Só estado corrente (sem as_of).

15. MCP (AI Agents) 15. MCP (Agentes de IA)

The platform exposes a remote MCP server (Model Context Protocol) so AI agents — Claude Code, Codex and any MCP-capable client — can use the API as native tools: screener, consolidated analysis, valuation with custom assumptions, valuation anchors, CVM documents with citation excerpts, insiders, portfolio selection/allocation and backtest. Nothing to install: generate a key on your Account page (menu → Conta → "Chaves de API") and paste the URL and the key into the client.

A plataforma expõe um servidor MCP (Model Context Protocol) remoto para agentes de IA — Claude Code, Codex e qualquer client compatível — usarem a API como ferramentas nativas: screener, análise consolidada, valuation com premissas customizadas, âncoras de valuation, documentos CVM com recorte de citações, insiders, seleção/alocação de carteira e backtest. Nada para instalar: gere uma chave na sua página de Conta (menu → Conta → "Chaves de API") e cole a URL e a chave no client.

MCP https://www.strategiainvest.com.br/mcp
Claude Code Claude Code
claude mcp add --transport http strategia https://www.strategiainvest.com.br/mcp \ --header "Authorization: ApiKey <your-api-key>"
Codex
codex mcp add strategia --url https://www.strategiainvest.com.br/mcp \ --bearer-token-env-var STRATEGIA_API_KEY

Equivalent in ~/.codex/config.toml: Equivalente em ~/.codex/config.toml:

[mcp_servers.strategia] url = "https://www.strategiainvest.com.br/mcp" bearer_token_env_var = "STRATEGIA_API_KEY"
Authentication & limits Autenticação e limites
  • The credential is the same ApiKey from section 1 — the server stores nothing and forwards your key on every call, so the API rate limit (120/min per credential) applies as usual. Clients that only send Bearer (like Codex) work: the server normalizes the scheme. A credencial é a mesma ApiKey da seção 1 — o servidor não armazena nada e repassa a sua chave em cada chamada, então o rate limit da API (120/min por credencial) vale normalmente. Clients que só enviam Bearer (como o Codex) funcionam: o servidor normaliza o esquema.
  • Advisor DCF tools additionally require the advisor role and the read:advisor-dcf / write:advisor-dcf scopes on the key. The client book (/v1/advisor/clients*) uses read:advisor-book / write:advisor-book, and issuing a client note requires write:advisor-notes — MCP never issues notes. Monitored theses and their alerts (/v1/advisor/theses*, /v1/advisor/alerts*) use read:advisor-theses / write:advisor-theses; the MCP reads alerts with list_alerts and never phrases them as orders. Alerts also carry the radar (source=event: a material event in a stock held by the advisor's clients, with measured class/weight, score by exposure and the CVM citation). The portfolio calendar (GET /v1/advisor/clients/<id>/calendar, GET /v1/advisor/calendar, scope read:advisor-book) lists announced dividends, called meetings and the next filing estimated from the company's seasonality (estimated: true); MCP get_calendar and simulate_portfolio read them. Memory (/v1/advisor/clients/<id>/decisions*, …/attribution, /v1/advisor/attribution, …/meeting-materials) uses the book scopes; issuing a meeting material requires write:advisor-notes. The decision trail is append-only with a SHA-256 per row; attribution is private to the advisor (counterfactuals are mechanical arithmetic, never a judgement); MCP get_decisions and get_attribution read them and never issue materials. As ferramentas de DCF do assessor exigem, além do papel de assessor, os escopos read:advisor-dcf / write:advisor-dcf na chave. O book de clientes (/v1/advisor/clients*) usa read:advisor-book / write:advisor-book, e emitir nota ao cliente exige write:advisor-notes — o MCP nunca emite nota. A tese monitorada e seus alertas (/v1/advisor/theses*, /v1/advisor/alerts*) usam read:advisor-theses / write:advisor-theses; o MCP lê alertas com list_alerts e nunca os fraseia como ordem. Os alertas trazem também o radar (source=event: evento material num papel dos clientes do assessor, com classe/peso medidos, score pela exposição e a citação CVM). A agenda da carteira (GET /v1/advisor/clients/<id>/calendar, GET /v1/advisor/calendar, escopo read:advisor-book) lista proventos anunciados, assembleias convocadas e o próximo balanço estimado pela sazonalidade da empresa (estimated: true); no MCP, get_calendar e simulate_portfolio. A memória (/v1/advisor/clients/<id>/decisions*, …/attribution, /v1/advisor/attribution, …/meeting-materials) usa os escopos do book; emitir material de reunião exige write:advisor-notes. A trilha de decisão é append-only com SHA-256 por linha; a atribuição é privada do assessor (contrafactuais são aritmética, nunca julgamento); no MCP, get_decisions e get_attribution leem e nunca emitem material.
  • Tools default to compact responses (e.g. analysis with sections=verdict,critique) so a full research session fits comfortably in an agent's context window; every tool accepts the same parameters documented on this page. As ferramentas usam respostas compactas por padrão (ex. análise com sections=verdict,critique) para uma sessão inteira de pesquisa caber com folga na janela de contexto do agente; cada ferramenta aceita os mesmos parâmetros documentados nesta página.
Listar Filtrar Portfólios