partnr
v0.1.0
Published
Official TypeScript SDK for Partnr API v2 - Brazilian financial data
Maintainers
Readme
partnr
Official TypeScript SDK for Partnr API v2 - Brazilian financial data.
Installation
npm install partnr
# or
yarn add partnr
# or
pnpm add partnrQuickstart
import { PartnrClient } from "partnr";
// Auto-detects PARTNR_API_KEY from environment
const client = new PartnrClient();
// Or provide explicitly
const client2 = new PartnrClient({
apiKey: "your-api-key",
});
// Get company details
const company = await client.companies.get("PETR3");
console.log(company.trading_name); // PETROBRAS
// Get historical quotes
const quotes = await client.quotes.getHistoricalQuotes("PETR4");
console.log(quotes[0].close_price);Configuration
const client = new PartnrClient({
apiKey: "your-api-key", // Required
baseUrl: "https://data.partnr.ai/v2/", // Optional, default
timeoutMs: 30000, // Optional, default 30s
maxRetries: 2, // Optional, default 2
headers: {
// Optional extra headers
"X-Custom-Header": "value",
},
});Examples
List Companies
// List all companies
const companies = await client.companies.list();
// With optional fields
const companiesWithSector = await client.companies.list({
show_sector: true,
show_market_cap: true,
});
// Access sector and market cap
for (const company of companiesWithSector) {
console.log(company.symbol, company.sector?.name, company.market_cap?.value);
}Get Company by Identifier
// You can use symbol, company_id (CNPJ), or ticker
const company = await client.companies.get("PETR3");
const company2 = await client.companies.get("PETR");
const company3 = await client.companies.get("33000167000101");
// With optional fields
const companyFull = await client.companies.get("PETR3", {
show_market_cap: true,
show_logo: true,
show_company_details: true,
});
// Market cap is an object with value and format
console.log(companyFull.market_cap?.value); // 497465651767
console.log(companyFull.market_cap?.format); // "BRL 497,465,651,767"Historical Quotes
// Get historical quote data
const quotes = await client.quotes.getHistoricalQuotes("PETR4", {
start_date: "2024-01-01",
end_date: "2024-12-31",
adjusted: true, // Adjust for dividends and corporate actions
});
for (const quote of quotes) {
console.log(`${quote.date}: ${quote.close_price} (vol: ${quote.volume})`);
}List and Get News
// List recent news
const news = await client.news.list({ limit: 10 });
// Filter by entity (ticker, sector, etc.)
const petrNews = await client.news.list({ query: "PETR4", limit: 5 });
// Get full article with summary and entities
const article = await client.news.get(news[0].id);
console.log(article.summary);
console.log(article.key_points);Paginate Through News
// Using async iterator
for await (const article of client.news.iterate({ limit: 20 })) {
console.log(article.title);
// Automatically fetches next page when needed
}Run Screener with Filters
const results = await client.screener.run({
orderBy: "droplet:PRICE_TO_EARNINGS",
order: "asc",
limit: 10,
primaryOnly: true,
filters: [
{ type: "close_price", op: ">=", value: 5 },
{ type: "sector", in: ["BANKING", "TECHNOLOGY"] },
{ type: "droplet:PRICE_TO_EARNINGS", op: "<", value: 15 },
],
});
for (const item of results.data) {
console.log(`${item.ticker}: R$ ${item.current_price}`);
}Financial Reports and Ratios
// Get standardized reports
const reports = await client.companies.getReports("PETR3", {
section: "INCOME_STATEMENT",
frequency: "QUARTERLY",
aggregation: "CONSOLIDATED",
});
// Get financial ratios
const ratios = await client.companies.getRatios("PETR3", {
ids: "EBITDA_MARGIN,ROE,NET_MARGIN",
frequency: "TTM",
});
// Get valuation ratios
const valuation = await client.companies.getValuationRatios("PETR3", {
ids: "PRICE_TO_EARNINGS,PRICE_TO_BOOK",
});Traded Funds (FIIs, ETFs)
// List all traded funds
const funds = await client.tradedFunds.list();
// Iterate through all funds
for await (const fund of client.tradedFunds.iterate()) {
console.log(`${fund.symbol}: ${fund.name}`);
}
// Get fund details
const hglg = await client.tradedFunds.get("HGLG11");
console.log(hglg.dividend_yield_12m);Macroeconomic Indicators
// List available indicators
const indicators = await client.macroeconomics.listIndicators();
// Get indicator series
const selic = await client.macroeconomics.getIndicatorSeries("INTEREST_RATE", {
country: "BRA",
unit: "ANNUAL",
limit: 12,
});
for (const point of selic) {
console.log(`${point.date}: ${point.value}%`);
}Daily Variations
const variations = await client.stocks.getVariations();
console.log("Top gainers:");
for (const stock of variations.highs.slice(0, 5)) {
console.log(`${stock.ticker}: +${(stock.variation * 100).toFixed(2)}%`);
}
console.log("Top losers:");
for (const stock of variations.lows.slice(0, 5)) {
console.log(`${stock.ticker}: ${(stock.variation * 100).toFixed(2)}%`);
}Error Handling
All errors include the requestId for debugging with Partnr support.
import {
PartnrClient,
ApiError,
AuthenticationError,
NotFoundError,
RateLimitError,
ValidationError,
ServerError,
} from "partnr";
try {
const company = await client.companies.get("INVALID");
} catch (error) {
if (error instanceof AuthenticationError) {
console.error("Invalid API key");
} else if (error instanceof NotFoundError) {
console.error("Company not found");
} else if (error instanceof RateLimitError) {
console.error("Rate limit exceeded, try again later");
} else if (error instanceof ValidationError) {
console.error("Invalid request parameters");
} else if (error instanceof ServerError) {
console.error("Server error, try again later");
} else if (error instanceof ApiError) {
console.error(`API Error: ${error.message}`);
}
// Always log the Request-Id for debugging
if (error instanceof ApiError) {
console.error(`Request-Id: ${error.requestId}`);
console.error(`Status: ${error.status}`);
console.error(`Code: ${error.code}`);
}
}Retries
The SDK automatically retries on:
- 429 (Rate Limit) - respects
Retry-Afterheader (supports both seconds and HTTP-date format) - 5xx (Server Errors)
- Network timeouts and failures
No retries on 4xx errors (except 429).
const client = new PartnrClient({
apiKey: "your-api-key",
maxRetries: 3, // Retry up to 3 times
timeoutMs: 60000, // 60s timeout
});Request/Response Hooks
Add logging, metrics, or custom behavior:
// Log all requests
client.setRequestHook((url, options) => {
console.log(`[${options.method}] ${url}`);
});
// Log all responses with timing
client.setResponseHook((url, response, durationMs) => {
console.log(`[${response.status}] ${url} - ${durationMs}ms`);
});Client Lifecycle
Close the client to abort all pending requests:
const client = new PartnrClient({ apiKey: "your-api-key" });
try {
// Use the client...
const company = await client.companies.get("PETR3");
} finally {
client.close(); // Abort all pending requests
}
// Check if closed
console.log(client.closed); // trueTypeScript Support
Full TypeScript support with exported types:
import type {
Company,
CompanyListItem,
Quote,
NewsArticle,
ScreenerResponse,
ScreenerFilter,
TradedFund,
MacroIndicator,
} from "partnr";Requirements
- Node.js >= 18.0.0 (uses native fetch)
License
MIT
