fmp-node-api 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4182 +1,2 @@
1
- 'use strict';
2
-
3
- var axios = require('axios');
4
-
5
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
-
7
- var axios__default = /*#__PURE__*/_interopDefault(axios);
8
-
9
- // src/client.ts
10
- function unwrapSingleObject(data) {
11
- if (Array.isArray(data) && data.length === 1) {
12
- return data[0];
13
- }
14
- return data;
15
- }
16
- function normalizeArrayResponse(data) {
17
- if (Array.isArray(data)) return data;
18
- if (data == null) return [];
19
- return data;
20
- }
21
- function normalizeObjectResponse(data) {
22
- if (data == null) return {};
23
- if (Array.isArray(data) && data.length === 0) return {};
24
- return data;
25
- }
26
- var FMPClient = class {
27
- constructor(config) {
28
- if (!config.apiKey) {
29
- throw new Error("API key is required for FMPClient");
30
- }
31
- this.apiKey = config.apiKey;
32
- this.v3Client = axios__default.default.create({
33
- baseURL: "https://financialmodelingprep.com/api/v3",
34
- timeout: config.timeout || 1e4,
35
- headers: { "Content-Type": "application/json" }
36
- });
37
- this.v4Client = axios__default.default.create({
38
- baseURL: "https://financialmodelingprep.com/api/v4",
39
- timeout: config.timeout || 1e4,
40
- headers: { "Content-Type": "application/json" }
41
- });
42
- this.stableClient = axios__default.default.create({
43
- baseURL: "https://financialmodelingprep.com/stable",
44
- timeout: config.timeout || 1e4,
45
- headers: { "Content-Type": "application/json" }
46
- });
47
- [this.v3Client, this.v4Client, this.stableClient].forEach((client) => {
48
- client.interceptors.request.use((config2) => {
49
- config2.params = { ...config2.params, apikey: this.apiKey };
50
- return config2;
51
- });
52
- });
53
- }
54
- /**
55
- * Standard get method - returns raw API response
56
- *
57
- * For endpoints that return arrays, this will always return an array (possibly empty) for `data` when success is true.
58
- * For endpoints that return objects, data is returned as-is.
59
- */
60
- async get(endpoint, version = "v3", params) {
61
- const client = this.getClientForVersion(version);
62
- try {
63
- const response = await client.get(endpoint, { params });
64
- let data = response.data;
65
- if (Array.isArray(data) || data == null) {
66
- data = normalizeArrayResponse(data);
67
- }
68
- return {
69
- success: true,
70
- data,
71
- error: null,
72
- status: response.status
73
- };
74
- } catch (error) {
75
- return {
76
- success: false,
77
- data: null,
78
- error: error.message || "Unknown error occurred",
79
- status: error.response?.status || 500
80
- };
81
- }
82
- }
83
- /**
84
- * Get method for single-object endpoints - unwraps single-item arrays
85
- *
86
- * For endpoints that return single objects, this will always return an object (possibly empty) for `data` when success is true.
87
- */
88
- async getSingle(endpoint, version = "v3", params) {
89
- const client = this.getClientForVersion(version);
90
- try {
91
- const response = await client.get(endpoint, { params });
92
- const data = normalizeObjectResponse(unwrapSingleObject(response.data));
93
- return {
94
- success: true,
95
- data,
96
- error: null,
97
- status: response.status
98
- };
99
- } catch (error) {
100
- return {
101
- success: false,
102
- data: null,
103
- error: error.message || "Unknown error occurred",
104
- status: error.response?.status || 500
105
- };
106
- }
107
- }
108
- getClientForVersion(version) {
109
- switch (version) {
110
- case "v3":
111
- return this.v3Client;
112
- case "v4":
113
- return this.v4Client;
114
- case "stable":
115
- return this.stableClient;
116
- default:
117
- return this.v3Client;
118
- }
119
- }
120
- };
121
-
122
- // src/utils/validation.ts
123
- var FMPValidation = class {
124
- /**
125
- * Validate stock symbol format
126
- * @param symbol - The symbol to validate
127
- * @returns True if the symbol format is valid
128
- */
129
- static isValidSymbol(symbol) {
130
- if (!symbol || typeof symbol !== "string") {
131
- return false;
132
- }
133
- return /^[A-Z]{1,5}$/.test(symbol);
134
- }
135
- /**
136
- * Validate crypto symbol format
137
- * @param symbol - The crypto symbol to validate
138
- * @returns True if the crypto symbol format is valid
139
- */
140
- static isValidCryptoSymbol(symbol) {
141
- if (!symbol || typeof symbol !== "string") {
142
- return false;
143
- }
144
- return /^[A-Z]{2,10}(USD|EUR|GBP|JPY|CAD|AUD|CHF|CNY)$/.test(symbol);
145
- }
146
- /**
147
- * Validate forex pair format
148
- * @param symbol - The forex pair to validate
149
- * @returns True if the forex pair format is valid
150
- */
151
- static isValidForexPair(symbol) {
152
- if (!symbol || typeof symbol !== "string") {
153
- return false;
154
- }
155
- return /^[A-Z]{3}[A-Z]{3}$/.test(symbol);
156
- }
157
- /**
158
- * Validate date format (YYYY-MM-DD)
159
- * @param date - The date string to validate
160
- * @returns True if the date format is valid
161
- */
162
- static isValidDate(date) {
163
- if (!date || typeof date !== "string") {
164
- return false;
165
- }
166
- const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
167
- if (!dateRegex.test(date)) {
168
- return false;
169
- }
170
- const dateObj = new Date(date);
171
- return !isNaN(dateObj.getTime()) && dateObj.toISOString().split("T")[0] === date;
172
- }
173
- /**
174
- * Validate date range
175
- * @param from - Start date
176
- * @param to - End date
177
- * @returns True if the date range is valid
178
- */
179
- static isValidDateRange(from, to) {
180
- if (!this.isValidDate(from) || !this.isValidDate(to)) {
181
- return false;
182
- }
183
- const fromDate = new Date(from);
184
- const toDate = new Date(to);
185
- return fromDate <= toDate;
186
- }
187
- /**
188
- * Validate API response structure
189
- * @param response - The response to validate
190
- * @returns True if the response has the expected structure
191
- */
192
- static isValidResponse(response) {
193
- return Boolean(
194
- response && typeof response === "object" && typeof response.success === "boolean"
195
- );
196
- }
197
- /**
198
- * Validate API key format
199
- * @param apiKey - The API key to validate
200
- * @returns True if the API key format is valid
201
- */
202
- static isValidApiKey(apiKey) {
203
- if (!apiKey || typeof apiKey !== "string") {
204
- return false;
205
- }
206
- return /^[a-zA-Z0-9]{32,}$/.test(apiKey);
207
- }
208
- /**
209
- * Validate period parameter
210
- * @param period - The period to validate
211
- * @returns True if the period is valid
212
- */
213
- static isValidPeriod(period) {
214
- if (!period || typeof period !== "string") {
215
- return false;
216
- }
217
- return ["annual", "quarter", "fy"].includes(period.toLowerCase());
218
- }
219
- /**
220
- * Validate limit parameter
221
- * @param limit - The limit to validate
222
- * @returns True if the limit is valid
223
- */
224
- static isValidLimit(limit) {
225
- return typeof limit === "number" && Number.isInteger(limit) && limit > 0 && limit <= 1e3;
226
- }
227
- /**
228
- * Get validation errors for quote parameters
229
- * @param params - The parameters to validate
230
- * @returns Array of validation error messages
231
- */
232
- static validateQuoteParams(params) {
233
- const errors = [];
234
- if (!params) {
235
- errors.push("Parameters object is required");
236
- return errors;
237
- }
238
- if (!params.symbol) {
239
- errors.push("Symbol is required");
240
- } else if (!this.isValidSymbol(params.symbol) && !this.isValidCryptoSymbol(params.symbol) && !this.isValidForexPair(params.symbol)) {
241
- errors.push("Invalid symbol format");
242
- }
243
- if (params.from && !this.isValidDate(params.from)) {
244
- errors.push("Invalid from date format (expected YYYY-MM-DD)");
245
- }
246
- if (params.to && !this.isValidDate(params.to)) {
247
- errors.push("Invalid to date format (expected YYYY-MM-DD)");
248
- }
249
- if (params.from && params.to && !this.isValidDateRange(params.from, params.to)) {
250
- errors.push("From date must be before or equal to to date");
251
- }
252
- return errors;
253
- }
254
- /**
255
- * Get validation errors for financial statement parameters
256
- * @param params - The parameters to validate
257
- * @returns Array of validation error messages
258
- */
259
- static validateFinancialParams(params) {
260
- const errors = [];
261
- if (!params) {
262
- errors.push("Parameters object is required");
263
- return errors;
264
- }
265
- if (!params.symbol) {
266
- errors.push("Symbol is required");
267
- } else if (!this.isValidSymbol(params.symbol)) {
268
- errors.push("Invalid symbol format");
269
- }
270
- if (params.period && !this.isValidPeriod(params.period)) {
271
- errors.push('Invalid period (must be "annual", "quarter", or "FY")');
272
- }
273
- if (params.limit && !this.isValidLimit(params.limit)) {
274
- errors.push("Invalid limit (must be a positive integer <= 1000)");
275
- }
276
- return errors;
277
- }
278
- /**
279
- * Get validation errors for date range parameters
280
- * @param params - The parameters to validate
281
- * @returns Array of validation error messages
282
- */
283
- static validateDateRangeParams(params) {
284
- const errors = [];
285
- if (!params) {
286
- errors.push("Parameters object is required");
287
- return errors;
288
- }
289
- if (params.from && !this.isValidDate(params.from)) {
290
- errors.push("Invalid from date format (expected YYYY-MM-DD)");
291
- }
292
- if (params.to && !this.isValidDate(params.to)) {
293
- errors.push("Invalid to date format (expected YYYY-MM-DD)");
294
- }
295
- if (params.from && params.to && !this.isValidDateRange(params.from, params.to)) {
296
- errors.push("From date must be before or equal to to date");
297
- }
298
- return errors;
299
- }
300
- /**
301
- * Validate and throw error if validation fails
302
- * @param errors - Array of validation errors
303
- * @param context - Context for the error message
304
- */
305
- static throwIfInvalid(errors, context = "Validation") {
306
- if (errors.length > 0) {
307
- throw new Error(`${context} failed: ${errors.join(", ")}`);
308
- }
309
- }
310
- };
311
-
312
- // src/endpoints/stock.ts
313
- var StockEndpoints = class {
314
- constructor(client) {
315
- this.client = client;
316
- }
317
- /**
318
- * Get current market capitalization for a stock
319
- *
320
- * Market capitalization represents the total value of a company's outstanding shares.
321
- * Calculated by multiplying the current share price by the number of outstanding shares.
322
- * This metric is crucial for understanding a company's size and market position.
323
- *
324
- * @param symbol - The stock symbol to get market cap for (e.g., 'AAPL', 'MSFT', 'GOOGL')
325
- *
326
- * @returns Promise resolving to market cap data including symbol, date, and market cap value
327
- *
328
- * @example
329
- * ```typescript
330
- * // Get market cap for Apple
331
- * const marketCap = await fmp.stock.getMarketCap('AAPL');
332
- * console.log(`Apple's market cap: $${marketCap.data.marketCap.toLocaleString()}`);
333
- *
334
- * // Get market cap for Microsoft
335
- * const msftCap = await fmp.stock.getMarketCap('MSFT');
336
- * ```
337
- *
338
- * @see {@link https://site.financialmodelingprep.com/developer/docs#market-cap-company-information|FMP Market Cap Documentation}
339
- */
340
- async getMarketCap(symbol) {
341
- return this.client.getSingle(`/market-capitalization/${symbol}`, "v3");
342
- }
343
- /**
344
- * Get historical stock splits for a company
345
- *
346
- * Stock splits occur when a company increases the number of shares by dividing existing shares.
347
- * This endpoint provides the complete history of stock splits including dates, ratios, and split types.
348
- * Useful for adjusting historical price data and understanding corporate actions.
349
- *
350
- * @param symbol - The stock symbol to get split history for (e.g., 'AAPL', 'TSLA', 'NVDA')
351
- *
352
- * @returns Promise resolving to historical stock splits with dates, labels, and split ratios
353
- *
354
- * @example
355
- * ```typescript
356
- * // Get Apple's split history
357
- * const splits = await fmp.stock.getStockSplits('AAPL');
358
- * splits.data.historical.forEach(split => {
359
- * console.log(`${split.date}: ${split.numerator}:${split.denominator} split`);
360
- * });
361
- *
362
- * // Get Tesla's split history
363
- * const teslaSplits = await fmp.stock.getStockSplits('TSLA');
364
- * ```
365
- *
366
- * @see {@link https://site.financialmodelingprep.com/developer/docs#splits-historical-splits|FMP Stock Splits Documentation}
367
- */
368
- async getStockSplits(symbol) {
369
- return this.client.get(`/historical-price-full/stock_split/${symbol}`, "v3");
370
- }
371
- /**
372
- * Get historical dividend payments for a stock
373
- *
374
- * Dividends are periodic payments made by companies to shareholders from profits.
375
- * This endpoint provides the complete dividend history including payment dates, amounts,
376
- * and important dates like ex-dividend, record, and declaration dates.
377
- *
378
- * @param symbol - The stock symbol to get dividend history for (e.g., 'KO', 'JNJ', 'PG')
379
- *
380
- * @returns Promise resolving to dividend history with payment details and important dates
381
- *
382
- * @example
383
- * ```typescript
384
- * // Get Coca-Cola's dividend history
385
- * const dividends = await fmp.stock.getDividendHistory('KO');
386
- * dividends.data.historical.forEach(dividend => {
387
- * console.log(`${dividend.date}: $${dividend.dividend} per share`);
388
- * });
389
- *
390
- * // Get Johnson & Johnson's dividend history
391
- * const jnjDividends = await fmp.stock.getDividendHistory('JNJ');
392
- * ```
393
- *
394
- * @see {@link https://site.financialmodelingprep.com/developer/docs#dividends-historical-dividends|FMP Dividends Documentation}
395
- */
396
- async getDividendHistory(symbol) {
397
- return this.client.getSingle(`/historical-price-full/stock_dividend/${symbol}`, "v3");
398
- }
399
- /**
400
- * Get real-time stock prices for multiple symbols
401
- *
402
- * Provides current market prices for stocks with minimal data overhead.
403
- * Returns basic price information including symbol and current price.
404
- * Ideal for quick price checks and portfolio monitoring.
405
- *
406
- * @param symbols - Array of stock symbols to get real-time prices for
407
- *
408
- * @returns Promise resolving to array of real-time price data with symbol and price
409
- *
410
- * @example
411
- * ```typescript
412
- * // Get prices for multiple tech stocks
413
- * const prices = await fmp.stock.getRealTimePrice([
414
- * 'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA'
415
- * ]);
416
- *
417
- * prices.data.forEach(stock => {
418
- * console.log(`${stock.symbol}: $${stock.price}`);
419
- * });
420
- *
421
- * // Get price for single stock
422
- * const aaplPrice = await fmp.stock.getRealTimePrice(['AAPL']);
423
- * ```
424
- */
425
- async getRealTimePrice(symbols) {
426
- const url = `stock/real-time-price/${symbols.join(",")}`;
427
- const result = await this.client.get(url, "v3");
428
- if (result.success && result.data && !Array.isArray(result.data)) {
429
- const data = result.data;
430
- if (typeof data === "object" && data !== null && "companiesPriceList" in data && Array.isArray(data.companiesPriceList)) {
431
- const filteredData2 = data.companiesPriceList.filter((item) => item && item.symbol);
432
- if (filteredData2.length > 0) {
433
- return { ...result, data: filteredData2 };
434
- }
435
- }
436
- if (typeof data === "object" && data !== null && "stockList" in data && Array.isArray(data.stockList)) {
437
- const filteredData2 = data.stockList.filter((item) => item && item.symbol);
438
- if (filteredData2.length > 0) {
439
- return { ...result, data: filteredData2 };
440
- }
441
- }
442
- if (data.symbol) {
443
- return { ...result, data: [data] };
444
- }
445
- if (symbols.length === 1) {
446
- console.warn(`No real-time price data found for symbol: ${symbols[0]}`);
447
- }
448
- return { ...result, data: [] };
449
- }
450
- const filteredData = result.data.filter((item) => item && item.symbol);
451
- return { ...result, data: filteredData };
452
- }
453
- /**
454
- * Get comprehensive real-time stock data for multiple symbols
455
- *
456
- * Provides detailed real-time market data including bid/ask prices, volume, trade sizes,
457
- * and timestamps. This endpoint offers much more information than the basic real-time price.
458
- * Perfect for trading applications, market analysis, and detailed price monitoring.
459
- *
460
- * @param symbols - Array of stock symbols to get detailed real-time data for
461
- *
462
- * @returns Promise resolving to array of detailed real-time data including bid/ask, volume, and timestamps
463
- *
464
- * @example
465
- * ```typescript
466
- * // Get detailed data for multiple stocks
467
- * const detailedData = await fmp.stock.getRealTimePriceForMultipleStocks([
468
- * 'AAPL', 'MSFT', 'GOOGL'
469
- * ]);
470
- *
471
- * detailedData.data.forEach(stock => {
472
- * console.log(`${stock.symbol}:`);
473
- * console.log(` Bid: $${stock.bidPrice} (${stock.bidSize} shares)`);
474
- * console.log(` Ask: $${stock.askPrice} (${stock.askSize} shares)`);
475
- * console.log(` Last: $${stock.lastSalePrice} (${stock.lastSaleSize} shares)`);
476
- * console.log(` Volume: ${stock.volume.toLocaleString()}`);
477
- * });
478
- *
479
- * // Get detailed data for single stock
480
- * const aaplDetailed = await fmp.stock.getRealTimePriceForMultipleStocks(['AAPL']);
481
- * ```
482
- *
483
- * @see {@link https://site.financialmodelingprep.com/developer/docs#real-time-full-price-quote|FMP Real-Time Full Price Documentation}
484
- */
485
- async getRealTimePriceForMultipleStocks(symbols) {
486
- const url = `stock/full/real-time-price/${symbols.join(",")}`;
487
- const result = await this.client.get(url, "v3");
488
- if (result.success && result.data && !Array.isArray(result.data)) {
489
- const data = result.data;
490
- if (typeof data === "object" && data !== null && "companiesPriceList" in data && Array.isArray(data.companiesPriceList)) {
491
- const filteredData2 = data.companiesPriceList.filter((item) => item && item.symbol);
492
- if (filteredData2.length > 0) {
493
- return { ...result, data: filteredData2 };
494
- }
495
- }
496
- if (typeof data === "object" && data !== null && "stockList" in data && Array.isArray(data.stockList)) {
497
- const filteredData2 = data.stockList.filter((item) => item && item.symbol);
498
- if (filteredData2.length > 0) {
499
- return { ...result, data: filteredData2 };
500
- }
501
- }
502
- if (data.symbol) {
503
- return { ...result, data: [data] };
504
- }
505
- if (symbols.length === 1) {
506
- console.warn(`No full real-time price data found for symbol: ${symbols[0]}`);
507
- }
508
- return { ...result, data: [] };
509
- }
510
- const filteredData = result.data.filter(
511
- (item) => item && item.symbol
512
- );
513
- return { ...result, data: filteredData };
514
- }
515
- };
516
-
517
- // src/endpoints/financial.ts
518
- var FinancialEndpoints = class {
519
- constructor(client) {
520
- this.client = client;
521
- }
522
- /**
523
- * Get income statement data
524
- *
525
- * Provides comprehensive income statement data including revenue, expenses,
526
- * net income, and earnings per share. Essential for analyzing company
527
- * profitability, revenue trends, and financial performance over time.
528
- *
529
- * @param params - Income statement request parameters
530
- * @param params.symbol - The stock symbol to get income statement for (e.g., 'AAPL', 'MSFT', 'GOOGL')
531
- * @param params.period - The reporting period: 'annual' or 'quarter' (default: 'annual')
532
- * @param params.limit - Number of periods to retrieve (default: 5)
533
- *
534
- * @returns Promise resolving to array of income statement data with financial metrics
535
- *
536
- * @example
537
- * ```typescript
538
- * // Get annual income statements for Apple
539
- * const incomeStatements = await fmp.financial.getIncomeStatement({ symbol: 'AAPL' });
540
- * incomeStatements.data.forEach(statement => {
541
- * console.log(`${statement.date}: Revenue $${statement.revenue.toLocaleString()}, Net Income $${statement.netIncome.toLocaleString()}`);
542
- * });
543
- *
544
- * // Get quarterly income statements for Microsoft
545
- * const quarterlyIncome = await fmp.financial.getIncomeStatement({ symbol: 'MSFT', period: 'quarter', limit: 8 });
546
- * ```
547
- *
548
- * @see {@link https://site.financialmodelingprep.com/developer/docs#income-statements-financial-statements|FMP Income Statement Documentation}
549
- */
550
- async getIncomeStatement(params) {
551
- const { symbol, period = "annual", limit = 5 } = params;
552
- return this.client.get(`/income-statement/${symbol}?period=${period}&limit=${limit}`, "v3");
553
- }
554
- /**
555
- * Get balance sheet data
556
- *
557
- * Provides comprehensive balance sheet data including assets, liabilities,
558
- * and shareholder equity. Essential for analyzing company financial position,
559
- * liquidity, and capital structure.
560
- *
561
- * @param params - Balance sheet request parameters
562
- * @param params.symbol - The stock symbol to get balance sheet for (e.g., 'AAPL', 'MSFT', 'GOOGL')
563
- * @param params.period - The reporting period: 'annual' or 'quarter' (default: 'annual')
564
- * @param params.limit - Number of periods to retrieve (default: 5)
565
- *
566
- * @returns Promise resolving to array of balance sheet data with financial position metrics
567
- *
568
- * @example
569
- * ```typescript
570
- * // Get annual balance sheets for Apple
571
- * const balanceSheets = await fmp.financial.getBalanceSheet({ symbol: 'AAPL' });
572
- * balanceSheets.data.forEach(sheet => {
573
- * console.log(`${sheet.date}: Assets $${sheet.totalAssets.toLocaleString()}, Equity $${sheet.totalStockholdersEquity.toLocaleString()}`);
574
- * });
575
- *
576
- * // Get quarterly balance sheets for Microsoft
577
- * const quarterlyBalance = await fmp.financial.getBalanceSheet({ symbol: 'MSFT', period: 'quarter', limit: 8 });
578
- * ```
579
- *
580
- * @see {@link https://site.financialmodelingprep.com/developer/docs#balance-sheet-statements-financial-statements|FMP Balance Sheet Documentation}
581
- */
582
- async getBalanceSheet(params) {
583
- const { symbol, period = "annual", limit = 5 } = params;
584
- return this.client.get(
585
- `/balance-sheet-statement/${symbol}?period=${period}&limit=${limit}`,
586
- "v3"
587
- );
588
- }
589
- /**
590
- * Get cash flow statement data
591
- *
592
- * Provides comprehensive cash flow data including operating, investing,
593
- * and financing cash flows. Essential for analyzing company cash generation,
594
- * capital allocation, and financial sustainability.
595
- *
596
- * @param params - Cash flow statement request parameters
597
- * @param params.symbol - The stock symbol to get cash flow statement for (e.g., 'AAPL', 'MSFT', 'GOOGL')
598
- * @param params.period - The reporting period: 'annual' or 'quarter' (default: 'annual')
599
- * @param params.limit - Number of periods to retrieve (default: 5)
600
- *
601
- * @returns Promise resolving to array of cash flow statement data with cash flow metrics
602
- *
603
- * @example
604
- * ```typescript
605
- * // Get annual cash flow statements for Apple
606
- * const cashFlows = await fmp.financial.getCashFlowStatement({ symbol: 'AAPL' });
607
- * cashFlows.data.forEach(flow => {
608
- * console.log(`${flow.date}: Operating CF $${flow.operatingCashFlow.toLocaleString()}, Free CF $${flow.freeCashFlow.toLocaleString()}`);
609
- * });
610
- *
611
- * // Get quarterly cash flow statements for Microsoft
612
- * const quarterlyCashFlow = await fmp.financial.getCashFlowStatement({ symbol: 'MSFT', period: 'quarter', limit: 8 });
613
- * ```
614
- *
615
- * @see {@link https://site.financialmodelingprep.com/developer/docs#cashflow-statements-financial-statements|FMP Cash Flow Statement Documentation}
616
- */
617
- async getCashFlowStatement(params) {
618
- const { symbol, period = "annual", limit = 5 } = params;
619
- return this.client.get(`/cash-flow-statement/${symbol}?period=${period}&limit=${limit}`, "v3");
620
- }
621
- /**
622
- * Get key financial metrics
623
- *
624
- * Provides essential financial metrics including revenue, net income,
625
- * P/E ratio, and other key performance indicators. Essential for
626
- * fundamental analysis and company valuation.
627
- *
628
- * @param params - Key metrics request parameters
629
- * @param params.symbol - The stock symbol to get key metrics for (e.g., 'AAPL', 'MSFT', 'GOOGL')
630
- * @param params.period - The reporting period: 'annual' or 'quarter' (default: 'annual')
631
- * @param params.limit - Number of periods to retrieve (default: 5)
632
- *
633
- * @returns Promise resolving to array of key metrics data with financial indicators
634
- *
635
- * @example
636
- * ```typescript
637
- * // Get key metrics for Apple
638
- * const keyMetrics = await fmp.financial.getKeyMetrics({ symbol: 'AAPL' });
639
- * keyMetrics.data.forEach(metric => {
640
- * console.log(`${metric.date}: P/E ${metric.peRatio}, ROE ${metric.roe}%`);
641
- * });
642
- *
643
- * // Get quarterly key metrics for Microsoft
644
- * const quarterlyMetrics = await fmp.financial.getKeyMetrics({ symbol: 'MSFT', period: 'quarter', limit: 8 });
645
- * ```
646
- *
647
- * @see {@link https://site.financialmodelingprep.com/developer/docs#key-metrics-statement-analysis|FMP Key Metrics Documentation}
648
- */
649
- async getKeyMetrics(params) {
650
- const { symbol, period = "annual", limit = 5 } = params;
651
- return this.client.get(`/key-metrics/${symbol}?period=${period}&limit=${limit}`, "v3");
652
- }
653
- /**
654
- * Get financial ratios
655
- *
656
- * Provides comprehensive financial ratios including P/B ratio, ROE,
657
- * debt-to-equity, and other important ratios. Essential for analyzing
658
- * company financial health and comparing with peers.
659
- *
660
- * @param params - Financial ratios request parameters
661
- * @param params.symbol - The stock symbol to get financial ratios for (e.g., 'AAPL', 'MSFT', 'GOOGL')
662
- * @param params.period - The reporting period: 'annual' or 'quarter' (default: 'annual')
663
- * @param params.limit - Number of periods to retrieve (default: 5)
664
- *
665
- * @returns Promise resolving to array of financial ratios data with ratio metrics
666
- *
667
- * @example
668
- * ```typescript
669
- * // Get financial ratios for Apple
670
- * const ratios = await fmp.financial.getFinancialRatios({ symbol: 'AAPL' });
671
- * ratios.data.forEach(ratio => {
672
- * console.log(`${ratio.date}: P/B ${ratio.priceToBookRatio}, Debt/Equity ${ratio.debtToEquity}`);
673
- * });
674
- *
675
- * // Get quarterly ratios for Microsoft
676
- * const quarterlyRatios = await fmp.financial.getFinancialRatios({ symbol: 'MSFT', period: 'quarter', limit: 8 });
677
- * ```
678
- *
679
- * @see {@link https://site.financialmodelingprep.com/developer/docs#ratios-statement-analysis|FMP Financial Ratios Documentation}
680
- */
681
- async getFinancialRatios(params) {
682
- const { symbol, period = "annual", limit = 5 } = params;
683
- return this.client.get(`/ratios/${symbol}?period=${period}&limit=${limit}`, "v3");
684
- }
685
- /**
686
- * Get enterprise value data
687
- *
688
- * Provides enterprise value metrics including total enterprise value,
689
- * market cap, and debt information. Essential for company valuation
690
- * and comparing companies with different capital structures.
691
- *
692
- * @param params - Enterprise value request parameters
693
- * @param params.symbol - The stock symbol to get enterprise value for (e.g., 'AAPL', 'MSFT', 'GOOGL')
694
- * @param params.period - The reporting period: 'annual' or 'quarter' (default: 'annual')
695
- * @param params.limit - Number of periods to retrieve (default: 5)
696
- *
697
- * @returns Promise resolving to array of enterprise value data with valuation metrics
698
- *
699
- * @example
700
- * ```typescript
701
- * // Get enterprise value for Apple
702
- * const enterpriseValue = await fmp.financial.getEnterpriseValue({ symbol: 'AAPL' });
703
- * enterpriseValue.data.forEach(ev => {
704
- * console.log(`${ev.date}: EV $${ev.enterpriseValue.toLocaleString()}, Market Cap $${ev.marketCapitalization.toLocaleString()}`);
705
- * });
706
- *
707
- * // Get quarterly enterprise value for Microsoft
708
- * const quarterlyEV = await fmp.financial.getEnterpriseValue({ symbol: 'MSFT', period: 'quarter', limit: 8 });
709
- * ```
710
- *
711
- * @see {@link https://site.financialmodelingprep.com/developer/docs#enterprise-values-statement-analysis|FMP Enterprise Value Documentation}
712
- */
713
- async getEnterpriseValue(params) {
714
- const { symbol, period = "annual", limit = 5 } = params;
715
- return this.client.get(`/enterprise-value/${symbol}?period=${period}&limit=${limit}`, "v3");
716
- }
717
- /**
718
- * Get cash flow growth data
719
- *
720
- * Provides cash flow growth rates showing how quickly a company's
721
- * cash flows are growing over time. Essential for analyzing cash
722
- * generation trends and financial sustainability.
723
- *
724
- * @param params - Cash flow growth request parameters
725
- * @param params.symbol - The stock symbol to get cash flow growth for (e.g., 'AAPL', 'MSFT', 'GOOGL')
726
- * @param params.period - The reporting period: 'annual' or 'quarter' (default: 'annual')
727
- * @param params.limit - Number of periods to retrieve (default: 5)
728
- *
729
- * @returns Promise resolving to array of cash flow growth data with growth metrics
730
- *
731
- * @example
732
- * ```typescript
733
- * // Get cash flow growth for Apple
734
- * const cashFlowGrowth = await fmp.financial.getCashflowGrowth({ symbol: 'AAPL' });
735
- * cashFlowGrowth.data.forEach(growth => {
736
- * console.log(`${growth.date}: Operating CF Growth ${growth.operatingCashFlowGrowth}%`);
737
- * });
738
- *
739
- * // Get quarterly cash flow growth for Microsoft
740
- * const quarterlyGrowth = await fmp.financial.getCashflowGrowth({ symbol: 'MSFT', period: 'quarter', limit: 8 });
741
- * ```
742
- *
743
- * @see {@link https://site.financialmodelingprep.com/developer/docs#cashflow-growth-statement-analysis|FMP Cash Flow Growth Documentation}
744
- */
745
- async getCashflowGrowth(params) {
746
- const { symbol, period = "annual", limit = 5 } = params;
747
- return this.client.get(
748
- `/cash-flow-statement-growth/${symbol}?period=${period}&limit=${limit}`,
749
- "v3"
750
- );
751
- }
752
- /**
753
- * Get income growth data
754
- *
755
- * Provides income growth rates showing how quickly a company's
756
- * revenue and net income are growing over time. Essential for
757
- * analyzing profitability trends and business momentum.
758
- *
759
- * @param params - Income growth request parameters
760
- * @param params.symbol - The stock symbol to get income growth for (e.g., 'AAPL', 'MSFT', 'GOOGL')
761
- * @param params.period - The reporting period: 'annual' or 'quarter' (default: 'annual')
762
- * @param params.limit - Number of periods to retrieve (default: 5)
763
- *
764
- * @returns Promise resolving to array of income growth data with growth metrics
765
- *
766
- * @example
767
- * ```typescript
768
- * // Get income growth for Apple
769
- * const incomeGrowth = await fmp.financial.getIncomeGrowth({ symbol: 'AAPL' });
770
- * incomeGrowth.data.forEach(growth => {
771
- * console.log(`${growth.date}: Revenue Growth ${growth.revenueGrowth}%, Net Income Growth ${growth.netIncomeGrowth}%`);
772
- * });
773
- *
774
- * // Get quarterly income growth for Microsoft
775
- * const quarterlyGrowth = await fmp.financial.getIncomeGrowth({ symbol: 'MSFT', period: 'quarter', limit: 8 });
776
- * ```
777
- *
778
- * @see {@link https://site.financialmodelingprep.com/developer/docs#income-growth-statement-analysis|FMP Income Growth Documentation}
779
- */
780
- async getIncomeGrowth(params) {
781
- const { symbol, period = "annual", limit = 5 } = params;
782
- return this.client.get(
783
- `/income-statement-growth/${symbol}?period=${period}&limit=${limit}`,
784
- "v3"
785
- );
786
- }
787
- /**
788
- * Get balance sheet growth data
789
- *
790
- * Provides balance sheet growth rates showing how quickly a company's
791
- * assets, liabilities, and equity are growing over time. Essential for
792
- * analyzing capital structure trends and financial position changes.
793
- *
794
- * @param params - Balance sheet growth request parameters
795
- * @param params.symbol - The stock symbol to get balance sheet growth for (e.g., 'AAPL', 'MSFT', 'GOOGL')
796
- * @param params.period - The reporting period: 'annual' or 'quarter' (default: 'annual')
797
- * @param params.limit - Number of periods to retrieve (default: 5)
798
- *
799
- * @returns Promise resolving to array of balance sheet growth data with growth metrics
800
- *
801
- * @example
802
- * ```typescript
803
- * // Get balance sheet growth for Apple
804
- * const balanceSheetGrowth = await fmp.financial.getBalanceSheetGrowth({ symbol: 'AAPL' });
805
- * balanceSheetGrowth.data.forEach(growth => {
806
- * console.log(`${growth.date}: Assets Growth ${growth.totalAssetsGrowth}%, Equity Growth ${growth.totalStockholdersEquityGrowth}%`);
807
- * });
808
- *
809
- * // Get quarterly balance sheet growth for Microsoft
810
- * const quarterlyGrowth = await fmp.financial.getBalanceSheetGrowth({ symbol: 'MSFT', period: 'quarter', limit: 8 });
811
- * ```
812
- *
813
- * @see {@link https://site.financialmodelingprep.com/developer/docs#balance-sheet-growth-statement-analysis|FMP Balance Sheet Growth Documentation}
814
- */
815
- async getBalanceSheetGrowth(params) {
816
- const { symbol, period = "annual", limit = 5 } = params;
817
- return this.client.get(
818
- `/balance-sheet-statement-growth/${symbol}?period=${period}&limit=${limit}`,
819
- "v3"
820
- );
821
- }
822
- /**
823
- * Get financial growth data
824
- *
825
- * Provides comprehensive financial growth rates across all key
826
- * financial metrics. Essential for analyzing overall financial
827
- * performance trends and business momentum.
828
- *
829
- * @param params - Financial growth request parameters
830
- * @param params.symbol - The stock symbol to get financial growth for (e.g., 'AAPL', 'MSFT', 'GOOGL')
831
- * @param params.period - The reporting period: 'annual' or 'quarter' (default: 'annual')
832
- * @param params.limit - Number of periods to retrieve (default: 5)
833
- *
834
- * @returns Promise resolving to array of financial growth data with comprehensive growth metrics
835
- *
836
- * @example
837
- * ```typescript
838
- * // Get financial growth for Apple
839
- * const financialGrowth = await fmp.financial.getFinancialGrowth({ symbol: 'AAPL' });
840
- * financialGrowth.data.forEach(growth => {
841
- * console.log(`${growth.date}: Revenue Growth ${growth.revenueGrowth}%, EPS Growth ${growth.epsGrowth}%`);
842
- * });
843
- *
844
- * // Get quarterly financial growth for Microsoft
845
- * const quarterlyGrowth = await fmp.financial.getFinancialGrowth({ symbol: 'MSFT', period: 'quarter', limit: 8 });
846
- * ```
847
- *
848
- * @see {@link https://site.financialmodelingprep.com/developer/docs#financial-growth-statement-analysis|FMP Financial Growth Documentation}
849
- */
850
- async getFinancialGrowth(params) {
851
- const { symbol, period = "annual", limit = 5 } = params;
852
- return this.client.get(`/financial-growth/${symbol}?period=${period}&limit=${limit}`, "v3");
853
- }
854
- /**
855
- * Get historical earnings data
856
- *
857
- * Provides historical and upcoming earnings announcements including
858
- * dates, estimated EPS, and actual EPS. Essential for analyzing
859
- * earnings trends and tracking company performance.
860
- *
861
- * @param params - Earnings historical request parameters
862
- * @param params.symbol - The stock symbol to get earnings history for (e.g., 'AAPL', 'MSFT', 'GOOGL')
863
- * @param params.limit - Number of periods to retrieve (default: 5)
864
- *
865
- * @returns Promise resolving to array of historical earnings data with announcement details
866
- *
867
- * @example
868
- * ```typescript
869
- * // Get earnings history for Apple
870
- * const earningsHistory = await fmp.financial.getEarningsHistorical({ symbol: 'AAPL', limit: 10 });
871
- * earningsHistory.data.forEach(earning => {
872
- * console.log(`${earning.date}: Est. ${earning.estimatedEps}, Actual ${earning.actualEps}`);
873
- * });
874
- *
875
- * // Get earnings history for Microsoft
876
- * const msftEarnings = await fmp.financial.getEarningsHistorical({ symbol: 'MSFT', limit: 8 });
877
- * ```
878
- *
879
- * @see {@link https://site.financialmodelingprep.com/developer/docs#earnings-historical-earnings|FMP Earnings Historical Documentation}
880
- */
881
- async getEarningsHistorical(params) {
882
- const { symbol, limit = 5 } = params;
883
- return this.client.get(`/historical/earning_calendar/${symbol}?limit=${limit}`, "v3");
884
- }
885
- /**
886
- * Get earnings surprises data
887
- *
888
- * Provides earnings announcements that exceeded or fell short of
889
- * analyst estimates. Essential for analyzing earnings quality and
890
- * market reactions to earnings releases.
891
- *
892
- * @param symbol - The stock symbol to get earnings surprises for (e.g., 'AAPL', 'MSFT', 'GOOGL')
893
- *
894
- * @returns Promise resolving to array of earnings surprises data with surprise details
895
- *
896
- * @example
897
- * ```typescript
898
- * // Get earnings surprises for Apple
899
- * const earningsSurprises = await fmp.financial.getEarningsSurprises('AAPL');
900
- * earningsSurprises.data.forEach(surprise => {
901
- * console.log(`${surprise.date}: Est. ${surprise.estimatedEps}, Actual ${surprise.actualEps}, Surprise ${surprise.surprisePercentage}%`);
902
- * });
903
- *
904
- * // Get earnings surprises for Microsoft
905
- * const msftSurprises = await fmp.financial.getEarningsSurprises('MSFT');
906
- * ```
907
- *
908
- * @see {@link https://site.financialmodelingprep.com/developer/docs#earnings-surprises-earnings|FMP Earnings Surprises Documentation}
909
- */
910
- async getEarningsSurprises(symbol) {
911
- return this.client.get(`/earnings-surprises/${symbol}`, "v3");
912
- }
913
- };
914
-
915
- // src/endpoints/etf.ts
916
- var ETFEndpoints = class {
917
- constructor(client) {
918
- this.client = client;
919
- }
920
- /**
921
- * Get available ETF holding dates
922
- *
923
- * Provides a list of dates when ETF holdings are updated and available.
924
- * Useful for determining when the most recent holdings data is available
925
- * and ensuring you're working with current portfolio information.
926
- *
927
- * @param symbol - ETF symbol to get holding dates for (e.g., 'SPY', 'VOO', 'QQQ')
928
- *
929
- * @returns Promise resolving to array of available holding dates
930
- *
931
- * @example
932
- * ```typescript
933
- * // Get holding dates for specific ETF
934
- * const spyDates = await fmp.etf.getHoldingDates('SPY');
935
- * spyDates.data.forEach(date => {
936
- * console.log(`Holdings available: ${date.date}`);
937
- * });
938
- *
939
- * // Get VOO holding dates
940
- * const vooDates = await fmp.etf.getHoldingDates('VOO');
941
- * ```
942
- *
943
- * @see {@link https://site.financialmodelingprep.com/developer/docs#etf-holding-dates-etf-holdings|FMP ETF Holding Dates Documentation}
944
- */
945
- async getHoldingDates(symbol) {
946
- return this.client.get("/etf-holdings/portfolio-date", "v4", { symbol });
947
- }
948
- /**
949
- * Get ETF holdings for specific date
950
- *
951
- * Provides detailed holdings information for an ETF on a specific date.
952
- * Includes individual stocks, their weights, shares held, and market values.
953
- * Essential for understanding ETF composition and portfolio analysis.
954
- *
955
- * @param params - ETF holdings request parameters
956
- * @param params.symbol - The ETF symbol to get holdings for (e.g., 'SPY', 'VOO', 'QQQ')
957
- * @param params.date - The date to get holdings for in YYYY-MM-DD format
958
- *
959
- * @returns Promise resolving to array of ETF holdings with detailed stock information
960
- *
961
- * @example
962
- * ```typescript
963
- * // Get SPY holdings for specific date
964
- * const holdings = await fmp.etf.getHoldings({ symbol: 'SPY', date: '2024-01-15' });
965
- * holdings.data.forEach(holding => {
966
- * console.log(`${holding.asset}: ${holding.weight}% (${holding.sharesNumber} shares)`);
967
- * });
968
- *
969
- * // Get VOO holdings
970
- * const vooHoldings = await fmp.etf.getHoldings({ symbol: 'VOO', date: '2024-01-15' });
971
- * ```
972
- *
973
- * @see {@link https://site.financialmodelingprep.com/developer/docs#etf-holdings-etf-holdings|FMP ETF Holdings Documentation}
974
- */
975
- async getHoldings(params) {
976
- const { symbol, date } = params;
977
- const queryParams = {};
978
- if (symbol) queryParams.symbol = symbol;
979
- if (date) queryParams.date = date;
980
- return this.client.get("/etf-holdings", "v4", queryParams);
981
- }
982
- /**
983
- * Get ETF holdings and components
984
- *
985
- * Provides all stocks held by a specific ETF including assets, share numbers,
986
- * and weight percentages. Essential for understanding ETF composition and
987
- * finding which ETFs hold specific stocks.
988
- *
989
- * @param symbol - The ETF symbol to get holdings for (e.g., 'SPY', 'VOO', 'QQQ')
990
- *
991
- * @returns Promise resolving to array of ETF holdings with stock details
992
- *
993
- * @example
994
- * ```typescript
995
- * // Get SPY holdings
996
- * const spyHoldings = await fmp.etf.getHolder('SPY');
997
- * spyHoldings.data.forEach(holding => {
998
- * console.log(`${holding.asset}: ${holding.weight}% (${holding.sharesNumber} shares)`);
999
- * });
1000
- *
1001
- * // Get VOO holdings
1002
- * const vooHoldings = await fmp.etf.getHolder('VOO');
1003
- * ```
1004
- *
1005
- * @see {@link https://site.financialmodelingprep.com/developer/docs#etf-holder-etf-holdings|FMP ETF Holder Documentation}
1006
- */
1007
- async getHolder(symbol) {
1008
- return this.client.get(`/etf-holder/${symbol}`, "v3");
1009
- }
1010
- /**
1011
- * Get ETF profile and information
1012
- *
1013
- * Provides comprehensive information about an ETF including ticker symbol,
1014
- * name, expense ratio, assets under management, and other key metrics.
1015
- * Essential for ETF comparison and due diligence.
1016
- *
1017
- * @param symbol - ETF symbol to get profile for (e.g., 'SPY', 'VOO', 'QQQ')
1018
- *
1019
- * @returns Promise resolving to ETF profile with detailed information
1020
- *
1021
- * @example
1022
- * ```typescript
1023
- * // Get SPY profile
1024
- * const spyProfile = await fmp.etf.getProfile('SPY');
1025
- * console.log(`SPY AUM: $${spyProfile.data.aum.toLocaleString()}`);
1026
- * console.log(`Expense Ratio: ${spyProfile.data.expenseRatio}%`);
1027
- *
1028
- * // Get VOO profile
1029
- * const vooProfile = await fmp.etf.getProfile('VOO');
1030
- * ```
1031
- *
1032
- * @see {@link https://site.financialmodelingprep.com/developer/docs#etf-information-etf-holdings|FMP ETF Information Documentation}
1033
- */
1034
- async getProfile(symbol) {
1035
- return this.client.getSingle("/etf-info", "v4", { symbol });
1036
- }
1037
- /**
1038
- * Get ETF sector weighting and exposure
1039
- *
1040
- * Provides a breakdown of an ETF's sector allocation showing the percentage
1041
- * of assets invested in each sector. Essential for understanding sector
1042
- * exposure and diversification analysis.
1043
- *
1044
- * @param symbol - The ETF symbol to get sector weighting for (e.g., 'SPY', 'VOO', 'QQQ')
1045
- *
1046
- * @returns Promise resolving to array of sector weightings with percentage allocations
1047
- *
1048
- * @example
1049
- * ```typescript
1050
- * // Get SPY sector weightings
1051
- * const sectorWeightings = await fmp.etf.getSectorWeighting('SPY');
1052
- * sectorWeightings.data.forEach(sector => {
1053
- * console.log(`${sector.sector}: ${sector.weight}%`);
1054
- * });
1055
- *
1056
- * // Get QQQ sector exposure (tech-heavy)
1057
- * const qqqSectors = await fmp.etf.getSectorWeighting('QQQ');
1058
- * ```
1059
- *
1060
- * @see {@link https://site.financialmodelingprep.com/developer/docs#etf-sector-weighting-etf-holdings|FMP ETF Sector Weighting Documentation}
1061
- */
1062
- async getSectorWeighting(symbol) {
1063
- return this.client.get(`/etf-sector-weightings/${symbol}`, "v3");
1064
- }
1065
- /**
1066
- * Get ETF country weighting and exposure
1067
- *
1068
- * Provides a breakdown of an ETF's geographic allocation showing the percentage
1069
- * of assets invested in each country. Essential for understanding international
1070
- * exposure and geographic diversification.
1071
- *
1072
- * @param symbol - The ETF symbol to get country weighting for (e.g., 'SPY', 'VOO', 'EFA')
1073
- *
1074
- * @returns Promise resolving to array of country weightings with percentage allocations
1075
- *
1076
- * @example
1077
- * ```typescript
1078
- * // Get SPY country weightings
1079
- * const countryWeightings = await fmp.etf.getCountryWeighting('SPY');
1080
- * countryWeightings.data.forEach(country => {
1081
- * console.log(`${country.country}: ${country.weight}%`);
1082
- * });
1083
- *
1084
- * // Get international ETF exposure
1085
- * const efaCountries = await fmp.etf.getCountryWeighting('EFA');
1086
- * ```
1087
- *
1088
- * @see {@link https://site.financialmodelingprep.com/developer/docs#etf-country-weighting-etf-holdings|FMP ETF Country Weighting Documentation}
1089
- */
1090
- async getCountryWeighting(symbol) {
1091
- return this.client.get(`/etf-country-weightings/${symbol}`, "v3");
1092
- }
1093
- /**
1094
- * Get ETF stock exposure and holdings
1095
- *
1096
- * Provides detailed exposure information for a specific stock across all ETFs
1097
- * that hold it. Includes market value, share numbers, and weight percentages.
1098
- * Useful for finding which ETFs have exposure to specific stocks.
1099
- *
1100
- * @param symbol - The stock symbol to get ETF exposure for (e.g., 'AAPL', 'MSFT', 'GOOGL')
1101
- *
1102
- * @returns Promise resolving to array of ETF exposures with detailed holding information
1103
- *
1104
- * @example
1105
- * ```typescript
1106
- * // Find ETFs that hold Apple
1107
- * const appleExposure = await fmp.etf.getStockExposure('AAPL');
1108
- * appleExposure.data.forEach(etf => {
1109
- * console.log(`${etf.etfSymbol}: ${etf.weight}% (${etf.sharesNumber} shares)`);
1110
- * });
1111
- *
1112
- * // Find ETFs that hold Microsoft
1113
- * const msftExposure = await fmp.etf.getStockExposure('MSFT');
1114
- * ```
1115
- *
1116
- * @see {@link https://site.financialmodelingprep.com/developer/docs#etf-sector-exposure-etf-holdings|FMP ETF Stock Exposure Documentation}
1117
- */
1118
- async getStockExposure(symbol) {
1119
- return this.client.get(`/etf-stock-exposure/${symbol}`, "v3");
1120
- }
1121
- };
1122
-
1123
- // src/endpoints/economic.ts
1124
- var EconomicEndpoints = class {
1125
- constructor(client) {
1126
- this.client = client;
1127
- }
1128
- /**
1129
- * Get treasury rates data
1130
- *
1131
- * Provides historical treasury rates for various maturities including
1132
- * 1-month, 3-month, 6-month, 1-year, 2-year, 3-year, 5-year, 7-year,
1133
- * 10-year, 20-year, and 30-year treasury bonds. Essential for analyzing
1134
- * interest rate trends, yield curves, and fixed income investments.
1135
- *
1136
- * @param params - Treasury rates request parameters
1137
- * @param params.from - Start date in YYYY-MM-DD format (optional, defaults to 1 year ago)
1138
- * @param params.to - End date in YYYY-MM-DD format (optional, defaults to today)
1139
- *
1140
- * @returns Promise resolving to array of treasury rates data with yield information
1141
- *
1142
- * @example
1143
- * ```typescript
1144
- * // Get treasury rates for the last year
1145
- * const treasuryRates = await fmp.economic.getTreasuryRates({
1146
- * from: '2023-01-01',
1147
- * to: '2023-12-31'
1148
- * });
1149
- * treasuryRates.data.forEach(rate => {
1150
- * console.log(`${rate.date}: 10Y ${rate.tenY}%, 2Y ${rate.twoY}%`);
1151
- * });
1152
- *
1153
- * // Get recent treasury rates
1154
- * const recentRates = await fmp.economic.getTreasuryRates({
1155
- * from: '2024-01-01'
1156
- * });
1157
- * ```
1158
- *
1159
- * @see {@link https://site.financialmodelingprep.com/developer/docs#treasury-rates-economics-data|FMP Treasury Rates Documentation}
1160
- */
1161
- async getTreasuryRates(params) {
1162
- const { from, to } = params;
1163
- const queryParams = {};
1164
- if (from) queryParams.from = from;
1165
- if (to) queryParams.to = to;
1166
- return this.client.get("/treasury", "v4", queryParams);
1167
- }
1168
- /**
1169
- * Get economic indicators data
1170
- *
1171
- * Provides real-time and historical economic data for a wide variety of
1172
- * economic indicators including GDP, unemployment, inflation, retail sales,
1173
- * and many others. Essential for macroeconomic analysis and understanding
1174
- * economic trends and cycles.
1175
- *
1176
- * @param params - Economic indicators request parameters
1177
- * @param params.name - The economic indicator to retrieve
1178
- * @param params.from - Start date in YYYY-MM-DD format (optional, defaults to 1 year ago)
1179
- * @param params.to - End date in YYYY-MM-DD format (optional, defaults to today)
1180
- *
1181
- * @returns Promise resolving to array of economic indicator data with historical values
1182
- *
1183
- * @example
1184
- * ```typescript
1185
- * // Get GDP data for the last year
1186
- * const gdpData = await fmp.economic.getEconomicIndicators({
1187
- * name: 'GDP',
1188
- * from: '2023-01-01',
1189
- * to: '2023-12-31'
1190
- * });
1191
- * gdpData.data.forEach(gdp => {
1192
- * console.log(`${gdp.date}: GDP $${gdp.value.toLocaleString()} billion`);
1193
- * });
1194
- *
1195
- * // Get unemployment rate data
1196
- * const unemploymentData = await fmp.economic.getEconomicIndicators({
1197
- * name: 'unemploymentRate',
1198
- * from: '2024-01-01'
1199
- * });
1200
- *
1201
- * // Get inflation rate data
1202
- * const inflationData = await fmp.economic.getEconomicIndicators({
1203
- * name: 'inflationRate',
1204
- * from: '2023-01-01',
1205
- * to: '2023-12-31'
1206
- * });
1207
- * ```
1208
- *
1209
- * @see {@link https://site.financialmodelingprep.com/developer/docs#economic-indicators-economics-data|FMP Economic Indicators Documentation}
1210
- */
1211
- async getEconomicIndicators(params) {
1212
- const { name, from, to } = params;
1213
- const queryParams = { name };
1214
- if (from) queryParams.from = from;
1215
- if (to) queryParams.to = to;
1216
- return this.client.get(`/economic`, "v4", queryParams);
1217
- }
1218
- };
1219
-
1220
- // src/endpoints/market.ts
1221
- var MarketEndpoints = class {
1222
- constructor(client) {
1223
- this.client = client;
1224
- }
1225
- /**
1226
- * Get current market hours and trading status
1227
- *
1228
- * Provides real-time information about market trading hours, including
1229
- * whether markets are currently open or closed, trading session times,
1230
- * and upcoming market holidays. Essential for determining trading
1231
- * availability and market status.
1232
- *
1233
- * @returns Promise resolving to market hours data with trading status and session information
1234
- *
1235
- * @example
1236
- * ```typescript
1237
- * // Get current market status
1238
- * const marketHours = await fmp.market.getMarketHours();
1239
- * console.log(`Market is ${marketHours.data.isTheStockMarketOpen ? 'OPEN' : 'CLOSED'}`);
1240
- * console.log(`Current time: ${marketHours.data.currentTime}`);
1241
- * console.log(`Next trading day: ${marketHours.data.nextTradingDay}`);
1242
- *
1243
- * // Check if it's a trading day
1244
- * if (marketHours.data.isTheStockMarketOpen) {
1245
- * console.log('Markets are currently open for trading');
1246
- * } else {
1247
- * console.log('Markets are closed');
1248
- * }
1249
- * ```
1250
- *
1251
- * @see {@link https://site.financialmodelingprep.com/developer/docs#market-hours|FMP Market Hours Documentation}
1252
- */
1253
- async getMarketHours() {
1254
- return this.client.get("/market-hours", "v3");
1255
- }
1256
- /**
1257
- * Get overall market performance data
1258
- *
1259
- * Provides comprehensive market performance data including major indices,
1260
- * market breadth, and key performance metrics. Essential for understanding
1261
- * overall market sentiment, trends, and daily market activity.
1262
- *
1263
- * @returns Promise resolving to array of market performance data with indices and metrics
1264
- *
1265
- * @example
1266
- * ```typescript
1267
- * // Get overall market performance
1268
- * const marketPerformance = await fmp.market.getMarketPerformance();
1269
- * marketPerformance.data.forEach(market => {
1270
- * console.log(`${market.index}: ${market.change} (${market.changesPercentage}%)`);
1271
- * console.log(` Open: $${market.open}, High: $${market.dayHigh}, Low: $${market.dayLow}`);
1272
- * });
1273
- *
1274
- * // Find specific indices
1275
- * const sp500 = marketPerformance.data.find(market => market.index === 'S&P 500');
1276
- * console.log(`S&P 500 performance: ${sp500?.changesPercentage}%`);
1277
- *
1278
- * // Check market sentiment
1279
- * const gainers = marketPerformance.data.filter(market => market.changesPercentage > 0);
1280
- * const losers = marketPerformance.data.filter(market => market.changesPercentage < 0);
1281
- * console.log(`Gaining indices: ${gainers.length}, Losing indices: ${losers.length}`);
1282
- * ```
1283
- *
1284
- * @see {@link https://site.financialmodelingprep.com/developer/docs#market-performance|FMP Market Performance Documentation}
1285
- */
1286
- async getMarketPerformance() {
1287
- return this.client.get("/market-performance", "v3");
1288
- }
1289
- /**
1290
- * Get top gaining stocks for the current trading day
1291
- *
1292
- * Provides a list of stocks that have gained the most value during the
1293
- * current trading session. Essential for identifying momentum stocks,
1294
- * tracking market movers, and discovering potential investment opportunities.
1295
- * Useful for day trading, momentum strategies, and market analysis.
1296
- *
1297
- * @returns Promise resolving to array of top gaining stocks with price and percentage change data
1298
- *
1299
- * @example
1300
- * ```typescript
1301
- * // Get top gainers for the day
1302
- * const gainers = await fmp.market.getGainers();
1303
- * console.log(`Top ${gainers.data.length} gaining stocks today:`);
1304
- *
1305
- * gainers.data.forEach((stock, index) => {
1306
- * console.log(`${index + 1}. ${stock.symbol} (${stock.name})`);
1307
- * console.log(` Price: $${stock.price} | Change: +${stock.change} (${stock.changesPercentage}%)`);
1308
- * console.log(` Volume: ${stock.volume.toLocaleString()}`);
1309
- * });
1310
- *
1311
- * // Find stocks with >10% gains
1312
- * const bigGainers = gainers.data.filter(stock => stock.changesPercentage > 10);
1313
- * console.log(`Stocks with >10% gains: ${bigGainers.length}`);
1314
- *
1315
- * // Check volume leaders among gainers
1316
- * const highVolumeGainers = gainers.data.filter(stock => stock.volume > 1000000);
1317
- * console.log(`High volume gainers (>1M shares): ${highVolumeGainers.length}`);
1318
- * ```
1319
- *
1320
- * @see {@link https://site.financialmodelingprep.com/developer/docs#market-biggest-gainers-market-overview|FMP Market Biggest Gainers Documentation}
1321
- */
1322
- async getGainers() {
1323
- return this.client.get("/stock_market/gainers", "v3");
1324
- }
1325
- /**
1326
- * Get top losing stocks for the current trading day
1327
- *
1328
- * Provides a list of stocks that have lost the most value during the
1329
- * current trading session. Essential for identifying underperforming stocks,
1330
- * tracking market decliners, and discovering potential contrarian opportunities.
1331
- * Useful for risk management, short selling strategies, and market analysis.
1332
- *
1333
- * @returns Promise resolving to array of top losing stocks with price and percentage change data
1334
- *
1335
- * @example
1336
- * ```typescript
1337
- * // Get top losers for the day
1338
- * const losers = await fmp.market.getLosers();
1339
- * console.log(`Top ${losers.data.length} losing stocks today:`);
1340
- *
1341
- * losers.data.forEach((stock, index) => {
1342
- * console.log(`${index + 1}. ${stock.symbol} (${stock.name})`);
1343
- * console.log(` Price: $${stock.price} | Change: ${stock.change} (${stock.changesPercentage}%)`);
1344
- * console.log(` Volume: ${stock.volume.toLocaleString()}`);
1345
- * });
1346
- *
1347
- * // Find stocks with >10% losses
1348
- * const bigLosers = losers.data.filter(stock => stock.changesPercentage < -10);
1349
- * console.log(`Stocks with >10% losses: ${bigLosers.length}`);
1350
- *
1351
- * // Check for potential oversold conditions
1352
- * const highVolumeLosers = losers.data.filter(stock => stock.volume > 1000000);
1353
- * console.log(`High volume losers (>1M shares): ${highVolumeLosers.length}`);
1354
- *
1355
- * // Look for potential bounce candidates
1356
- * const oversoldStocks = losers.data.filter(stock =>
1357
- * stock.changesPercentage < -5 && stock.volume > 500000
1358
- * );
1359
- * ```
1360
- *
1361
- * @see {@link https://site.financialmodelingprep.com/developer/docs#market-biggest-losers-market-overview|FMP Market Biggest Losers Documentation}
1362
- */
1363
- async getLosers() {
1364
- return this.client.get("/stock_market/losers", "v3");
1365
- }
1366
- /**
1367
- * Get most actively traded stocks for the current trading day
1368
- *
1369
- * Provides a list of stocks with the highest trading volume during the
1370
- * current trading session. Essential for identifying stocks with high
1371
- * liquidity, tracking market interest, and discovering stocks with
1372
- * significant trading activity. Useful for day trading and liquidity analysis.
1373
- *
1374
- * @returns Promise resolving to array of most active stocks with volume and price data
1375
- *
1376
- * @example
1377
- * ```typescript
1378
- * // Get most active stocks for the day
1379
- * const mostActive = await fmp.market.getMostActive();
1380
- * console.log(`Top ${mostActive.data.length} most active stocks today:`);
1381
- *
1382
- * mostActive.data.forEach((stock, index) => {
1383
- * console.log(`${index + 1}. ${stock.symbol} (${stock.name})`);
1384
- * console.log(` Volume: ${stock.volume.toLocaleString()} shares`);
1385
- * console.log(` Price: $${stock.price} | Change: ${stock.change} (${stock.changesPercentage}%)`);
1386
- * console.log(` Avg Volume: ${stock.avgVolume?.toLocaleString() || 'N/A'}`);
1387
- * });
1388
- *
1389
- * // Find stocks with unusual volume (>2x average)
1390
- * const unusualVolume = mostActive.data.filter(stock =>
1391
- * stock.avgVolume && stock.volume > stock.avgVolume * 2
1392
- * );
1393
- * console.log(`Stocks with unusual volume: ${unusualVolume.length}`);
1394
- *
1395
- * // Check for high volume gainers
1396
- * const highVolumeGainers = mostActive.data.filter(stock =>
1397
- * stock.changesPercentage > 0 && stock.volume > 1000000
1398
- * );
1399
- * console.log(`High volume gainers: ${highVolumeGainers.length}`);
1400
- *
1401
- * // Find penny stocks with high volume
1402
- * const pennyStocks = mostActive.data.filter(stock =>
1403
- * stock.price < 5 && stock.volume > 500000
1404
- * );
1405
- * ```
1406
- *
1407
- * @see {@link https://site.financialmodelingprep.com/developer/docs#market-most-actives|FMP Market Most Actives Documentation}
1408
- */
1409
- async getMostActive() {
1410
- return this.client.get("/stock_market/actives", "v3");
1411
- }
1412
- /**
1413
- * Get sector performance data for the current trading day
1414
- *
1415
- * Provides performance data for all major market sectors including
1416
- * technology, healthcare, financials, energy, and others. Essential for
1417
- * sector rotation analysis, identifying leading/lagging sectors, and
1418
- * understanding market breadth and sector-specific trends.
1419
- *
1420
- * @returns Promise resolving to array of sector performance data with percentage changes
1421
- *
1422
- * @example
1423
- * ```typescript
1424
- * // Get sector performance for the day
1425
- * const sectorPerformance = await fmp.market.getSectorPerformance();
1426
- * console.log(`Sector performance for ${sectorPerformance.data.length} sectors:`);
1427
- *
1428
- * sectorPerformance.data.forEach(sector => {
1429
- * const changeColor = sector.changesPercentage >= 0 ? 'green' : 'red';
1430
- * console.log(`${sector.sector}: ${sector.changesPercentage}%`);
1431
- * console.log(` Change: ${sector.changesPercentage >= 0 ? '+' : ''}${sector.changesPercentage}%`);
1432
- * });
1433
- *
1434
- * // Find best performing sectors
1435
- * const topSectors = sectorPerformance.data
1436
- * .sort((a, b) => b.changesPercentage - a.changesPercentage)
1437
- * .slice(0, 3);
1438
- * console.log('Top 3 performing sectors:');
1439
- * topSectors.forEach((sector, index) => {
1440
- * console.log(`${index + 1}. ${sector.sector}: ${sector.changesPercentage}%`);
1441
- * });
1442
- *
1443
- * // Find worst performing sectors
1444
- * const bottomSectors = sectorPerformance.data
1445
- * .sort((a, b) => a.changesPercentage - b.changesPercentage)
1446
- * .slice(0, 3);
1447
- * console.log('Bottom 3 performing sectors:');
1448
- * bottomSectors.forEach((sector, index) => {
1449
- * console.log(`${index + 1}. ${sector.sector}: ${sector.changesPercentage}%`);
1450
- * });
1451
- *
1452
- * // Check for sector rotation
1453
- * const gainingSectors = sectorPerformance.data.filter(sector => sector.changesPercentage > 0);
1454
- * const losingSectors = sectorPerformance.data.filter(sector => sector.changesPercentage < 0);
1455
- * console.log(`Sectors gaining: ${gainingSectors.length}, Sectors losing: ${losingSectors.length}`);
1456
- * ```
1457
- *
1458
- * @see {@link https://site.financialmodelingprep.com/developer/docs#sector-performance-market-overview|FMP Sector Performance Documentation}
1459
- */
1460
- async getSectorPerformance() {
1461
- return this.client.get("/sector-performance", "v3");
1462
- }
1463
- /**
1464
- * Get real-time data for major market indices
1465
- *
1466
- * Provides real-time quote data for all major stock market indices including
1467
- * S&P 500, Dow Jones Industrial Average, NASDAQ Composite, and other global
1468
- * indices. Essential for tracking overall market performance, understanding
1469
- * market sentiment, and identifying broad market trends.
1470
- *
1471
- * @returns Promise resolving to array of market index data with real-time quotes
1472
- *
1473
- * @example
1474
- * ```typescript
1475
- * // Get real-time market indices
1476
- * const marketIndices = await fmp.market.getMarketIndex();
1477
- * console.log(`Real-time data for ${marketIndices.data.length} major indices:`);
1478
- *
1479
- * marketIndices.data.forEach(index => {
1480
- * console.log(`${index.symbol} (${index.name}):`);
1481
- * console.log(` Price: $${index.price}`);
1482
- * console.log(` Change: ${index.change} (${index.changesPercentage}%)`);
1483
- * console.log(` Day Range: $${index.dayLow} - $${index.dayHigh}`);
1484
- * console.log(` Volume: ${index.volume?.toLocaleString() || 'N/A'}`);
1485
- * });
1486
- *
1487
- * // Find specific major indices
1488
- * const sp500 = marketIndices.data.find(index => index.symbol === '^GSPC');
1489
- * const nasdaq = marketIndices.data.find(index => index.symbol === '^IXIC');
1490
- * const dowJones = marketIndices.data.find(index => index.symbol === '^DJI');
1491
- *
1492
- * console.log(`S&P 500: ${sp500?.price} (${sp500?.changesPercentage}%)`);
1493
- * console.log(`NASDAQ: ${nasdaq?.price} (${nasdaq?.changesPercentage}%)`);
1494
- * console.log(`Dow Jones: ${dowJones?.price} (${dowJones?.changesPercentage}%)`);
1495
- *
1496
- * // Check market breadth
1497
- * const gainingIndices = marketIndices.data.filter(index => index.changesPercentage > 0);
1498
- * const losingIndices = marketIndices.data.filter(index => index.changesPercentage < 0);
1499
- * console.log(`Indices gaining: ${gainingIndices.length}, Indices losing: ${losingIndices.length}`);
1500
- *
1501
- * // Find international indices
1502
- * const internationalIndices = marketIndices.data.filter(index =>
1503
- * !index.symbol.startsWith('^') ||
1504
- * index.name.toLowerCase().includes('europe') ||
1505
- * index.name.toLowerCase().includes('asia')
1506
- * );
1507
- * ```
1508
- *
1509
- * @see {@link https://site.financialmodelingprep.com/developer/docs#market-index-market-overview|FMP Market Index Documentation}
1510
- */
1511
- async getMarketIndex() {
1512
- return this.client.get("/quotes/index", "v3");
1513
- }
1514
- };
1515
-
1516
- // src/endpoints/list.ts
1517
- var ListEndpoints = class {
1518
- constructor(client) {
1519
- this.client = client;
1520
- }
1521
- /**
1522
- * Get comprehensive list of all available stocks
1523
- *
1524
- * Provides a complete list of all stocks available on major exchanges including
1525
- * NYSE, NASDAQ, and other global markets. Essential for discovering available
1526
- * symbols, building watchlists, or creating stock screening applications.
1527
- *
1528
- * @returns Promise resolving to array of stock data with symbol, name, exchange, and price information
1529
- *
1530
- * @example
1531
- * ```typescript
1532
- * // Get all available stocks
1533
- * const stocks = await fmp.list.getStockList();
1534
- * console.log(`Total stocks available: ${stocks.data.length}`);
1535
- *
1536
- * // Find specific stocks
1537
- * const appleStock = stocks.data.find(stock => stock.symbol === 'AAPL');
1538
- * console.log(`Apple: ${appleStock?.name} (${appleStock?.exchange})`);
1539
- *
1540
- * // Filter by exchange
1541
- * const nasdaqStocks = stocks.data.filter(stock => stock.exchange === 'NASDAQ');
1542
- * console.log(`NASDAQ stocks: ${nasdaqStocks.length}`);
1543
- * ```
1544
- *
1545
- * @see {@link https://site.financialmodelingprep.com/developer/docs#symbol-list-stock-list|FMP Stock List Documentation}
1546
- */
1547
- async getStockList() {
1548
- return this.client.get("/stock/list");
1549
- }
1550
- /**
1551
- * Get comprehensive list of all available ETFs
1552
- *
1553
- * Provides a complete list of all Exchange-Traded Funds (ETFs) available for trading.
1554
- * Includes ETFs from various asset classes including equity, bond, commodity, and
1555
- * sector-specific funds. Essential for ETF research and portfolio construction.
1556
- *
1557
- * @returns Promise resolving to array of ETF data with symbol, name, exchange, and asset class information
1558
- *
1559
- * @example
1560
- * ```typescript
1561
- * // Get all available ETFs
1562
- * const etfs = await fmp.list.getETFList();
1563
- * console.log(`Total ETFs available: ${etfs.data.length}`);
1564
- *
1565
- * // Find specific ETFs
1566
- * const spyETF = etfs.data.find(etf => etf.symbol === 'SPY');
1567
- * console.log(`SPY: ${spyETF?.name} (${spyETF?.assetClass})`);
1568
- *
1569
- * // Filter by asset class
1570
- * const equityETFs = etfs.data.filter(etf => etf.assetClass === 'Equity');
1571
- * console.log(`Equity ETFs: ${equityETFs.length}`);
1572
- *
1573
- * // Find sector ETFs
1574
- * const techETFs = etfs.data.filter(etf =>
1575
- * etf.name.toLowerCase().includes('technology') ||
1576
- * etf.name.toLowerCase().includes('tech')
1577
- * );
1578
- * ```
1579
- *
1580
- * @see {@link https://site.financialmodelingprep.com/developer/docs#exchange-traded-fund-search-stock-list|FMP ETF List Documentation}
1581
- */
1582
- async getETFList() {
1583
- return this.client.get("/etf/list");
1584
- }
1585
- /**
1586
- * Get comprehensive list of all available cryptocurrencies
1587
- *
1588
- * Provides a complete list of all cryptocurrencies available for trading.
1589
- * Includes major cryptocurrencies like Bitcoin, Ethereum, and thousands of altcoins
1590
- * with their trading pairs against USD and other major currencies.
1591
- *
1592
- * @returns Promise resolving to array of cryptocurrency data with symbol, name, and exchange information
1593
- *
1594
- * @example
1595
- * ```typescript
1596
- * // Get all available cryptocurrencies
1597
- * const cryptos = await fmp.list.getCryptoList();
1598
- * console.log(`Total cryptocurrencies available: ${cryptos.data.length}`);
1599
- *
1600
- * // Find major cryptocurrencies
1601
- * const bitcoin = cryptos.data.find(crypto => crypto.symbol === 'BTCUSD');
1602
- * console.log(`Bitcoin: ${bitcoin?.name} (${bitcoin?.exchange})`);
1603
- *
1604
- * const ethereum = cryptos.data.find(crypto => crypto.symbol === 'ETHUSD');
1605
- * console.log(`Ethereum: ${ethereum?.name} (${ethereum?.exchange})`);
1606
- *
1607
- * // Filter by exchange
1608
- * const binanceCryptos = cryptos.data.filter(crypto => crypto.exchange === 'Binance');
1609
- * console.log(`Binance cryptocurrencies: ${binanceCryptos.length}`);
1610
- *
1611
- * // Find altcoins
1612
- * const altcoins = cryptos.data.filter(crypto =>
1613
- * !['BTCUSD', 'ETHUSD', 'USDTUSD', 'USDCUSD'].includes(crypto.symbol)
1614
- * );
1615
- * ```
1616
- *
1617
- * @see {@link https://site.financialmodelingprep.com/developer/docs#cryptocurrencies-list-crypto|FMP Cryptocurrency List Documentation}
1618
- */
1619
- async getCryptoList() {
1620
- return this.client.get("/symbol/available-cryptocurrencies");
1621
- }
1622
- /**
1623
- * Get comprehensive list of all available forex currency pairs
1624
- *
1625
- * Provides a complete list of all foreign exchange currency pairs available for trading.
1626
- * Includes major, minor, and exotic currency pairs with their base and quote currencies.
1627
- * Essential for forex trading, currency analysis, and international market research.
1628
- *
1629
- * @returns Promise resolving to array of forex data with currency pair symbols and exchange information
1630
- *
1631
- * @example
1632
- * ```typescript
1633
- * // Get all available forex pairs
1634
- * const forexPairs = await fmp.list.getForexList();
1635
- * console.log(`Total forex pairs available: ${forexPairs.data.length}`);
1636
- *
1637
- * // Find major currency pairs
1638
- * const eurUsd = forexPairs.data.find(pair => pair.symbol === 'EURUSD');
1639
- * console.log(`EUR/USD: ${eurUsd?.name} (${eurUsd?.exchange})`);
1640
- *
1641
- * const gbpUsd = forexPairs.data.find(pair => pair.symbol === 'GBPUSD');
1642
- * console.log(`GBP/USD: ${gbpUsd?.name} (${gbpUsd?.exchange})`);
1643
- *
1644
- * // Filter major pairs (USD as quote currency)
1645
- * const majorPairs = forexPairs.data.filter(pair =>
1646
- * pair.symbol.endsWith('USD') && pair.symbol.length === 6
1647
- * );
1648
- * console.log(`Major pairs: ${majorPairs.length}`);
1649
- *
1650
- * // Find exotic pairs
1651
- * const exoticPairs = forexPairs.data.filter(pair =>
1652
- * pair.symbol.includes('ZAR') || pair.symbol.includes('TRY') || pair.symbol.includes('BRL')
1653
- * );
1654
- * ```
1655
- *
1656
- * @see {@link https://site.financialmodelingprep.com/developer/docs#forex-list-forex|FMP Forex List Documentation}
1657
- */
1658
- async getForexList() {
1659
- return this.client.get("/symbol/available-forex-currency-pairs");
1660
- }
1661
- /**
1662
- * Get comprehensive list of all available market indexes
1663
- *
1664
- * Provides a complete list of all market indexes available for tracking and analysis.
1665
- * Includes major global indexes like S&P 500, NASDAQ, Dow Jones, as well as
1666
- * international indexes, sector indexes, and specialized market benchmarks.
1667
- *
1668
- * @returns Promise resolving to array of index data with symbol, name, and exchange information
1669
- *
1670
- * @example
1671
- * ```typescript
1672
- * // Get all available indexes
1673
- * const indexes = await fmp.list.getAvailableIndexes();
1674
- * console.log(`Total indexes available: ${indexes.data.length}`);
1675
- *
1676
- * // Find major US indexes
1677
- * const sp500 = indexes.data.find(index => index.symbol === '^GSPC');
1678
- * console.log(`S&P 500: ${sp500?.name} (${sp500?.exchange})`);
1679
- *
1680
- * const nasdaq = indexes.data.find(index => index.symbol === '^IXIC');
1681
- * console.log(`NASDAQ: ${nasdaq?.name} (${nasdaq?.exchange})`);
1682
- *
1683
- * const dowJones = indexes.data.find(index => index.symbol === '^DJI');
1684
- * console.log(`Dow Jones: ${dowJones?.name} (${dowJones?.exchange})`);
1685
- *
1686
- * // Filter by exchange
1687
- * const nyseIndexes = indexes.data.filter(index => index.exchange === 'NYSE');
1688
- * console.log(`NYSE indexes: ${nyseIndexes.length}`);
1689
- *
1690
- * // Find sector indexes
1691
- * const techIndexes = indexes.data.filter(index =>
1692
- * index.name.toLowerCase().includes('technology') ||
1693
- * index.name.toLowerCase().includes('tech')
1694
- * );
1695
- * ```
1696
- *
1697
- * @see {@link https://site.financialmodelingprep.com/developer/docs#available-indexes|FMP Available Indexes Documentation}
1698
- */
1699
- async getAvailableIndexes() {
1700
- return this.client.get("/symbol/available-indexes");
1701
- }
1702
- };
1703
-
1704
- // src/endpoints/calendar.ts
1705
- var CalendarEndpoints = class {
1706
- constructor(client) {
1707
- this.client = client;
1708
- }
1709
- /**
1710
- * Get earnings calendar data
1711
- *
1712
- * Provides upcoming earnings announcements for all publicly traded companies
1713
- * within a specified date range. Essential for tracking earnings season,
1714
- * market events, and investment timing decisions.
1715
- *
1716
- * @param params - Earnings calendar request parameters
1717
- * @param params.from - Start date in YYYY-MM-DD format (optional, defaults to today)
1718
- * @param params.to - End date in YYYY-MM-DD format (optional, defaults to 30 days from today)
1719
- *
1720
- * @returns Promise resolving to array of earnings calendar data with announcement details
1721
- *
1722
- * @example
1723
- * ```typescript
1724
- * // Get earnings calendar for next week
1725
- * const earningsCalendar = await fmp.calendar.getEarningsCalendar({
1726
- * from: '2024-01-15',
1727
- * to: '2024-01-22'
1728
- * });
1729
- * earningsCalendar.data.forEach(earning => {
1730
- * console.log(`${earning.date}: ${earning.symbol} - Est. EPS: ${earning.estimatedEps}`);
1731
- * });
1732
- *
1733
- * // Get earnings calendar for current month
1734
- * const monthlyEarnings = await fmp.calendar.getEarningsCalendar({
1735
- * from: '2024-01-01',
1736
- * to: '2024-01-31'
1737
- * });
1738
- * ```
1739
- *
1740
- * @see {@link https://site.financialmodelingprep.com/developer/docs#earnings-calendar-earnings|FMP Earnings Calendar Documentation}
1741
- */
1742
- async getEarningsCalendar(params = {}) {
1743
- const { from, to } = params;
1744
- const queryParams = {};
1745
- if (from) queryParams.from = from;
1746
- if (to) queryParams.to = to;
1747
- return this.client.get("/earning_calendar", "v3", queryParams);
1748
- }
1749
- /**
1750
- * Get confirmed earnings calendar data
1751
- *
1752
- * Provides confirmed earnings announcements with verified dates and times.
1753
- * These are earnings announcements that have been officially confirmed
1754
- * by companies, providing more reliable scheduling information.
1755
- *
1756
- * @param params - Confirmed earnings calendar request parameters
1757
- * @param params.from - Start date in YYYY-MM-DD format (optional, defaults to today)
1758
- * @param params.to - End date in YYYY-MM-DD format (optional, defaults to 30 days from today)
1759
- *
1760
- * @returns Promise resolving to array of confirmed earnings calendar data
1761
- *
1762
- * @example
1763
- * ```typescript
1764
- * // Get confirmed earnings for next week
1765
- * const confirmedEarnings = await fmp.calendar.getEarningsConfirmed({
1766
- * from: '2024-01-15',
1767
- * to: '2024-01-22'
1768
- * });
1769
- * confirmedEarnings.data.forEach(earning => {
1770
- * console.log(`${earning.date}: ${earning.symbol} - Confirmed: ${earning.time}`);
1771
- * });
1772
- *
1773
- * // Get confirmed earnings for current month
1774
- * const monthlyConfirmed = await fmp.calendar.getEarningsConfirmed({
1775
- * from: '2024-01-01',
1776
- * to: '2024-01-31'
1777
- * });
1778
- * ```
1779
- *
1780
- * @see {@link https://site.financialmodelingprep.com/developer/docs#earnings-confirmed-earnings|FMP Earnings Confirmed Documentation}
1781
- */
1782
- async getEarningsConfirmed(params = {}) {
1783
- const { from, to } = params;
1784
- const queryParams = {};
1785
- if (from) queryParams.from = from;
1786
- if (to) queryParams.to = to;
1787
- return this.client.get("/earning-calendar-confirmed", "v4", queryParams);
1788
- }
1789
- /**
1790
- * Get dividends calendar data
1791
- *
1792
- * Provides upcoming dividend payments and ex-dividend dates for all
1793
- * publicly traded companies within a specified date range. Essential
1794
- * for dividend investors and income-focused strategies.
1795
- *
1796
- * @param params - Dividends calendar request parameters
1797
- * @param params.from - Start date in YYYY-MM-DD format (optional, defaults to today)
1798
- * @param params.to - End date in YYYY-MM-DD format (optional, defaults to 30 days from today)
1799
- *
1800
- * @returns Promise resolving to array of dividends calendar data with payment details
1801
- *
1802
- * @example
1803
- * ```typescript
1804
- * // Get dividends calendar for next week
1805
- * const dividendsCalendar = await fmp.calendar.getDividendsCalendar({
1806
- * from: '2024-01-15',
1807
- * to: '2024-01-22'
1808
- * });
1809
- * dividendsCalendar.data.forEach(dividend => {
1810
- * console.log(`${dividend.date}: ${dividend.symbol} - Amount: $${dividend.amount}`);
1811
- * });
1812
- *
1813
- * // Get dividends calendar for current month
1814
- * const monthlyDividends = await fmp.calendar.getDividendsCalendar({
1815
- * from: '2024-01-01',
1816
- * to: '2024-01-31'
1817
- * });
1818
- * ```
1819
- *
1820
- * @see {@link https://site.financialmodelingprep.com/developer/docs#dividends-calendar-dividends|FMP Dividends Calendar Documentation}
1821
- */
1822
- async getDividendsCalendar(params = {}) {
1823
- const { from, to } = params;
1824
- const queryParams = {};
1825
- if (from) queryParams.from = from;
1826
- if (to) queryParams.to = to;
1827
- return this.client.get("/stock_dividend_calendar", "v3", queryParams);
1828
- }
1829
- /**
1830
- * Get economic calendar data
1831
- *
1832
- * Provides upcoming economic events, indicators, and data releases
1833
- * that can impact financial markets. Essential for understanding
1834
- * market-moving events and economic trends.
1835
- *
1836
- * @param params - Economic calendar request parameters
1837
- * @param params.from - Start date in YYYY-MM-DD format (optional, defaults to today)
1838
- * @param params.to - End date in YYYY-MM-DD format (optional, defaults to 30 days from today)
1839
- *
1840
- * @returns Promise resolving to array of economic calendar data with event details
1841
- *
1842
- * @example
1843
- * ```typescript
1844
- * // Get economic calendar for next week
1845
- * const economicCalendar = await fmp.calendar.getEconomicsCalendar({
1846
- * from: '2024-01-15',
1847
- * to: '2024-01-22'
1848
- * });
1849
- * economicCalendar.data.forEach(event => {
1850
- * console.log(`${event.date}: ${event.event} - Country: ${event.country}`);
1851
- * });
1852
- *
1853
- * // Get economic calendar for current month
1854
- * const monthlyEconomic = await fmp.calendar.getEconomicsCalendar({
1855
- * from: '2024-01-01',
1856
- * to: '2024-01-31'
1857
- * });
1858
- * ```
1859
- *
1860
- * @see {@link https://site.financialmodelingprep.com/developer/docs#economics-calendar-economics-data|FMP Economic Calendar Documentation}
1861
- */
1862
- async getEconomicsCalendar(params = {}) {
1863
- const { from, to } = params;
1864
- const queryParams = {};
1865
- if (from) queryParams.from = from;
1866
- if (to) queryParams.to = to;
1867
- return this.client.get("/economic_calendar", "v3", queryParams);
1868
- }
1869
- /**
1870
- * Get IPO calendar data
1871
- *
1872
- * Provides upcoming initial public offerings (IPOs) and their details
1873
- * within a specified date range. Essential for tracking new market
1874
- * entrants and investment opportunities in newly public companies.
1875
- *
1876
- * @param params - IPO calendar request parameters
1877
- * @param params.from - Start date in YYYY-MM-DD format (optional, defaults to today)
1878
- * @param params.to - End date in YYYY-MM-DD format (optional, defaults to 30 days from today)
1879
- *
1880
- * @returns Promise resolving to array of IPO calendar data with offering details
1881
- *
1882
- * @example
1883
- * ```typescript
1884
- * // Get IPO calendar for next week
1885
- * const ipoCalendar = await fmp.calendar.getIPOCalendar({
1886
- * from: '2024-01-15',
1887
- * to: '2024-01-22'
1888
- * });
1889
- * ipoCalendar.data.forEach(ipo => {
1890
- * console.log(`${ipo.date}: ${ipo.symbol} - Price: $${ipo.price}, Shares: ${ipo.shares.toLocaleString()}`);
1891
- * });
1892
- *
1893
- * // Get IPO calendar for current month
1894
- * const monthlyIPOs = await fmp.calendar.getIPOCalendar({
1895
- * from: '2024-01-01',
1896
- * to: '2024-01-31'
1897
- * });
1898
- * ```
1899
- *
1900
- * @see {@link https://site.financialmodelingprep.com/developer/docs#ipo-calender-by-ipo-calendar|FMP IPO Calendar Documentation}
1901
- */
1902
- async getIPOCalendar(params = {}) {
1903
- const { from, to } = params;
1904
- const queryParams = {};
1905
- if (from) queryParams.from = from;
1906
- if (to) queryParams.to = to;
1907
- return this.client.get("/ipo_calendar", "v3", queryParams);
1908
- }
1909
- /**
1910
- * Get stock splits calendar data
1911
- *
1912
- * Provides upcoming stock splits for publicly traded companies within
1913
- * a specified date range. Essential for understanding corporate actions
1914
- * that affect share prices and trading dynamics.
1915
- *
1916
- * @param params - Stock splits calendar request parameters
1917
- * @param params.from - Start date in YYYY-MM-DD format (optional, defaults to today)
1918
- * @param params.to - End date in YYYY-MM-DD format (optional, defaults to 30 days from today)
1919
- *
1920
- * @returns Promise resolving to array of stock splits calendar data with split details
1921
- *
1922
- * @example
1923
- * ```typescript
1924
- * // Get stock splits calendar for next week
1925
- * const splitsCalendar = await fmp.calendar.getSplitsCalendar({
1926
- * from: '2024-01-15',
1927
- * to: '2024-01-22'
1928
- * });
1929
- * splitsCalendar.data.forEach(split => {
1930
- * console.log(`${split.date}: ${split.symbol} - Ratio: ${split.numerator}:${split.denominator}`);
1931
- * });
1932
- *
1933
- * // Get stock splits calendar for current month
1934
- * const monthlySplits = await fmp.calendar.getSplitsCalendar({
1935
- * from: '2024-01-01',
1936
- * to: '2024-01-31'
1937
- * });
1938
- * ```
1939
- *
1940
- * @see {@link https://site.financialmodelingprep.com/developer/docs#splits-calendar-splits|FMP Stock Splits Calendar Documentation}
1941
- */
1942
- async getSplitsCalendar(params = {}) {
1943
- const { from, to } = params;
1944
- const queryParams = {};
1945
- if (from) queryParams.from = from;
1946
- if (to) queryParams.to = to;
1947
- return this.client.get("/stock_split_calendar", "v3", queryParams);
1948
- }
1949
- };
1950
-
1951
- // src/endpoints/company.ts
1952
- var CompanyEndpoints = class {
1953
- constructor(client) {
1954
- this.client = client;
1955
- }
1956
- /**
1957
- * Get comprehensive company profile and information
1958
- *
1959
- * Provides detailed company information including financial metrics, business description,
1960
- * headquarters location, and key performance indicators. Essential for fundamental analysis
1961
- * and understanding a company's business model and market position.
1962
- *
1963
- * @param symbol - The stock symbol to get the profile for (e.g., 'AAPL', 'MSFT', 'GOOGL')
1964
- *
1965
- * @returns Promise resolving to comprehensive company profile with financial and business information
1966
- *
1967
- * @example
1968
- * ```typescript
1969
- * // Get Apple's company profile
1970
- * const profile = await fmp.company.getCompanyProfile('AAPL');
1971
- * console.log(`Company: ${profile.data.companyName}`);
1972
- * console.log(`Industry: ${profile.data.industry}`);
1973
- * console.log(`Market Cap: $${profile.data.mktCap.toLocaleString()}`);
1974
- * console.log(`Description: ${profile.data.description.substring(0, 100)}...`);
1975
- *
1976
- * // Get Microsoft's profile
1977
- * const msftProfile = await fmp.company.getCompanyProfile('MSFT');
1978
- * ```
1979
- *
1980
- * @see {@link https://site.financialmodelingprep.com/developer/docs#company-profile-company-information|FMP Company Profile Documentation}
1981
- */
1982
- async getCompanyProfile(symbol) {
1983
- return this.client.getSingle(`/profile/${symbol}`, "v3");
1984
- }
1985
- /**
1986
- * Get executive compensation and governance information
1987
- *
1988
- * Provides detailed compensation data for company executives including salary, bonuses,
1989
- * stock options, and other benefits. Essential for governance analysis and understanding
1990
- * executive pay structures and alignment with shareholder interests.
1991
- *
1992
- * @param symbol - The stock symbol to get executive compensation for (e.g., 'AAPL', 'MSFT', 'TSLA')
1993
- *
1994
- * @returns Promise resolving to array of executive compensation data with detailed pay information
1995
- *
1996
- * @example
1997
- * ```typescript
1998
- * // Get Apple's executive compensation
1999
- * const compensation = await fmp.company.getExecutiveCompensation('AAPL');
2000
- * compensation.data.forEach(exec => {
2001
- * console.log(`${exec.name} (${exec.title}):`);
2002
- * console.log(` Salary: $${exec.salary.toLocaleString()}`);
2003
- * console.log(` Bonus: $${exec.bonus.toLocaleString()}`);
2004
- * console.log(` Stock Options: $${exec.stockAwards.toLocaleString()}`);
2005
- * });
2006
- *
2007
- * // Get Tesla's executive compensation
2008
- * const teslaComp = await fmp.company.getExecutiveCompensation('TSLA');
2009
- * ```
2010
- *
2011
- * @see {@link https://site.financialmodelingprep.com/developer/docs#executive-compensation-company-information|FMP Executive Compensation Documentation}
2012
- */
2013
- async getExecutiveCompensation(symbol) {
2014
- return this.client.get(`/governance/executive_compensation`, "v4", { symbol });
2015
- }
2016
- /**
2017
- * Get company notes and financial disclosures
2018
- *
2019
- * Provides important notes and disclosures from company financial statements.
2020
- * These notes contain critical information about accounting policies, risks,
2021
- * contingencies, and other material information that affects financial analysis.
2022
- *
2023
- * @param symbol - The stock symbol to get notes for (e.g., 'AAPL', 'MSFT', 'JPM')
2024
- *
2025
- * @returns Promise resolving to array of company notes with detailed disclosure information
2026
- *
2027
- * @example
2028
- * ```typescript
2029
- * // Get Apple's company notes
2030
- * const notes = await fmp.company.getCompanyNotes('AAPL');
2031
- * notes.data.forEach(note => {
2032
- * console.log(`Note ${note.noteNumber}: ${note.noteTitle}`);
2033
- * console.log(` Content: ${note.noteContent.substring(0, 100)}...`);
2034
- * });
2035
- *
2036
- * // Get JPMorgan's notes
2037
- * const jpmNotes = await fmp.company.getCompanyNotes('JPM');
2038
- * ```
2039
- *
2040
- * @see {@link https://site.financialmodelingprep.com/developer/docs#company-notes-company-information|FMP Company Notes Documentation}
2041
- */
2042
- async getCompanyNotes(symbol) {
2043
- return this.client.get(`/company-notes`, "v4", { symbol });
2044
- }
2045
- /**
2046
- * Get historical employee count data
2047
- *
2048
- * Provides historical data on company employee counts over time.
2049
- * Useful for analyzing company growth, operational efficiency, and workforce trends.
2050
- * Employee count is often a key indicator of company expansion or contraction.
2051
- *
2052
- * @param symbol - The stock symbol to get historical employee count for (e.g., 'AAPL', 'MSFT', 'AMZN')
2053
- *
2054
- * @returns Promise resolving to array of historical employee count data with year-by-year information
2055
- *
2056
- * @example
2057
- * ```typescript
2058
- * // Get Apple's employee count history
2059
- * const employees = await fmp.company.getHistoricalEmployeeCount('AAPL');
2060
- * employees.data.forEach(year => {
2061
- * console.log(`${year.year}: ${year.employeeCount.toLocaleString()} employees`);
2062
- * });
2063
- *
2064
- * // Get Amazon's employee growth
2065
- * const amazonEmployees = await fmp.company.getHistoricalEmployeeCount('AMZN');
2066
- * ```
2067
- *
2068
- * @see {@link https://site.financialmodelingprep.com/developer/docs#historical-employee-company-information|FMP Historical Employee Count Documentation}
2069
- */
2070
- async getHistoricalEmployeeCount(symbol) {
2071
- return this.client.get(`/historical/employee_count`, "v4", { symbol });
2072
- }
2073
- /**
2074
- * Get current shares float information
2075
- *
2076
- * Provides the total number of shares that are publicly traded (float) for a company.
2077
- * The float is calculated by subtracting restricted shares from total outstanding shares.
2078
- * Important for understanding liquidity, volatility, and trading dynamics.
2079
- *
2080
- * @param symbol - The stock symbol to get shares float for (e.g., 'AAPL', 'TSLA', 'NVDA')
2081
- *
2082
- * @returns Promise resolving to shares float data with current float information
2083
- *
2084
- * @example
2085
- * ```typescript
2086
- * // Get Apple's shares float
2087
- * const float = await fmp.company.getSharesFloat('AAPL');
2088
- * console.log(`Float: ${float.data.sharesFloat.toLocaleString()} shares`);
2089
- * console.log(`Outstanding: ${float.data.sharesOutstanding.toLocaleString()} shares`);
2090
- * console.log(`Restricted: ${float.data.restrictedShares.toLocaleString()} shares`);
2091
- *
2092
- * // Get Tesla's float
2093
- * const teslaFloat = await fmp.company.getSharesFloat('TSLA');
2094
- * ```
2095
- *
2096
- * @see {@link https://site.financialmodelingprep.com/developer/docs#company-share-float-share-float|FMP Shares Float Documentation}
2097
- */
2098
- async getSharesFloat(symbol) {
2099
- return this.client.getSingle(`/shares_float`, "v4", { symbol });
2100
- }
2101
- /**
2102
- * Get historical shares float data
2103
- *
2104
- * Provides historical data on company shares float over time.
2105
- * Useful for analyzing changes in liquidity, share issuance, and corporate actions
2106
- * that affect the number of publicly traded shares.
2107
- *
2108
- * @param symbol - The stock symbol to get historical shares float for (e.g., 'AAPL', 'TSLA', 'NVDA')
2109
- *
2110
- * @returns Promise resolving to array of historical shares float data with date-by-date information
2111
- *
2112
- * @example
2113
- * ```typescript
2114
- * // Get Apple's historical float
2115
- * const historicalFloat = await fmp.company.getHistoricalSharesFloat('AAPL');
2116
- * historicalFloat.data.forEach(entry => {
2117
- * console.log(`${entry.date}: ${entry.sharesFloat.toLocaleString()} shares`);
2118
- * });
2119
- *
2120
- * // Get Tesla's float history
2121
- * const teslaHistory = await fmp.company.getHistoricalSharesFloat('TSLA');
2122
- * ```
2123
- *
2124
- * @see {@link https://site.financialmodelingprep.com/developer/docs#company-historical-share-float|FMP Historical Shares Float Documentation}
2125
- */
2126
- async getHistoricalSharesFloat(symbol) {
2127
- return this.client.get(`/historical/shares_float`, "v4", { symbol });
2128
- }
2129
- /**
2130
- * Get earnings call transcript for specific quarter
2131
- *
2132
- * Provides the full transcript of a company's earnings conference call.
2133
- * Contains detailed Q&A sessions, management commentary, and insights into
2134
- * company performance, strategy, and future outlook.
2135
- *
2136
- * @param params - Earnings call transcript request parameters
2137
- * @param params.symbol - The stock symbol to get transcript for (e.g., 'AAPL', 'MSFT', 'TSLA')
2138
- * @param params.year - The year of the earnings call (e.g., 2024)
2139
- * @param params.quarter - The quarter of the earnings call (1, 2, 3, or 4)
2140
- *
2141
- * @returns Promise resolving to earnings call transcript with full text content
2142
- *
2143
- * @example
2144
- * ```typescript
2145
- * // Get Apple's Q1 2024 earnings call
2146
- * const transcript = await fmp.company.getEarningsCallTranscript({
2147
- * symbol: 'AAPL',
2148
- * year: 2024,
2149
- * quarter: 1
2150
- * });
2151
- * console.log(`Transcript: ${transcript.data[0].content.substring(0, 200)}...`);
2152
- *
2153
- * // Get Tesla's Q4 2023 earnings call
2154
- * const teslaTranscript = await fmp.company.getEarningsCallTranscript({
2155
- * symbol: 'TSLA',
2156
- * year: 2023,
2157
- * quarter: 4
2158
- * });
2159
- * ```
2160
- *
2161
- * @see {@link https://site.financialmodelingprep.com/developer/docs#earnings-transcript-earnings-transcripts|FMP Earnings Call Transcript Documentation}
2162
- */
2163
- async getEarningsCallTranscript(params) {
2164
- const { symbol, year, quarter } = params;
2165
- return this.client.getSingle(`/earning_call_transcript/${symbol}`, "v3", { year, quarter });
2166
- }
2167
- /**
2168
- * Get available earnings call transcript dates
2169
- *
2170
- * Provides a list of all available earnings call transcript dates for a company.
2171
- * Useful for discovering which quarters have transcripts available before
2172
- * requesting the full transcript content.
2173
- *
2174
- * @param symbol - The stock symbol to get transcript dates for (e.g., 'AAPL', 'MSFT', 'TSLA')
2175
- *
2176
- * @returns Promise resolving to array of available transcript dates with quarter information
2177
- *
2178
- * @example
2179
- * ```typescript
2180
- * // Get Apple's available transcript dates
2181
- * const transcriptDates = await fmp.company.getCompanyTranscriptData('AAPL');
2182
- * transcriptDates.data.forEach(date => {
2183
- * console.log(`Q${date.quarter} ${date.year}: ${date.date}`);
2184
- * });
2185
- *
2186
- * // Get Microsoft's transcript availability
2187
- * const msftDates = await fmp.company.getCompanyTranscriptData('MSFT');
2188
- * ```
2189
- *
2190
- * @see {@link https://site.financialmodelingprep.com/developer/docs#transcript-dates-earnings-transcripts|FMP Company Transcript Data Documentation}
2191
- */
2192
- async getCompanyTranscriptData(symbol) {
2193
- return this.client.getSingle(`/earning_call_transcript`, "v4", { symbol });
2194
- }
2195
- };
2196
-
2197
- // src/endpoints/quote.ts
2198
- var QuoteEndpoints = class {
2199
- constructor(client) {
2200
- this.client = client;
2201
- }
2202
- /**
2203
- * Get real-time quote data for any asset type (stocks, crypto, forex, commodities, ETFs)
2204
- *
2205
- * This endpoint provides current market data including price, volume, market cap, and key metrics.
2206
- * Works with any valid symbol across all supported asset classes.
2207
- *
2208
- * @param symbol - The trading symbol (e.g., 'AAPL', 'BTCUSD', 'EURUSD', 'GCUSD', 'SPY')
2209
- *
2210
- * @returns Promise resolving to quote data with current price, volume, market cap, and performance metrics
2211
- *
2212
- * @example
2213
- * ```typescript
2214
- * // Get stock quote
2215
- * const aaplQuote = await fmp.quote.getQuote('AAPL');
2216
- *
2217
- * // Get crypto quote
2218
- * const btcQuote = await fmp.quote.getQuote('BTCUSD');
2219
- *
2220
- * // Get forex quote
2221
- * const eurQuote = await fmp.quote.getQuote('EURUSD');
2222
- * ```
2223
- */
2224
- async getQuote(symbol) {
2225
- return this.client.getSingle(`/quote/${symbol}`, "v3");
2226
- }
2227
- /**
2228
- * Get historical price data for any asset type with customizable date range
2229
- *
2230
- * Retrieves daily OHLCV (Open, High, Low, Close, Volume) data for the specified symbol.
2231
- * Data includes adjusted close prices, volume, and percentage changes.
2232
- *
2233
- * @param params - Historical price request parameters
2234
- * @param params.symbol - The trading symbol to get historical data for
2235
- * @param params.from - Start date in YYYY-MM-DD format (optional, defaults to 1 year ago)
2236
- * @param params.to - End date in YYYY-MM-DD format (optional, defaults to today)
2237
- *
2238
- * @returns Promise resolving to historical price data with daily OHLCV information
2239
- *
2240
- * @example
2241
- * ```typescript
2242
- * // Get last year's data
2243
- * const history = await fmp.quote.getHistoricalPrice({
2244
- * symbol: 'AAPL',
2245
- * from: '2023-01-01',
2246
- * to: '2023-12-31'
2247
- * });
2248
- *
2249
- * // Get recent data (last 30 days)
2250
- * const recent = await fmp.quote.getHistoricalPrice({
2251
- * symbol: 'BTCUSD',
2252
- * from: '2024-01-01'
2253
- * });
2254
- * ```
2255
- */
2256
- async getHistoricalPrice(params) {
2257
- const { symbol, from, to } = params;
2258
- const queryParams = {};
2259
- if (from) queryParams.from = from;
2260
- if (to) queryParams.to = to;
2261
- return this.client.getSingle(`/historical-price-full/${symbol}`, "v3", queryParams);
2262
- }
2263
- /**
2264
- * Get real-time quotes for multiple symbols in a single request
2265
- *
2266
- * Efficiently retrieve quote data for multiple assets across different asset classes.
2267
- * Useful for portfolio tracking, market monitoring, or batch data collection.
2268
- *
2269
- * @param symbols - Array of trading symbols to get quotes for
2270
- *
2271
- * @returns Promise resolving to an array of quote data for all requested symbols
2272
- *
2273
- * @example
2274
- * ```typescript
2275
- * // Get quotes for a mixed portfolio
2276
- * const quotes = await fmp.quote.getQuotes([
2277
- * 'AAPL', // Stock
2278
- * 'BTCUSD', // Crypto
2279
- * 'EURUSD', // Forex
2280
- * 'SPY' // ETF
2281
- * ]);
2282
- *
2283
- * // Get quotes for tech stocks
2284
- * const techQuotes = await fmp.quote.getQuotes([
2285
- * 'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA'
2286
- * ]);
2287
- * ```
2288
- */
2289
- async getQuotes(symbols) {
2290
- const symbolsParam = symbols.join(",");
2291
- return this.client.get(`/quote/${symbolsParam}`, "v3");
2292
- }
2293
- /**
2294
- * Get intraday price data with customizable time intervals
2295
- *
2296
- * Retrieves intraday OHLCV data at specified intervals (1min to 4hour).
2297
- * Perfect for technical analysis, day trading, or short-term price monitoring.
2298
- *
2299
- * @param params - Intraday request parameters
2300
- * @param params.symbol - The trading symbol to get intraday data for
2301
- * @param params.interval - Time interval: '1min', '5min', '15min', '30min', '1hour', or '4hour'
2302
- * @param params.from - Start date in YYYY-MM-DD format (optional)
2303
- * @param params.to - End date in YYYY-MM-DD format (optional)
2304
- *
2305
- * @returns Promise resolving to intraday price data with OHLCV information at specified intervals
2306
- *
2307
- * @example
2308
- * ```typescript
2309
- * // Get 5-minute intraday data for today
2310
- * const intraday = await fmp.quote.getIntraday({
2311
- * symbol: 'AAPL',
2312
- * interval: '5min',
2313
- * from: '2024-01-15'
2314
- * });
2315
- *
2316
- * // Get 1-hour data for crypto
2317
- * const cryptoIntraday = await fmp.quote.getIntraday({
2318
- * symbol: 'BTCUSD',
2319
- * interval: '1hour',
2320
- * from: '2024-01-10',
2321
- * to: '2024-01-15'
2322
- * });
2323
- * ```
2324
- */
2325
- async getIntraday(params) {
2326
- const { symbol, interval, from, to } = params;
2327
- const queryParams = {};
2328
- if (from) queryParams.from = from;
2329
- if (to) queryParams.to = to;
2330
- return this.client.get(`/historical-chart/${interval}/${symbol}`, "v3", queryParams);
2331
- }
2332
- };
2333
-
2334
- // src/endpoints/senate-house.ts
2335
- var SenateHouseEndpoints = class {
2336
- constructor(client) {
2337
- this.client = client;
2338
- }
2339
- /**
2340
- * Get senate trading data for a specific stock symbol
2341
- *
2342
- * Provides detailed information about senate members' trading activities for a specific stock.
2343
- * Includes transaction details, amounts, dates, and ownership information for transparency
2344
- * and compliance with the STOCK Act (Stop Trading on Congressional Knowledge).
2345
- *
2346
- * @param params - Senate trading request parameters
2347
- * @param params.symbol - The stock symbol to get senate trading data for (e.g., 'AAPL', 'MSFT', 'TSLA')
2348
- *
2349
- * @returns Promise resolving to array of senate trading data with transaction details
2350
- *
2351
- * @example
2352
- * ```typescript
2353
- * // Get senate trading data for Apple
2354
- * const appleSenateTrading = await fmp.senateHouse.getSenateTrading({ symbol: 'AAPL' });
2355
- * appleSenateTrading.data.forEach(trade => {
2356
- * console.log(`${trade.firstName} ${trade.lastName} (${trade.office}):`);
2357
- * console.log(` ${trade.type} ${trade.amount} of ${trade.assetDescription}`);
2358
- * console.log(` Transaction Date: ${trade.transactionDate}`);
2359
- * });
2360
- *
2361
- * // Get senate trading data for Tesla
2362
- * const teslaSenateTrading = await fmp.senateHouse.getSenateTrading({ symbol: 'TSLA' });
2363
- * ```
2364
- *
2365
- * @see {@link https://site.financialmodelingprep.com/developer/docs#senate-trading|FMP Senate Trading Documentation}
2366
- */
2367
- async getSenateTrading(params) {
2368
- const { symbol } = params;
2369
- return this.client.get(`/senate-trading`, "v4", { symbol });
2370
- }
2371
- /**
2372
- * Get senate trading RSS feed with pagination
2373
- *
2374
- * Provides a paginated RSS feed of all senate trading activities across all stocks.
2375
- * Useful for monitoring congressional trading activities, compliance tracking,
2376
- * and transparency reporting. Returns recent trading disclosures from senate members.
2377
- *
2378
- * @param params - Senate trading RSS feed request parameters
2379
- * @param params.page - The page number to retrieve (starts from 0)
2380
- *
2381
- * @returns Promise resolving to array of senate trading data from RSS feed
2382
- *
2383
- * @example
2384
- * ```typescript
2385
- * // Get first page of senate trading RSS feed
2386
- * const firstPage = await fmp.senateHouse.getSenateTradingRSSFeed({ page: 0 });
2387
- * console.log(`First page: ${firstPage.data.length} trading activities`);
2388
- *
2389
- * // Get second page of senate trading RSS feed
2390
- * const secondPage = await fmp.senateHouse.getSenateTradingRSSFeed({ page: 1 });
2391
- * console.log(`Second page: ${secondPage.data.length} trading activities`);
2392
- *
2393
- * // Get recent senate trading activities
2394
- * const recentTrades = await fmp.senateHouse.getSenateTradingRSSFeed({ page: 0 });
2395
- * recentTrades.data.forEach(trade => {
2396
- * console.log(`${trade.firstName} ${trade.lastName}: ${trade.type} ${trade.amount}`);
2397
- * });
2398
- * ```
2399
- *
2400
- * @see {@link https://site.financialmodelingprep.com/developer/docs#senate-trading-rss-feed-senate|FMP Senate Trading RSS Feed Documentation}
2401
- */
2402
- async getSenateTradingRSSFeed(params) {
2403
- const { page } = params;
2404
- return this.client.get("/senate-trading-rss-feed", "v4", { page });
2405
- }
2406
- /**
2407
- * Get senate trading data for a specific senator by name
2408
- *
2409
- * Provides detailed trading activities for a specific senate member across all stocks.
2410
- * Useful for tracking individual senator's trading patterns, compliance monitoring,
2411
- * and transparency reporting. Returns all trading disclosures for the specified senator.
2412
- *
2413
- * @param params - Senate trading by name request parameters
2414
- * @param params.name - The name of the senator to get trading data for (e.g., 'John Smith', 'Jane Doe')
2415
- *
2416
- * @returns Promise resolving to array of senate trading data for the specified senator
2417
- *
2418
- * @example
2419
- * ```typescript
2420
- * // Get trading data for Senator John Smith
2421
- * const johnSmithTrades = await fmp.senateHouse.getSenateTradingByName({ name: 'John Smith' });
2422
- * johnSmithTrades.data.forEach(trade => {
2423
- * console.log(`${trade.symbol}: ${trade.type} ${trade.amount}`);
2424
- * console.log(` Transaction Date: ${trade.transactionDate}`);
2425
- * console.log(` Asset: ${trade.assetDescription}`);
2426
- * });
2427
- *
2428
- * // Get trading data for Senator Jane Doe
2429
- * const janeDoeTrades = await fmp.senateHouse.getSenateTradingByName({ name: 'Jane Doe' });
2430
- * console.log(`Jane Doe has ${janeDoeTrades.data.length} trading activities`);
2431
- * ```
2432
- *
2433
- * @see {@link https://site.financialmodelingprep.com/developer/docs/stable#senate-trading-by-name|FMP Senate Trading by Name Documentation}
2434
- */
2435
- async getSenateTradingByName(params) {
2436
- const { name } = params;
2437
- return this.client.get("/senate-trades-by-name", "stable", { name });
2438
- }
2439
- /**
2440
- * Get house trading data for a specific stock symbol
2441
- *
2442
- * Provides detailed information about house representatives' trading activities for a specific stock.
2443
- * Includes transaction details, amounts, dates, and district information for transparency
2444
- * and compliance with the STOCK Act (Stop Trading on Congressional Knowledge).
2445
- *
2446
- * @param params - House trading request parameters
2447
- * @param params.symbol - The stock symbol to get house trading data for (e.g., 'AAPL', 'MSFT', 'TSLA')
2448
- *
2449
- * @returns Promise resolving to array of house trading data with transaction details
2450
- *
2451
- * @example
2452
- * ```typescript
2453
- * // Get house trading data for Apple
2454
- * const appleHouseTrading = await fmp.senateHouse.getHouseTrading({ symbol: 'AAPL' });
2455
- * appleHouseTrading.data.forEach(trade => {
2456
- * console.log(`${trade.representative} (District ${trade.district}):`);
2457
- * console.log(` ${trade.type} ${trade.amount} of ${trade.assetDescription}`);
2458
- * console.log(` Transaction Date: ${trade.transactionDate}`);
2459
- * });
2460
- *
2461
- * // Get house trading data for Microsoft
2462
- * const msftHouseTrading = await fmp.senateHouse.getHouseTrading({ symbol: 'MSFT' });
2463
- * console.log(`Microsoft house trading activities: ${msftHouseTrading.data.length}`);
2464
- * ```
2465
- *
2466
- * @see {@link https://site.financialmodelingprep.com/developer/docs#house-disclosure|FMP House Trading Documentation}
2467
- */
2468
- async getHouseTrading(params) {
2469
- const { symbol } = params;
2470
- return this.client.get("/senate-disclosure", "v4", { symbol });
2471
- }
2472
- /**
2473
- * Get house trading RSS feed with pagination
2474
- *
2475
- * Provides a paginated RSS feed of all house trading activities across all stocks.
2476
- * Useful for monitoring congressional trading activities, compliance tracking,
2477
- * and transparency reporting. Returns recent trading disclosures from house representatives.
2478
- *
2479
- * @param params - House trading RSS feed request parameters
2480
- * @param params.page - The page number to retrieve (starts from 0)
2481
- *
2482
- * @returns Promise resolving to array of house trading data from RSS feed
2483
- *
2484
- * @example
2485
- * ```typescript
2486
- * // Get first page of house trading RSS feed
2487
- * const firstPage = await fmp.senateHouse.getHouseTradingRSSFeed({ page: 0 });
2488
- * console.log(`First page: ${firstPage.data.length} trading activities`);
2489
- *
2490
- * // Get second page of house trading RSS feed
2491
- * const secondPage = await fmp.senateHouse.getHouseTradingRSSFeed({ page: 1 });
2492
- * console.log(`Second page: ${secondPage.data.length} trading activities`);
2493
- *
2494
- * // Get recent house trading activities
2495
- * const recentTrades = await fmp.senateHouse.getHouseTradingRSSFeed({ page: 0 });
2496
- * recentTrades.data.forEach(trade => {
2497
- * console.log(`${trade.representative} (District ${trade.district}): ${trade.type} ${trade.amount}`);
2498
- * });
2499
- * ```
2500
- *
2501
- * @see {@link https://site.financialmodelingprep.com/developer/docs#house-disclosure-rss-feed-senate|FMP House Trading RSS Feed Documentation}
2502
- */
2503
- async getHouseTradingRSSFeed(params) {
2504
- const { page } = params;
2505
- return this.client.get("/senate-disclosure-rss-feed", "v4", { page });
2506
- }
2507
- /**
2508
- * Get house trading data for a specific representative by name
2509
- *
2510
- * Provides detailed trading activities for a specific house representative across all stocks.
2511
- * Useful for tracking individual representative's trading patterns, compliance monitoring,
2512
- * and transparency reporting. Returns all trading disclosures for the specified representative.
2513
- *
2514
- * @param params - House trading by name request parameters
2515
- * @param params.name - The name of the representative to get trading data for (e.g., 'John Smith', 'Jane Doe')
2516
- *
2517
- * @returns Promise resolving to array of house trading data for the specified representative
2518
- *
2519
- * @example
2520
- * ```typescript
2521
- * // Get trading data for Representative John Smith
2522
- * const johnSmithTrades = await fmp.senateHouse.getHouseTradingByName({ name: 'John Smith' });
2523
- * johnSmithTrades.data.forEach(trade => {
2524
- * console.log(`${trade.symbol}: ${trade.type} ${trade.amount}`);
2525
- * console.log(` Transaction Date: ${trade.transactionDate}`);
2526
- * console.log(` Asset: ${trade.assetDescription}`);
2527
- * console.log(` District: ${trade.district}`);
2528
- * });
2529
- *
2530
- * // Get trading data for Representative Jane Doe
2531
- * const janeDoeTrades = await fmp.senateHouse.getHouseTradingByName({ name: 'Jane Doe' });
2532
- * console.log(`Jane Doe has ${janeDoeTrades.data.length} trading activities`);
2533
- * ```
2534
- *
2535
- * @see {@link https://site.financialmodelingprep.com/developer/docs/stable#house-trading-by-name|FMP House Trading by Name Documentation}
2536
- */
2537
- async getHouseTradingByName(params) {
2538
- const { name } = params;
2539
- return this.client.get("/house-trades-by-name", "stable", { name });
2540
- }
2541
- };
2542
-
2543
- // src/endpoints/institutional.ts
2544
- var InstitutionalEndpoints = class {
2545
- constructor(client) {
2546
- this.client = client;
2547
- }
2548
- /**
2549
- * Get Form 13F institutional stock ownership data
2550
- *
2551
- * Provides Form 13F institutional stock ownership data for investment
2552
- * managers with over $100 million in assets under management. Essential
2553
- * for analyzing institutional investment patterns and holdings.
2554
- *
2555
- * @param params - Form 13F request parameters
2556
- * @param params.cik - Central Index Key (CIK) of the investment manager
2557
- * @param params.date - Specific date in YYYY-MM-DD format (optional, defaults to most recent filing)
2558
- *
2559
- * @returns Promise resolving to array of Form 13F institutional ownership data
2560
- *
2561
- * @example
2562
- * ```typescript
2563
- * // Get Berkshire Hathaway's Form 13F data
2564
- * const berkshire13F = await fmp.institutional.getForm13F({
2565
- * cik: '0001067983'
2566
- * });
2567
- * berkshire13F.data.forEach(holding => {
2568
- * console.log(`${holding.issuerName}: ${holding.value.toLocaleString()} shares, $${holding.value.toLocaleString()}`);
2569
- * });
2570
- *
2571
- * // Get Form 13F data for specific date
2572
- * const historical13F = await fmp.institutional.getForm13F({
2573
- * cik: '0001067983',
2574
- * date: '2023-12-31'
2575
- * });
2576
- *
2577
- * // Get BlackRock's Form 13F data
2578
- * const blackrock13F = await fmp.institutional.getForm13F({
2579
- * cik: '0001364742'
2580
- * });
2581
- * ```
2582
- *
2583
- * @see {@link https://site.financialmodelingprep.com/developer/docs#form-13f-13f---institutional-stock-ownership|FMP Form 13F Documentation}
2584
- */
2585
- async getForm13F(params) {
2586
- const { cik, date } = params;
2587
- const queryParams = {};
2588
- if (date) queryParams.date = date;
2589
- return this.client.get(`/form-thirteen/${cik}`, "v3", queryParams);
2590
- }
2591
- /**
2592
- * Get Form 13F filing dates for an investment manager
2593
- *
2594
- * Provides available filing dates for Form 13F submissions by a specific
2595
- * investment manager. Essential for discovering historical filing dates
2596
- * before requesting detailed Form 13F data.
2597
- *
2598
- * @param params - Form 13F dates request parameters
2599
- * @param params.cik - Central Index Key (CIK) of the investment manager
2600
- *
2601
- * @returns Promise resolving to array of available Form 13F filing dates
2602
- *
2603
- * @example
2604
- * ```typescript
2605
- * // Get Berkshire Hathaway's Form 13F filing dates
2606
- * const berkshireDates = await fmp.institutional.getForm13FDates({
2607
- * cik: '0001067983'
2608
- * });
2609
- * berkshireDates.data.forEach(date => {
2610
- * console.log(`Filing date: ${date}`);
2611
- * });
2612
- *
2613
- * // Get BlackRock's filing dates
2614
- * const blackrockDates = await fmp.institutional.getForm13FDates({
2615
- * cik: '0001364742'
2616
- * });
2617
- * ```
2618
- *
2619
- * @see {@link https://site.financialmodelingprep.com/developer/docs#form-13f-dates-13f---institutional-stock-ownership|FMP Form 13F Dates Documentation}
2620
- */
2621
- async getForm13FDates(params) {
2622
- const { cik } = params;
2623
- return this.client.get(`/form-thirteen-date/${cik}`, "v3");
2624
- }
2625
- /**
2626
- * Get institutional holders for a company
2627
- *
2628
- * Provides data on institutional investors holding shares in a specific
2629
- * company. Essential for understanding institutional ownership patterns,
2630
- * major shareholders, and investment sentiment.
2631
- *
2632
- * @param params - Institutional holders request parameters
2633
- * @param params.symbol - Stock symbol to get institutional holders for
2634
- *
2635
- * @returns Promise resolving to array of institutional holders data
2636
- *
2637
- * @example
2638
- * ```typescript
2639
- * // Get Apple's institutional holders
2640
- * const appleHolders = await fmp.institutional.getInstitutionalHolders({
2641
- * symbol: 'AAPL'
2642
- * });
2643
- * appleHolders.data.forEach(holder => {
2644
- * console.log(`${holder.holder}: ${holder.shares.toLocaleString()} shares (${holder.weight}%)`);
2645
- * });
2646
- *
2647
- * // Get Microsoft's institutional holders
2648
- * const msftHolders = await fmp.institutional.getInstitutionalHolders({
2649
- * symbol: 'MSFT'
2650
- * });
2651
- *
2652
- * // Get Tesla's institutional holders
2653
- * const teslaHolders = await fmp.institutional.getInstitutionalHolders({
2654
- * symbol: 'TSLA'
2655
- * });
2656
- * ```
2657
- *
2658
- * @see {@link https://site.financialmodelingprep.com/developer/docs#institutional-holder-13f---institutional-stock-ownership|FMP Institutional Holders Documentation}
2659
- */
2660
- async getInstitutionalHolders(params) {
2661
- const { symbol } = params;
2662
- return this.client.get(`/institutional-holder/${symbol}`, "v3");
2663
- }
2664
- };
2665
-
2666
- // src/endpoints/insider.ts
2667
- var InsiderEndpoints = class {
2668
- constructor(client) {
2669
- this.client = client;
2670
- }
2671
- /**
2672
- * Get insider trading RSS feed data
2673
- *
2674
- * Provides real-time RSS feed of insider trading activities across all
2675
- * publicly traded companies. Essential for monitoring insider trading
2676
- * patterns, corporate governance, and potential market-moving events.
2677
- *
2678
- * @param params - RSS feed request parameters
2679
- * @param params.page - Page number for pagination (default: 0)
2680
- *
2681
- * @returns Promise resolving to array of insider trading RSS feed data
2682
- *
2683
- * @example
2684
- * ```typescript
2685
- * // Get first page of insider trading RSS feed
2686
- * const rssFeed = await fmp.insider.getInsiderTradingRSS({ page: 0 });
2687
- * rssFeed.data.forEach(trade => {
2688
- * console.log(`${trade.date}: ${trade.symbol} - ${trade.insiderName} ${trade.transactionType}`);
2689
- * });
2690
- *
2691
- * // Get second page of RSS feed
2692
- * const nextPage = await fmp.insider.getInsiderTradingRSS({ page: 1 });
2693
- * ```
2694
- *
2695
- * @see {@link https://site.financialmodelingprep.com/developer/docs#insider-trades-rss-insider-trading|FMP Insider Trading RSS Documentation}
2696
- */
2697
- async getInsiderTradingRSS(params) {
2698
- const { page = 0 } = params;
2699
- return this.client.get(`/insider-trading-rss-feed`, "v4", { page });
2700
- }
2701
- /**
2702
- * Search for insider trades with advanced filtering
2703
- *
2704
- * Provides comprehensive insider trading data with multiple filtering options
2705
- * including symbol, CIK numbers, and transaction types. Essential for detailed
2706
- * analysis of insider trading patterns and corporate governance.
2707
- *
2708
- * @param params - Insider trading search parameters
2709
- * @param params.symbol - Stock symbol to filter by (optional)
2710
- * @param params.reportingCik - Reporting CIK to filter by (optional)
2711
- * @param params.companyCik - Company CIK to filter by (optional)
2712
- * @param params.transactionType - Transaction type to filter by (optional)
2713
- * @param params.page - Page number for pagination (default: 0)
2714
- *
2715
- * @returns Promise resolving to array of insider trading search results
2716
- *
2717
- * @example
2718
- * ```typescript
2719
- * // Search for Apple insider trades
2720
- * const appleTrades = await fmp.insider.searchInsiderTrading({
2721
- * symbol: 'AAPL',
2722
- * page: 0
2723
- * });
2724
- * appleTrades.data.forEach(trade => {
2725
- * console.log(`${trade.date}: ${trade.insiderName} - ${trade.transactionType} ${trade.sharesTraded} shares`);
2726
- * });
2727
- *
2728
- * // Search by transaction type
2729
- * const purchases = await fmp.insider.searchInsiderTrading({
2730
- * transactionType: 'P-Purchase',
2731
- * page: 0
2732
- * });
2733
- *
2734
- * // Search by CIK
2735
- * const cikTrades = await fmp.insider.searchInsiderTrading({
2736
- * companyCik: '0000320193',
2737
- * page: 0
2738
- * });
2739
- * ```
2740
- *
2741
- * @see {@link https://site.financialmodelingprep.com/developer/docs#insider-trades-search-insider-trading|FMP Insider Trading Search Documentation}
2742
- */
2743
- async searchInsiderTrading(params) {
2744
- const { symbol, reportingCik, companyCik, transactionType, page = 0 } = params;
2745
- const queryParams = { page };
2746
- if (symbol) queryParams.symbol = symbol;
2747
- if (reportingCik) queryParams.reportingCik = reportingCik;
2748
- if (companyCik) queryParams.companyCik = companyCik;
2749
- if (transactionType) queryParams.transactionType = transactionType;
2750
- return this.client.get(`/insider-trading`, "v4", queryParams);
2751
- }
2752
- /**
2753
- * Get all available transaction types
2754
- *
2755
- * Provides a comprehensive list of all insider trading transaction types
2756
- * used in SEC filings. Essential for understanding different types of
2757
- * insider trading activities and filtering search results.
2758
- *
2759
- * @returns Promise resolving to array of transaction types with descriptions
2760
- *
2761
- * @example
2762
- * ```typescript
2763
- * // Get all transaction types
2764
- * const transactionTypes = await fmp.insider.getTransactionTypes();
2765
- * transactionTypes.data.forEach(type => {
2766
- * console.log(`${type.code}: ${type.description}`);
2767
- * });
2768
- * ```
2769
- *
2770
- * @see {@link https://site.financialmodelingprep.com/developer/docs#transaction-types-insider-trading|FMP Transaction Types Documentation}
2771
- */
2772
- async getTransactionTypes() {
2773
- return this.client.get(`/insider-trading-transaction-type`, "v4");
2774
- }
2775
- /**
2776
- * Get insiders roster for a specific company
2777
- *
2778
- * Provides a list of all insiders (officers, directors, and beneficial owners)
2779
- * for a specific company. Essential for understanding corporate governance
2780
- * structure and identifying key personnel.
2781
- *
2782
- * @param params - Insiders request parameters
2783
- * @param params.symbol - Stock symbol to get insiders for
2784
- *
2785
- * @returns Promise resolving to array of insiders data for the company
2786
- *
2787
- * @example
2788
- * ```typescript
2789
- * // Get Apple's insiders roster
2790
- * const appleInsiders = await fmp.insider.getInsidersBySymbol({ symbol: 'AAPL' });
2791
- * appleInsiders.data.forEach(insider => {
2792
- * console.log(`${insider.name} - ${insider.title} (${insider.cik})`);
2793
- * });
2794
- *
2795
- * // Get Microsoft's insiders
2796
- * const msftInsiders = await fmp.insider.getInsidersBySymbol({ symbol: 'MSFT' });
2797
- * ```
2798
- *
2799
- * @see {@link https://site.financialmodelingprep.com/developer/docs#insiders-by-symbol-insider-trading|FMP Insiders by Symbol Documentation}
2800
- */
2801
- async getInsidersBySymbol(params) {
2802
- const { symbol } = params;
2803
- return this.client.get(`/insider-roaster`, "v4", { symbol });
2804
- }
2805
- /**
2806
- * Get insider trade statistics for a company
2807
- *
2808
- * Provides comprehensive statistics on insider trading activity for a
2809
- * specific company including total trades, volume, and value metrics.
2810
- * Essential for analyzing insider trading patterns and sentiment.
2811
- *
2812
- * @param params - Statistics request parameters
2813
- * @param params.symbol - Stock symbol to get statistics for
2814
- *
2815
- * @returns Promise resolving to array of insider trade statistics data
2816
- *
2817
- * @example
2818
- * ```typescript
2819
- * // Get Apple's insider trade statistics
2820
- * const appleStats = await fmp.insider.getInsiderTradeStatistics({ symbol: 'AAPL' });
2821
- * appleStats.data.forEach(stat => {
2822
- * console.log(`${stat.insiderName}: ${stat.totalTrades} trades, ${stat.totalShares} shares`);
2823
- * });
2824
- *
2825
- * // Get Microsoft's statistics
2826
- * const msftStats = await fmp.insider.getInsiderTradeStatistics({ symbol: 'MSFT' });
2827
- * ```
2828
- *
2829
- * @see {@link https://site.financialmodelingprep.com/developer/docs#insider-trade-statistics-insider-trading|FMP Insider Trade Statistics Documentation}
2830
- */
2831
- async getInsiderTradeStatistics(params) {
2832
- const { symbol } = params;
2833
- return this.client.get(`/insider-roaster-statistic`, "v4", { symbol });
2834
- }
2835
- /**
2836
- * Get CIK mapper data
2837
- *
2838
- * Provides a mapping between CIK (Central Index Key) numbers and company
2839
- * names. Essential for converting between CIK numbers and company
2840
- * identifiers in insider trading analysis.
2841
- *
2842
- * @param params - CIK mapper request parameters
2843
- * @param params.page - Page number for pagination (default: 0)
2844
- *
2845
- * @returns Promise resolving to array of CIK mapper data
2846
- *
2847
- * @example
2848
- * ```typescript
2849
- * // Get first page of CIK mapper
2850
- * const cikMapper = await fmp.insider.getCikMapper({ page: 0 });
2851
- * cikMapper.data.forEach(mapping => {
2852
- * console.log(`CIK: ${mapping.cik} - Company: ${mapping.name}`);
2853
- * });
2854
- *
2855
- * // Get second page
2856
- * const nextPage = await fmp.insider.getCikMapper({ page: 1 });
2857
- * ```
2858
- *
2859
- * @see {@link https://site.financialmodelingprep.com/developer/docs#cik-mapper-insider-trading|FMP CIK Mapper Documentation}
2860
- */
2861
- async getCikMapper(params) {
2862
- const { page = 0 } = params;
2863
- return this.client.get(`/mapper-cik-name`, "v4", { page });
2864
- }
2865
- /**
2866
- * Get CIK mapper by name search
2867
- *
2868
- * Provides CIK numbers and company names matching a search term.
2869
- * Useful for finding companies by partial name matches and
2870
- * converting company names to CIK numbers.
2871
- *
2872
- * @param params - CIK mapper by name request parameters
2873
- * @param params.name - Company name or partial name to search for
2874
- * @param params.page - Page number for pagination (default: 0)
2875
- *
2876
- * @returns Promise resolving to array of CIK mapper data matching the search
2877
- *
2878
- * @example
2879
- * ```typescript
2880
- * // Search for Apple by name
2881
- * const appleCik = await fmp.insider.getCikMapperByName({
2882
- * name: 'Apple',
2883
- * page: 0
2884
- * });
2885
- * appleCik.data.forEach(mapping => {
2886
- * console.log(`CIK: ${mapping.cik} - Company: ${mapping.name}`);
2887
- * });
2888
- *
2889
- * // Search for Microsoft
2890
- * const msftCik = await fmp.insider.getCikMapperByName({
2891
- * name: 'Microsoft',
2892
- * page: 0
2893
- * });
2894
- * ```
2895
- *
2896
- * @see {@link https://site.financialmodelingprep.com/developer/docs#cik-mapper-by-name-insider-trading|FMP CIK Mapper by Name Documentation}
2897
- */
2898
- async getCikMapperByName(params) {
2899
- const { name, page = 0 } = params;
2900
- return this.client.get(`/mapper-cik-name`, "v4", { name, page });
2901
- }
2902
- /**
2903
- * Get CIK mapper by symbol
2904
- *
2905
- * Provides CIK number and company name for a specific stock symbol.
2906
- * Essential for converting stock symbols to CIK numbers for use
2907
- * in insider trading searches and analysis.
2908
- *
2909
- * @param params - CIK mapper by symbol request parameters
2910
- * @param params.symbol - Stock symbol to get CIK for
2911
- *
2912
- * @returns Promise resolving to CIK mapper data for the symbol
2913
- *
2914
- * @example
2915
- * ```typescript
2916
- * // Get Apple's CIK by symbol
2917
- * const appleCik = await fmp.insider.getCikMapperBySymbol({ symbol: 'AAPL' });
2918
- * console.log(`Apple CIK: ${appleCik.data.cik} - ${appleCik.data.name}`);
2919
- *
2920
- * // Get Microsoft's CIK
2921
- * const msftCik = await fmp.insider.getCikMapperBySymbol({ symbol: 'MSFT' });
2922
- * ```
2923
- *
2924
- * @see {@link https://site.financialmodelingprep.com/developer/docs#cik-mapper-company-insider-trading|FMP CIK Mapper by Symbol Documentation}
2925
- */
2926
- async getCikMapperBySymbol(params) {
2927
- const { symbol } = params;
2928
- return this.client.getSingle(`/mapper-cik-company/${symbol}`, "v4");
2929
- }
2930
- /**
2931
- * Get beneficial ownership acquisitions
2932
- *
2933
- * Provides data on acquisitions of beneficial ownership for a specific
2934
- * company. Essential for tracking significant ownership changes and
2935
- * corporate governance events.
2936
- *
2937
- * @param params - Beneficial ownership request parameters
2938
- * @param params.symbol - Stock symbol to get beneficial ownership data for
2939
- *
2940
- * @returns Promise resolving to array of beneficial ownership acquisition data
2941
- *
2942
- * @example
2943
- * ```typescript
2944
- * // Get Apple's beneficial ownership acquisitions
2945
- * const appleOwnership = await fmp.insider.getBeneficialOwnership({ symbol: 'AAPL' });
2946
- * appleOwnership.data.forEach(acquisition => {
2947
- * console.log(`${acquisition.date}: ${acquisition.insiderName} acquired ${acquisition.sharesAcquired} shares`);
2948
- * });
2949
- *
2950
- * // Get Microsoft's beneficial ownership
2951
- * const msftOwnership = await fmp.insider.getBeneficialOwnership({ symbol: 'MSFT' });
2952
- * ```
2953
- *
2954
- * @see {@link https://site.financialmodelingprep.com/developer/docs#acquisition-of-beneficial-ownership|FMP Beneficial Ownership Documentation}
2955
- */
2956
- async getBeneficialOwnership(params) {
2957
- const { symbol } = params;
2958
- return this.client.get(`/insider/ownership/acquisition_of_beneficial_ownership`, "v4", {
2959
- symbol
2960
- });
2961
- }
2962
- /**
2963
- * Get fail to deliver data
2964
- *
2965
- * Provides fail to deliver data for a specific company, which indicates
2966
- * when market participants fail to deliver securities on settlement date.
2967
- * Important for understanding market mechanics and potential short interest.
2968
- *
2969
- * @param params - Fail to deliver request parameters
2970
- * @param params.symbol - Stock symbol to get fail to deliver data for
2971
- * @param params.page - Page number for pagination (default: 0)
2972
- *
2973
- * @returns Promise resolving to array of fail to deliver data
2974
- *
2975
- * @example
2976
- * ```typescript
2977
- * // Get Apple's fail to deliver data
2978
- * const appleFailToDeliver = await fmp.insider.getFailToDeliver({
2979
- * symbol: 'AAPL',
2980
- * page: 0
2981
- * });
2982
- * appleFailToDeliver.data.forEach(entry => {
2983
- * console.log(`${entry.date}: ${entry.shares} shares failed to deliver`);
2984
- * });
2985
- *
2986
- * // Get Microsoft's fail to deliver data
2987
- * const msftFailToDeliver = await fmp.insider.getFailToDeliver({
2988
- * symbol: 'MSFT',
2989
- * page: 0
2990
- * });
2991
- * ```
2992
- *
2993
- * @see {@link https://site.financialmodelingprep.com/developer/docs#fail-to-deliver|FMP Fail to Deliver Documentation}
2994
- */
2995
- async getFailToDeliver(params) {
2996
- const { symbol, page = 0 } = params;
2997
- return this.client.get(`/fail_to_deliver`, "v4", { symbol, page });
2998
- }
2999
- /**
3000
- * Get all insider trades for a symbol (convenience method)
3001
- * @param symbol - The stock symbol to get insider trades for
3002
- * @param page - Page number for pagination (default: 0)
3003
- * @returns A list of insider trades for the specified symbol
3004
- */
3005
- async getInsiderTradesBySymbol(symbol, page = 0) {
3006
- return this.searchInsiderTrading({ symbol, page });
3007
- }
3008
- /**
3009
- * Get insider trades by transaction type (convenience method)
3010
- * @param transactionType - The transaction type to filter by
3011
- * @param page - Page number for pagination (default: 0)
3012
- * @returns A list of insider trades filtered by transaction type
3013
- */
3014
- async getInsiderTradesByType(transactionType, page = 0) {
3015
- return this.searchInsiderTrading({ transactionType, page });
3016
- }
3017
- /**
3018
- * Get insider trades by reporting CIK (convenience method)
3019
- * @param reportingCik - The reporting CIK to filter by
3020
- * @param page - Page number for pagination (default: 0)
3021
- * @returns A list of insider trades filtered by reporting CIK
3022
- */
3023
- async getInsiderTradesByReportingCik(reportingCik, page = 0) {
3024
- return this.searchInsiderTrading({ reportingCik, page });
3025
- }
3026
- /**
3027
- * Get insider trades by company CIK (convenience method)
3028
- * @param companyCik - The company CIK to filter by
3029
- * @param page - Page number for pagination (default: 0)
3030
- * @returns A list of insider trades filtered by company CIK
3031
- */
3032
- async getInsiderTradesByCompanyCik(companyCik, page = 0) {
3033
- return this.searchInsiderTrading({ companyCik, page });
3034
- }
3035
- };
3036
-
3037
- // src/endpoints/sec.ts
3038
- var SECEndpoints = class {
3039
- constructor(client) {
3040
- this.client = client;
3041
- }
3042
- /**
3043
- * Get RSS feed of SEC filings
3044
- *
3045
- * Provides a real-time feed of SEC filings from publicly traded companies,
3046
- * including filing types, links to SEC pages, and direct links to filings.
3047
- * Essential for staying up-to-date on the latest SEC filings for all companies
3048
- * or for monitoring specific companies' regulatory activities.
3049
- *
3050
- * @param params - RSS feed parameters (optional)
3051
- * @returns Promise resolving to array of RSS feed items with SEC filing information
3052
- *
3053
- * @example
3054
- * ```typescript
3055
- * // Get all recent SEC filings
3056
- * const allFilings = await fmp.sec.getRSSFeed();
3057
- * console.log(`Recent SEC filings: ${allFilings.data.length}`);
3058
- *
3059
- * // Get specific filing type
3060
- * const form4Filings = await fmp.sec.getRSSFeed({ type: '4' });
3061
- * console.log(`Form 4 filings: ${form4Filings.data.length}`);
3062
- *
3063
- * // Get filings with date range
3064
- * const recentFilings = await fmp.sec.getRSSFeed({
3065
- * from: '2024-01-01',
3066
- * to: '2024-01-31'
3067
- * });
3068
- * console.log(`Recent filings: ${recentFilings.data.length}`);
3069
- *
3070
- * // Get limited results
3071
- * const limitedFilings = await fmp.sec.getRSSFeed({ limit: 10 });
3072
- * console.log(`Limited filings: ${limitedFilings.data.length}`);
3073
- * ```
3074
- *
3075
- * @see {@link https://site.financialmodelingprep.com/developer/docs#rss-feed-securities-and-exchange-commission-(s.e.c)|FMP RSS Feed Documentation}
3076
- */
3077
- async getRSSFeed(params) {
3078
- return this.client.get("/rss_feed", "v4", params);
3079
- }
3080
- /**
3081
- * Get comprehensive RSS feed of all SEC filings
3082
- *
3083
- * Provides a comprehensive real-time feed of all SEC filings from publicly
3084
- * traded companies in the latest RSS feed format. This endpoint offers the
3085
- * most complete overview of SEC filings with enhanced metadata and formatting.
3086
- *
3087
- * @param params - RSS feed all parameters (optional)
3088
- * @returns Promise resolving to array of comprehensive RSS feed items with enhanced SEC filing information
3089
- *
3090
- * @example
3091
- * ```typescript
3092
- * // Get all comprehensive SEC filings
3093
- * const allFilings = await fmp.sec.getRSSFeedAll();
3094
- * console.log(`Comprehensive SEC filings: ${allFilings.data.length}`);
3095
- *
3096
- * // Get paginated results
3097
- * const page2Filings = await fmp.sec.getRSSFeedAll({ page: 1 });
3098
- * console.log(`Page 2 filings: ${page2Filings.data.length}`);
3099
- *
3100
- * // Get specific data type
3101
- * const specificData = await fmp.sec.getRSSFeedAll({ datatype: 'json' });
3102
- * console.log(`Specific data type filings: ${specificData.data.length}`);
3103
- * ```
3104
- *
3105
- * @see {@link https://site.financialmodelingprep.com/developer/docs#rss-feed-all-securities-and-exchange-commission-(s.e.c)|FMP RSS Feed All Documentation}
3106
- */
3107
- async getRSSFeedAll(params) {
3108
- return this.client.get("/rss_feed_all", "v4", params);
3109
- }
3110
- /**
3111
- * Get RSS feed V3 of SEC filings
3112
- *
3113
- * Provides a real-time feed of SEC filings from publicly traded companies
3114
- * in the V3 RSS feed format. This version offers enhanced metadata and
3115
- * improved structure for better parsing and analysis of SEC filings.
3116
- *
3117
- * @param params - RSS feed V3 parameters (optional)
3118
- * @returns Promise resolving to array of V3 RSS feed items with enhanced SEC filing information
3119
- *
3120
- * @example
3121
- * ```typescript
3122
- * // Get V3 format SEC filings
3123
- * const v3Filings = await fmp.sec.getRSSFeedV3();
3124
- * console.log(`V3 SEC filings: ${v3Filings.data.length}`);
3125
- *
3126
- * // Get paginated V3 results
3127
- * const page2V3 = await fmp.sec.getRSSFeedV3({ page: 1 });
3128
- * console.log(`Page 2 V3 filings: ${page2V3.data.length}`);
3129
- *
3130
- * // Get specific data type
3131
- * const specificV3 = await fmp.sec.getRSSFeedV3({ datatype: 'json' });
3132
- * console.log(`Specific V3 data type: ${specificV3.data.length}`);
3133
- * ```
3134
- *
3135
- * @see {@link https://site.financialmodelingprep.com/developer/docs#rss-feed-v3-securities-and-exchange-commission-(s.e.c)|FMP RSS Feed V3 Documentation}
3136
- */
3137
- async getRSSFeedV3(params) {
3138
- return this.client.get("/rss_feed", "v3", params);
3139
- }
3140
- /**
3141
- * Get RSS feed of 8-K SEC filings
3142
- *
3143
- * Provides a real-time feed specifically for 8-K SEC filings from publicly
3144
- * traded companies. 8-K filings are used to announce major events that
3145
- * shareholders should know about, such as earnings releases, mergers,
3146
- * acquisitions, and other material events.
3147
- *
3148
- * @param params - RSS feed 8-K parameters (optional)
3149
- * @returns Promise resolving to array of 8-K RSS feed items with material event information
3150
- *
3151
- * @example
3152
- * ```typescript
3153
- * // Get all 8-K filings
3154
- * const form8KFilings = await fmp.sec.getRSSFeed8K();
3155
- * console.log(`8-K filings: ${form8KFilings.data.length}`);
3156
- *
3157
- * // Get 8-K filings with date range
3158
- * const recent8K = await fmp.sec.getRSSFeed8K({
3159
- * from: '2024-01-01',
3160
- * to: '2024-01-31'
3161
- * });
3162
- * console.log(`Recent 8-K filings: ${recent8K.data.length}`);
3163
- *
3164
- * // Get 8-K filings with financials
3165
- * const financial8K = await fmp.sec.getRSSFeed8K({ hasFinancial: true });
3166
- * console.log(`8-K filings with financials: ${financial8K.data.length}`);
3167
- *
3168
- * // Get limited 8-K results
3169
- * const limited8K = await fmp.sec.getRSSFeed8K({ limit: 10 });
3170
- * console.log(`Limited 8-K filings: ${limited8K.data.length}`);
3171
- * ```
3172
- *
3173
- * @see {@link https://site.financialmodelingprep.com/developer/docs#rss-feed-8-k-securities-and-exchange-commission-(s.e.c)|FMP RSS Feed 8-K Documentation}
3174
- */
3175
- async getRSSFeed8K(params) {
3176
- return this.client.get("/rss_feed_8k", "v4", params);
3177
- }
3178
- /**
3179
- * Get SEC filings for a specific company
3180
- *
3181
- * Provides direct access to SEC filings for a specific company, including
3182
- * filing types, links to SEC pages, and direct links to specific filings.
3183
- * Essential for monitoring a company's regulatory compliance and staying
3184
- * informed about important corporate events and disclosures.
3185
- *
3186
- * @param symbol - The stock symbol to get SEC filings for (e.g., 'AAPL', 'MSFT', 'GOOGL')
3187
- * @param params - SEC filings parameters (optional)
3188
- * @returns Promise resolving to array of SEC filings with detailed filing information
3189
- *
3190
- * @example
3191
- * ```typescript
3192
- * // Get all SEC filings for Apple
3193
- * const appleFilings = await fmp.sec.getSECFilings({ symbol: 'AAPL' });
3194
- * console.log(`Apple SEC filings: ${appleFilings.data.length}`);
3195
- *
3196
- * // Get specific filing type for Microsoft
3197
- * const msftForm4 = await fmp.sec.getSECFilings({
3198
- * symbol: 'MSFT',
3199
- * params: { type: '4' }
3200
- * });
3201
- * console.log(`Microsoft Form 4 filings: ${msftForm4.data.length}`);
3202
- * ```
3203
- *
3204
- * @see {@link https://site.financialmodelingprep.com/developer/docs#sec-filings-securities-and-exchange-commission-(s.e.c)|FMP SEC Filings Documentation}
3205
- */
3206
- async getSECFilings({
3207
- symbol,
3208
- params
3209
- }) {
3210
- return this.client.get(`/sec_filings/${symbol}`, "v3", params);
3211
- }
3212
- /**
3213
- * Get individual industry classification for a company
3214
- *
3215
- * Provides the industry classification for a specific company based on the
3216
- * Standard Industrial Classification (SIC) system. Essential for understanding
3217
- * a company's business sector, industry peers, and market positioning.
3218
- *
3219
- * @param params - Industry classification parameters
3220
- * @returns Promise resolving to industry classification data with SIC code and description
3221
- *
3222
- * @example
3223
- * ```typescript
3224
- * // Get Apple's industry classification by symbol
3225
- * const appleIndustry = await fmp.sec.getIndividualIndustryClassification({ symbol: 'AAPL' });
3226
- * console.log(`Apple Industry: ${appleIndustry.data.industryTitle}`);
3227
- * console.log(`SIC Code: ${appleIndustry.data.sicCode}`);
3228
- *
3229
- * // Get industry classification by CIK
3230
- * const cikIndustry = await fmp.sec.getIndividualIndustryClassification({ cik: 320193 });
3231
- * console.log(`CIK Industry: ${cikIndustry.data.industryTitle}`);
3232
- *
3233
- * // Get industry classification by SIC code
3234
- * const sicIndustry = await fmp.sec.getIndividualIndustryClassification({ sicCode: 3571 });
3235
- * console.log(`SIC Industry: ${sicIndustry.data.industryTitle}`);
3236
- * ```
3237
- *
3238
- * @see {@link https://site.financialmodelingprep.com/developer/docs#individual-industry-classification-standard-industrial-classification|FMP Individual Industry Classification Documentation}
3239
- */
3240
- async getIndividualIndustryClassification(params) {
3241
- return this.client.getSingle("/standard_industrial_classification", "v4", params);
3242
- }
3243
- /**
3244
- * Get all industry classifications
3245
- *
3246
- * Provides a comprehensive overview of all industries classified according
3247
- * to the Standard Industrial Classification (SIC) system. Essential for
3248
- * understanding industry categories, sector analysis, and market research.
3249
- *
3250
- * @returns Promise resolving to array of all industry classifications with SIC codes and descriptions
3251
- *
3252
- * @example
3253
- * ```typescript
3254
- * // Get all industry classifications
3255
- * const allIndustries = await fmp.sec.getAllIndustryClassifications();
3256
- * console.log(`Total industries: ${allIndustries.data.length}`);
3257
- *
3258
- * allIndustries.data.forEach((industry, index) => {
3259
- * console.log(`${index + 1}. ${industry.industryTitle}`);
3260
- * console.log(` SIC Code: ${industry.sicCode}`);
3261
- * });
3262
- *
3263
- * // Find specific industry
3264
- * const techIndustry = allIndustries.data.find(industry =>
3265
- * industry.industryTitle.toLowerCase().includes('computer')
3266
- * );
3267
- * console.log(`Tech Industry: ${techIndustry?.industryTitle}`);
3268
- * ```
3269
- *
3270
- * @see {@link https://site.financialmodelingprep.com/developer/docs#all-industry-classification-standard-industrial-classification|FMP All Industry Classifications Documentation}
3271
- */
3272
- async getAllIndustryClassifications() {
3273
- return this.client.get("/standard_industrial_classification/all", "v4");
3274
- }
3275
- /**
3276
- * Get industry classification codes
3277
- *
3278
- * Provides detailed information about the Standard Industrial Classification
3279
- * (SIC) system and helps identify SIC codes for specific industries.
3280
- * Essential for understanding industry categorization and sector analysis.
3281
- *
3282
- * @param params - Industry classification codes parameters
3283
- * @returns Promise resolving to array of industry classification codes with detailed information
3284
- *
3285
- * @example
3286
- * ```typescript
3287
- * // Get all industry classification codes
3288
- * const allCodes = await fmp.sec.getIndustryClassificationCodes({});
3289
- * console.log(`Total SIC codes: ${allCodes.data.length}`);
3290
- *
3291
- * // Search for specific SIC code
3292
- * const code3571 = await fmp.sec.getIndustryClassificationCodes({ sicCode: 3571 });
3293
- * console.log(`SIC 3571: ${code3571.data[0]?.industryTitle}`);
3294
- *
3295
- * // Search for industry by title
3296
- * const computerIndustry = await fmp.sec.getIndustryClassificationCodes({ industryTitle: 'Computer' });
3297
- * console.log(`Computer-related industries: ${computerIndustry.data.length}`);
3298
- * ```
3299
- *
3300
- * @see {@link https://site.financialmodelingprep.com/developer/docs#industry-classification-codes-standard-industrial-classification|FMP Industry Classification Codes Documentation}
3301
- */
3302
- async getIndustryClassificationCodes(params) {
3303
- return this.client.get("/standard_industrial_classification_list", "v4", params);
3304
- }
3305
- };
3306
-
3307
- // src/endpoints/mutual-fund.ts
3308
- var MutualFundEndpoints = class {
3309
- constructor(client) {
3310
- this.client = client;
3311
- }
3312
- /**
3313
- * Get mutual fund holders of a specific stock
3314
- *
3315
- * Provides data on mutual funds that hold shares in a specific stock.
3316
- * Essential for understanding mutual fund ownership patterns and
3317
- * which mutual funds are invested in particular companies.
3318
- *
3319
- * @param symbol - The stock symbol to get mutual fund holders for (e.g., 'AAPL', 'MSFT', 'GOOGL')
3320
- *
3321
- * @returns Promise resolving to array of mutual fund holders with position details
3322
- *
3323
- * @example
3324
- * ```typescript
3325
- * // Get mutual funds that hold Apple stock
3326
- * const appleHolders = await fmp.mutualFund.getHolders('AAPL');
3327
- * console.log(`${appleHolders.data.length} mutual funds hold AAPL`);
3328
- *
3329
- * appleHolders.data.forEach((holder, index) => {
3330
- * console.log(`${index + 1}. ${holder.holder}`);
3331
- * console.log(` Shares: ${holder.shares?.toLocaleString() || 'N/A'}`);
3332
- * console.log(` Weight: ${holder.weightPercent}% | Change: ${holder.change}`);
3333
- * });
3334
- *
3335
- * // Get mutual funds that hold Microsoft stock
3336
- * const msftHolders = await fmp.mutualFund.getHolders('MSFT');
3337
- *
3338
- * // Find top mutual fund holders by shares
3339
- * const topHolders = msftHolders.data
3340
- * .sort((a, b) => (b.shares || 0) - (a.shares || 0))
3341
- * .slice(0, 10);
3342
- * console.log('Top 10 mutual fund holders by shares:');
3343
- * topHolders.forEach((holder, index) => {
3344
- * console.log(`${index + 1}. ${holder.holder}: ${holder.shares.toLocaleString()} shares`);
3345
- * });
3346
- *
3347
- * // Get mutual funds that hold Google stock
3348
- * const googlHolders = await fmp.mutualFund.getHolders('GOOGL');
3349
- *
3350
- * // Analyze mutual fund concentration
3351
- * const totalShares = googlHolders.data.reduce((sum, holder) => sum + (holder.shares || 0), 0);
3352
- * console.log(`Total shares held by mutual funds: ${totalShares.toLocaleString()}`);
3353
- *
3354
- * googlHolders.data.forEach(holder => {
3355
- * const percentage = ((holder.shares || 0) / totalShares * 100).toFixed(2);
3356
- * console.log(`${holder.holder}: ${percentage}% of total mutual fund holdings`);
3357
- * });
3358
- * ```
3359
- *
3360
- * @see {@link https://site.financialmodelingprep.com/developer/docs#mutual-fund-holder-mutual-funds-holdings|FMP Mutual Fund Holders Documentation}
3361
- */
3362
- async getHolders(symbol) {
3363
- return this.client.get(`/mutual-fund-holder/${symbol}`, "v3");
3364
- }
3365
- };
3366
-
3367
- // src/fmp.ts
3368
- var FMP = class {
3369
- constructor(config = {}) {
3370
- const apiKey = config.apiKey || process.env.FMP_API_KEY;
3371
- if (!apiKey) {
3372
- throw new Error(
3373
- "FMP API key is required. Please provide it in the config or set the FMP_API_KEY environment variable."
3374
- );
3375
- }
3376
- if (!FMPValidation.isValidApiKey(apiKey)) {
3377
- throw new Error("Invalid API key format");
3378
- }
3379
- const client = new FMPClient({ ...config, apiKey });
3380
- this.stock = new StockEndpoints(client);
3381
- this.financial = new FinancialEndpoints(client);
3382
- this.etf = new ETFEndpoints(client);
3383
- this.economic = new EconomicEndpoints(client);
3384
- this.market = new MarketEndpoints(client);
3385
- this.list = new ListEndpoints(client);
3386
- this.calendar = new CalendarEndpoints(client);
3387
- this.company = new CompanyEndpoints(client);
3388
- this.quote = new QuoteEndpoints(client);
3389
- this.senateHouse = new SenateHouseEndpoints(client);
3390
- this.institutional = new InstitutionalEndpoints(client);
3391
- this.insider = new InsiderEndpoints(client);
3392
- this.sec = new SECEndpoints(client);
3393
- this.mutualFund = new MutualFundEndpoints(client);
3394
- }
3395
- /**
3396
- * Get the underlying client instance for advanced usage
3397
- */
3398
- getClient() {
3399
- return this.stock["client"];
3400
- }
3401
- };
3402
-
3403
- // src/types/common.ts
3404
- var Period = /* @__PURE__ */ ((Period2) => {
3405
- Period2["ANNUAL"] = "annual";
3406
- Period2["QUARTER"] = "quarter";
3407
- return Period2;
3408
- })(Period || {});
3409
- var Exchange = /* @__PURE__ */ ((Exchange2) => {
3410
- Exchange2["NYSE"] = "NYSE";
3411
- Exchange2["NASDAQ"] = "NASDAQ";
3412
- Exchange2["AMEX"] = "AMEX";
3413
- Exchange2["TSX"] = "TSX";
3414
- Exchange2["LSE"] = "LSE";
3415
- Exchange2["ASX"] = "ASX";
3416
- Exchange2["NSE"] = "NSE";
3417
- Exchange2["BSE"] = "BSE";
3418
- return Exchange2;
3419
- })(Exchange || {});
3420
-
3421
- // src/types/insider.ts
3422
- var TransactionType = /* @__PURE__ */ ((TransactionType2) => {
3423
- TransactionType2["AWARD"] = "A-Award";
3424
- TransactionType2["CONVERSION"] = "C-Conversion";
3425
- TransactionType2["RETURN"] = "D-Return";
3426
- TransactionType2["EXPIRE_SHORT"] = "E-ExpireShort";
3427
- TransactionType2["IN_KIND"] = "F-InKind";
3428
- TransactionType2["GIFT"] = "G-Gift";
3429
- TransactionType2["EXPIRE_LONG"] = "H-ExpireLong";
3430
- TransactionType2["DISCRETIONARY"] = "I-Discretionary";
3431
- TransactionType2["OTHER"] = "J-Other";
3432
- TransactionType2["SMALL"] = "L-Small";
3433
- TransactionType2["EXEMPT"] = "M-Exempt";
3434
- TransactionType2["OUT_OF_THE_MONEY"] = "O-OutOfTheMoney";
3435
- TransactionType2["PURCHASE"] = "P-Purchase";
3436
- TransactionType2["SALE"] = "S-Sale";
3437
- TransactionType2["TENDER"] = "U-Tender";
3438
- TransactionType2["WILL"] = "W-Will";
3439
- TransactionType2["IN_THE_MONEY"] = "X-InTheMoney";
3440
- TransactionType2["TRUST"] = "Z-Trust";
3441
- return TransactionType2;
3442
- })(TransactionType || {});
3443
-
3444
- // src/utils/constants.ts
3445
- var DEFAULT_TIMEOUT = 1e4;
3446
- var DEFAULT_LIMIT = 100;
3447
- var MAX_LIMIT = 1e3;
3448
- var PERIODS = {
3449
- ANNUAL: "annual",
3450
- QUARTER: "quarter"
3451
- };
3452
- var EXCHANGES = {
3453
- NYSE: "NYSE",
3454
- NASDAQ: "NASDAQ",
3455
- AMEX: "AMEX",
3456
- TSX: "TSX",
3457
- LSE: "LSE",
3458
- ASX: "ASX",
3459
- NSE: "NSE",
3460
- BSE: "BSE"
3461
- };
3462
- var SECTORS = {
3463
- TECHNOLOGY: "Technology",
3464
- HEALTHCARE: "Healthcare",
3465
- FINANCIAL: "Financial",
3466
- CONSUMER_DISCRETIONARY: "Consumer Discretionary",
3467
- CONSUMER_STAPLES: "Consumer Staples",
3468
- INDUSTRIALS: "Industrials",
3469
- ENERGY: "Energy",
3470
- MATERIALS: "Materials",
3471
- UTILITIES: "Utilities",
3472
- REAL_ESTATE: "Real Estate",
3473
- COMMUNICATION_SERVICES: "Communication Services"
3474
- };
3475
- var COUNTRIES = {
3476
- US: "US",
3477
- CA: "CA",
3478
- GB: "GB",
3479
- AU: "AU",
3480
- IN: "IN",
3481
- DE: "DE",
3482
- FR: "FR",
3483
- JP: "JP",
3484
- CN: "CN",
3485
- BR: "BR"
3486
- };
3487
- var ERROR_MESSAGES = {
3488
- API_KEY_REQUIRED: "API key is required",
3489
- SYMBOL_REQUIRED: "Symbol is required",
3490
- INVALID_SYMBOL: "Invalid symbol format",
3491
- INVALID_DATE: "Invalid date format. Use YYYY-MM-DD",
3492
- INVALID_PERIOD: 'Period must be either "annual" or "quarter"',
3493
- INVALID_LIMIT: "Limit must be between 1 and 1000",
3494
- INVALID_PAGE: "Page must be a non-negative number",
3495
- REQUEST_FAILED: "Request failed",
3496
- RATE_LIMIT_EXCEEDED: "Rate limit exceeded",
3497
- UNAUTHORIZED: "Unauthorized - Invalid API key",
3498
- NOT_FOUND: "Resource not found"
3499
- };
3500
- var HTTP_STATUS = {
3501
- OK: 200,
3502
- CREATED: 201,
3503
- BAD_REQUEST: 400,
3504
- UNAUTHORIZED: 401,
3505
- FORBIDDEN: 403,
3506
- NOT_FOUND: 404,
3507
- TOO_MANY_REQUESTS: 429,
3508
- INTERNAL_SERVER_ERROR: 500
3509
- };
3510
-
3511
- // src/utils/formatting.ts
3512
- function formatCurrency(value, currency = "USD") {
3513
- return new Intl.NumberFormat("en-US", {
3514
- style: "currency",
3515
- currency
3516
- }).format(value);
3517
- }
3518
- function formatPercentage(value, decimals = 2) {
3519
- return `${value.toFixed(decimals)}%`;
3520
- }
3521
- function formatLargeNumber(value) {
3522
- if (value >= 1e12) {
3523
- return `${(value / 1e12).toFixed(2)}T`;
3524
- } else if (value >= 1e9) {
3525
- return `${(value / 1e9).toFixed(2)}B`;
3526
- } else if (value >= 1e6) {
3527
- return `${(value / 1e6).toFixed(2)}M`;
3528
- } else if (value >= 1e3) {
3529
- return `${(value / 1e3).toFixed(2)}K`;
3530
- }
3531
- return value.toString();
3532
- }
3533
- function formatDate(date) {
3534
- const d = typeof date === "string" ? new Date(date) : date;
3535
- return d.toISOString().split("T")[0];
3536
- }
3537
- function formatReadableDate(date) {
3538
- const d = typeof date === "string" ? new Date(date) : date;
3539
- return d.toLocaleDateString("en-US", {
3540
- year: "numeric",
3541
- month: "long",
3542
- day: "numeric"
3543
- });
3544
- }
3545
- function formatTimestamp(timestamp) {
3546
- const date = new Date(timestamp * 1e3);
3547
- return date.toLocaleString("en-US");
3548
- }
3549
- function formatNumber(value, decimals = 2) {
3550
- return value.toFixed(decimals);
3551
- }
3552
- function formatVolume(volume) {
3553
- if (volume >= 1e9) {
3554
- return `${(volume / 1e9).toFixed(2)}B`;
3555
- } else if (volume >= 1e6) {
3556
- return `${(volume / 1e6).toFixed(2)}M`;
3557
- } else if (volume >= 1e3) {
3558
- return `${(volume / 1e3).toFixed(2)}K`;
3559
- }
3560
- return volume.toString();
3561
- }
3562
-
3563
- // src/utils/helpers.ts
3564
- var FMPHelpers = class {
3565
- /**
3566
- * Get all available endpoint categories from the FMP client
3567
- * @param fmp - The FMP client instance
3568
- * @returns Array of endpoint category names
3569
- */
3570
- static getEndpointCategories(fmp) {
3571
- return Object.keys(fmp).filter(
3572
- (key) => typeof fmp[key] === "object" && fmp[key] !== null && key !== "constructor"
3573
- );
3574
- }
3575
- /**
3576
- * Get all methods for a specific endpoint category
3577
- * @param fmp - The FMP client instance
3578
- * @param endpoint - The endpoint category name
3579
- * @returns Array of method names
3580
- */
3581
- static getEndpointMethods(fmp, endpoint) {
3582
- const endpointObj = fmp[endpoint];
3583
- if (!endpointObj || typeof endpointObj !== "object") {
3584
- return [];
3585
- }
3586
- return Object.getOwnPropertyNames(endpointObj).filter(
3587
- (name) => typeof endpointObj[name] === "function" && name !== "constructor"
3588
- );
3589
- }
3590
- /**
3591
- * Get all available methods across all endpoint categories
3592
- * @param fmp - The FMP client instance
3593
- * @returns Object mapping endpoint categories to their methods
3594
- */
3595
- static getAllMethods(fmp) {
3596
- const methods = {};
3597
- const categories = this.getEndpointCategories(fmp);
3598
- categories.forEach((category) => {
3599
- methods[category] = this.getEndpointMethods(fmp, category);
3600
- });
3601
- return methods;
3602
- }
3603
- /**
3604
- * Get a summary of the API structure
3605
- * @param fmp - The FMP client instance
3606
- * @returns Summary object with endpoint and method counts
3607
- */
3608
- static getApiSummary(fmp) {
3609
- const categories = this.getEndpointCategories(fmp);
3610
- const allMethods = this.getAllMethods(fmp);
3611
- const totalMethods = Object.values(allMethods).reduce(
3612
- (sum, methods) => sum + methods.length,
3613
- 0
3614
- );
3615
- const methodCounts = {};
3616
- categories.forEach((category) => {
3617
- methodCounts[category] = allMethods[category]?.length || 0;
3618
- });
3619
- return {
3620
- totalEndpoints: categories.length,
3621
- totalMethods,
3622
- categories,
3623
- methodCounts
3624
- };
3625
- }
3626
- /**
3627
- * Check if a specific method exists on an endpoint
3628
- * @param fmp - The FMP client instance
3629
- * @param endpoint - The endpoint category name
3630
- * @param method - The method name
3631
- * @returns True if the method exists
3632
- */
3633
- static hasMethod(fmp, endpoint, method) {
3634
- const methods = this.getEndpointMethods(fmp, endpoint);
3635
- return methods.includes(method);
3636
- }
3637
- /**
3638
- * Get method signature information (basic introspection)
3639
- * @param fmp - The FMP client instance
3640
- * @param endpoint - The endpoint category name
3641
- * @param method - The method name
3642
- * @returns Method information or null if not found
3643
- */
3644
- static getMethodInfo(fmp, endpoint, method) {
3645
- const endpointObj = fmp[endpoint];
3646
- if (!endpointObj || typeof endpointObj !== "object") {
3647
- return null;
3648
- }
3649
- const methodFn = endpointObj[method];
3650
- if (typeof methodFn !== "function") {
3651
- return null;
3652
- }
3653
- return {
3654
- name: method,
3655
- type: "function",
3656
- async: methodFn.constructor.name === "AsyncFunction"
3657
- };
3658
- }
3659
- };
3660
-
3661
- // src/utils/utils.ts
3662
- var FMPUtils = class {
3663
- /**
3664
- * Format currency values
3665
- * @param value - The numeric value to format
3666
- * @param currency - The currency code (default: USD)
3667
- * @param locale - The locale for formatting (default: en-US)
3668
- * @returns Formatted currency string
3669
- */
3670
- static formatCurrency(value, currency = "USD", locale = "en-US") {
3671
- if (typeof value !== "number" || isNaN(value)) {
3672
- return "N/A";
3673
- }
3674
- try {
3675
- return new Intl.NumberFormat(locale, {
3676
- style: "currency",
3677
- currency,
3678
- minimumFractionDigits: 2,
3679
- maximumFractionDigits: 2
3680
- }).format(value);
3681
- } catch (error) {
3682
- return `${currency} ${value.toFixed(2)}`;
3683
- }
3684
- }
3685
- /**
3686
- * Format percentages
3687
- * @param value - The percentage value (as decimal, e.g., 0.15 for 15%)
3688
- * @param decimals - Number of decimal places (default: 2)
3689
- * @returns Formatted percentage string
3690
- */
3691
- static formatPercentage(value, decimals = 2) {
3692
- if (typeof value !== "number" || isNaN(value)) {
3693
- return "N/A";
3694
- }
3695
- return `${value.toFixed(decimals)}%`;
3696
- }
3697
- /**
3698
- * Format large numbers with abbreviations (K, M, B, T)
3699
- * @param value - The numeric value to format
3700
- * @param decimals - Number of decimal places (default: 1)
3701
- * @returns Formatted number string
3702
- */
3703
- static formatLargeNumber(value, decimals = 1) {
3704
- if (typeof value !== "number" || isNaN(value)) {
3705
- return "N/A";
3706
- }
3707
- const absValue = Math.abs(value);
3708
- const sign = value < 0 ? "-" : "";
3709
- if (absValue >= 1e12) {
3710
- return `${sign}${(absValue / 1e12).toFixed(decimals)}T`;
3711
- } else if (absValue >= 1e9) {
3712
- return `${sign}${(absValue / 1e9).toFixed(decimals)}B`;
3713
- } else if (absValue >= 1e6) {
3714
- return `${sign}${(absValue / 1e6).toFixed(decimals)}M`;
3715
- } else if (absValue >= 1e3) {
3716
- return `${sign}${(absValue / 1e3).toFixed(decimals)}K`;
3717
- } else {
3718
- return `${sign}${absValue.toFixed(decimals)}`;
3719
- }
3720
- }
3721
- /**
3722
- * Convert date string to Date object
3723
- * @param dateString - The date string in YYYY-MM-DD format
3724
- * @returns Date object or null if invalid
3725
- */
3726
- static parseDate(dateString) {
3727
- if (!dateString || typeof dateString !== "string") {
3728
- return null;
3729
- }
3730
- const [year, month, day] = dateString.split("-").map(Number);
3731
- if (isNaN(year) || isNaN(month) || isNaN(day)) {
3732
- return null;
3733
- }
3734
- if (month < 1 || month > 12) {
3735
- return null;
3736
- }
3737
- const date = new Date(Date.UTC(year, month - 1, day));
3738
- if (isNaN(date.getTime())) {
3739
- return null;
3740
- }
3741
- const parsedYear = date.getUTCFullYear();
3742
- const parsedMonth = date.getUTCMonth() + 1;
3743
- const parsedDay = date.getUTCDate();
3744
- if (parsedYear !== year || parsedMonth !== month || parsedDay !== day) {
3745
- return null;
3746
- }
3747
- return date;
3748
- }
3749
- /**
3750
- * Format date to readable string
3751
- * @param date - Date object or date string
3752
- * @param format - Format style ('short', 'long', 'iso')
3753
- * @returns Formatted date string
3754
- */
3755
- static formatDate(date, format = "short") {
3756
- const dateObj = typeof date === "string" ? this.parseDate(date) : date;
3757
- if (!dateObj) {
3758
- return "Invalid Date";
3759
- }
3760
- switch (format) {
3761
- case "long":
3762
- return dateObj.toLocaleDateString("en-US", {
3763
- weekday: "long",
3764
- year: "numeric",
3765
- month: "long",
3766
- day: "numeric"
3767
- });
3768
- case "iso":
3769
- return dateObj.toISOString().split("T")[0];
3770
- case "short":
3771
- default:
3772
- return dateObj.toLocaleDateString("en-US", {
3773
- year: "numeric",
3774
- month: "short",
3775
- day: "numeric"
3776
- });
3777
- }
3778
- }
3779
- /**
3780
- * Calculate working days between two dates (excluding weekends)
3781
- * @param from - Start date
3782
- * @param to - End date
3783
- * @returns Number of working days
3784
- */
3785
- static getWorkingDays(from, to) {
3786
- const startDate = typeof from === "string" ? this.parseDate(from) : from;
3787
- const endDate = typeof to === "string" ? this.parseDate(to) : to;
3788
- if (!startDate || !endDate) {
3789
- return 0;
3790
- }
3791
- let workingDays = 0;
3792
- const currentDate = new Date(startDate);
3793
- const endDateNormalized = new Date(
3794
- Date.UTC(endDate.getUTCFullYear(), endDate.getUTCMonth(), endDate.getUTCDate())
3795
- );
3796
- while (currentDate <= endDateNormalized) {
3797
- const dayOfWeek = currentDate.getUTCDay();
3798
- if (dayOfWeek !== 0 && dayOfWeek !== 6) {
3799
- workingDays++;
3800
- }
3801
- currentDate.setUTCDate(currentDate.getUTCDate() + 1);
3802
- }
3803
- return workingDays;
3804
- }
3805
- /**
3806
- * Calculate percentage change between two values
3807
- * @param oldValue - The original value
3808
- * @param newValue - The new value
3809
- * @param decimals - Number of decimal places (default: 2)
3810
- * @returns Percentage change as a number
3811
- */
3812
- static calculatePercentageChange(oldValue, newValue, decimals = 2) {
3813
- if (typeof oldValue !== "number" || typeof newValue !== "number" || isNaN(oldValue) || isNaN(newValue) || oldValue === 0) {
3814
- return 0;
3815
- }
3816
- const change = (newValue - oldValue) / oldValue * 100;
3817
- return Number(change.toFixed(decimals));
3818
- }
3819
- /**
3820
- * Batch API calls with rate limiting
3821
- * @param calls - Array of async functions to execute
3822
- * @param delayMs - Delay between calls in milliseconds (default: 100)
3823
- * @param maxConcurrent - Maximum concurrent calls (default: 1)
3824
- * @returns Array of results
3825
- */
3826
- static async batchCalls(calls, delayMs = 100, maxConcurrent = 1) {
3827
- const results = [];
3828
- if (maxConcurrent === 1) {
3829
- for (const call of calls) {
3830
- results.push(await call());
3831
- if (delayMs > 0) {
3832
- await new Promise((resolve) => setTimeout(resolve, delayMs));
3833
- }
3834
- }
3835
- } else {
3836
- const chunks = this.chunkArray(calls, maxConcurrent);
3837
- for (const chunk of chunks) {
3838
- const chunkResults = await Promise.all(chunk.map((call) => call()));
3839
- results.push(...chunkResults);
3840
- if (delayMs > 0) {
3841
- await new Promise((resolve) => setTimeout(resolve, delayMs));
3842
- }
3843
- }
3844
- }
3845
- return results;
3846
- }
3847
- /**
3848
- * Split array into chunks
3849
- * @param array - The array to split
3850
- * @param chunkSize - Size of each chunk
3851
- * @returns Array of chunks
3852
- */
3853
- static chunkArray(array, chunkSize) {
3854
- const chunks = [];
3855
- for (let i = 0; i < array.length; i += chunkSize) {
3856
- chunks.push(array.slice(i, i + chunkSize));
3857
- }
3858
- return chunks;
3859
- }
3860
- /**
3861
- * Retry a function with exponential backoff
3862
- * @param fn - The function to retry
3863
- * @param maxRetries - Maximum number of retries (default: 3)
3864
- * @param baseDelay - Base delay in milliseconds (default: 1000)
3865
- * @returns Function result
3866
- */
3867
- static async retryWithBackoff(fn, maxRetries = 3, baseDelay = 1e3) {
3868
- let lastError;
3869
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
3870
- try {
3871
- return await fn();
3872
- } catch (error) {
3873
- lastError = error;
3874
- if (attempt === maxRetries) {
3875
- throw lastError;
3876
- }
3877
- const delay = baseDelay * Math.pow(2, attempt);
3878
- await new Promise((resolve) => setTimeout(resolve, delay));
3879
- }
3880
- }
3881
- throw lastError;
3882
- }
3883
- /**
3884
- * Debounce a function
3885
- * @param func - The function to debounce
3886
- * @param wait - Wait time in milliseconds
3887
- * @returns Debounced function
3888
- */
3889
- static debounce(func, wait) {
3890
- let timeout;
3891
- return (...args) => {
3892
- clearTimeout(timeout);
3893
- timeout = setTimeout(() => func(...args), wait);
3894
- };
3895
- }
3896
- /**
3897
- * Throttle a function
3898
- * @param func - The function to throttle
3899
- * @param limit - Time limit in milliseconds
3900
- * @returns Throttled function
3901
- */
3902
- static throttle(func, limit) {
3903
- let inThrottle;
3904
- return (...args) => {
3905
- if (!inThrottle) {
3906
- func(...args);
3907
- inThrottle = true;
3908
- setTimeout(() => inThrottle = false, limit);
3909
- }
3910
- };
3911
- }
3912
- };
3913
-
3914
- // src/utils/debug.ts
3915
- var _FMPDebug = class _FMPDebug {
3916
- /**
3917
- * Log API calls for debugging (only in development)
3918
- * @param endpoint - The endpoint being called
3919
- * @param params - The parameters passed to the endpoint
3920
- * @param response - The response received
3921
- * @param duration - The duration of the call in milliseconds
3922
- */
3923
- static logApiCall(endpoint, params, response, duration) {
3924
- if (!this.isDevelopment && !this.isDebugEnabled) {
3925
- return;
3926
- }
3927
- const logData = {
3928
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3929
- endpoint,
3930
- params,
3931
- success: response?.success,
3932
- status: response?.status,
3933
- duration: duration ? `${duration}ms` : void 0
3934
- };
3935
- console.log("\u{1F50D} FMP API Call:", logData);
3936
- }
3937
- /**
3938
- * Log API errors for debugging
3939
- * @param endpoint - The endpoint that failed
3940
- * @param params - The parameters that were passed
3941
- * @param error - The error that occurred
3942
- */
3943
- static logApiError(endpoint, params, error) {
3944
- if (!this.isDevelopment && !this.isDebugEnabled) {
3945
- return;
3946
- }
3947
- console.error("\u274C FMP API Error:", {
3948
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3949
- endpoint,
3950
- params,
3951
- error: error?.message || error,
3952
- stack: error?.stack
3953
- });
3954
- }
3955
- /**
3956
- * Get comprehensive API usage statistics
3957
- * @param fmp - The FMP client instance
3958
- * @returns Detailed API statistics
3959
- */
3960
- static getApiStats(fmp) {
3961
- const summary = FMPHelpers.getApiSummary(fmp);
3962
- const estimatedApiCalls = Object.values(summary.methodCounts).reduce(
3963
- (total, count) => total + count * 2,
3964
- // Assume 2 calls per method on average
3965
- 0
3966
- );
3967
- return {
3968
- ...summary,
3969
- estimatedApiCalls
3970
- };
3971
- }
3972
- /**
3973
- * Validate API key format and provide feedback
3974
- * @param apiKey - The API key to validate
3975
- * @returns Validation result with details
3976
- */
3977
- static validateApiKey(apiKey) {
3978
- const length = apiKey?.length || 0;
3979
- const format = apiKey?.match(/^[a-zA-Z0-9]+$/) ? "alphanumeric" : "invalid";
3980
- const isValid = length >= 32 && format === "alphanumeric";
3981
- const suggestions = [];
3982
- if (length < 32) {
3983
- suggestions.push("API key should be at least 32 characters long");
3984
- }
3985
- if (format !== "alphanumeric") {
3986
- suggestions.push("API key should contain only letters and numbers");
3987
- }
3988
- if (!apiKey) {
3989
- suggestions.push("API key is required");
3990
- }
3991
- return {
3992
- isValid,
3993
- length,
3994
- format,
3995
- suggestions
3996
- };
3997
- }
3998
- /**
3999
- * Check API key environment variable
4000
- * @returns Environment check result
4001
- */
4002
- static checkApiKeyEnvironment() {
4003
- const envVarName = "FMP_API_KEY";
4004
- const apiKey = process.env[envVarName];
4005
- const hasEnvVar = !!apiKey;
4006
- const validation = this.validateApiKey(apiKey || "");
4007
- const suggestions = [];
4008
- if (!hasEnvVar) {
4009
- suggestions.push(`Set ${envVarName} environment variable`);
4010
- suggestions.push("Add to your .env file: FMP_API_KEY=your_api_key_here");
4011
- } else if (!validation.isValid) {
4012
- suggestions.push(...validation.suggestions);
4013
- }
4014
- return {
4015
- hasEnvVar,
4016
- envVarName,
4017
- isValid: validation.isValid,
4018
- suggestions
4019
- };
4020
- }
4021
- /**
4022
- * Get performance metrics for API calls
4023
- * @param fmp - The FMP client instance
4024
- * @returns Performance information
4025
- */
4026
- static getPerformanceInfo() {
4027
- return {
4028
- nodeVersion: process.version,
4029
- platform: process.platform,
4030
- memoryUsage: process.memoryUsage(),
4031
- uptime: process.uptime()
4032
- };
4033
- }
4034
- /**
4035
- * Create a debug configuration object
4036
- * @param fmp - The FMP client instance
4037
- * @returns Debug configuration
4038
- */
4039
- static createDebugConfig(fmp) {
4040
- return {
4041
- apiStats: this.getApiStats(fmp),
4042
- envCheck: this.checkApiKeyEnvironment(),
4043
- performance: this.getPerformanceInfo(),
4044
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
4045
- };
4046
- }
4047
- /**
4048
- * Print debug information to console
4049
- * @param fmp - The FMP client instance
4050
- */
4051
- static printDebugInfo(fmp) {
4052
- if (!this.isDevelopment && !this.isDebugEnabled) {
4053
- return;
4054
- }
4055
- const config = this.createDebugConfig(fmp);
4056
- console.log("\u{1F527} FMP Debug Information:");
4057
- console.log("\u{1F4CA} API Stats:", config.apiStats);
4058
- console.log("\u{1F511} Environment Check:", config.envCheck);
4059
- console.log("\u26A1 Performance:", config.performance);
4060
- console.log("\u{1F552} Timestamp:", config.timestamp);
4061
- }
4062
- /**
4063
- * Enable debug mode programmatically
4064
- */
4065
- static enableDebugMode() {
4066
- process.env.FMP_DEBUG = "true";
4067
- this.isDebugEnabled = true;
4068
- console.log("\u{1F527} FMP Debug mode enabled");
4069
- }
4070
- /**
4071
- * Disable debug mode programmatically
4072
- */
4073
- static disableDebugMode() {
4074
- process.env.FMP_DEBUG = "false";
4075
- this.isDebugEnabled = false;
4076
- console.log("\u{1F527} FMP Debug mode disabled");
4077
- }
4078
- /**
4079
- * Check if debug mode is enabled
4080
- * @returns True if debug mode is enabled
4081
- */
4082
- static isDebugMode() {
4083
- return this.isDevelopment || this.isDebugEnabled;
4084
- }
4085
- /**
4086
- * Create a debug wrapper for API calls
4087
- * @param fmp - The FMP client instance
4088
- * @returns FMP client with debug logging
4089
- */
4090
- static createDebugWrapper(fmp) {
4091
- if (!this.isDebugMode()) {
4092
- return fmp;
4093
- }
4094
- return new Proxy(fmp, {
4095
- get(target, prop) {
4096
- const value = target[prop];
4097
- if (typeof value === "object" && value !== null) {
4098
- return new Proxy(value, {
4099
- get(endpointTarget, methodName) {
4100
- const method = endpointTarget[methodName];
4101
- if (typeof method === "function") {
4102
- return async (...args) => {
4103
- const startTime = Date.now();
4104
- const endpoint = `${String(prop)}.${String(methodName)}`;
4105
- let params;
4106
- if (methodName === "getQuote" && args.length === 1 && typeof args[0] === "string") {
4107
- params = { symbol: args[0] };
4108
- } else if (args.length === 1 && typeof args[0] === "object" && args[0] !== null) {
4109
- params = args[0];
4110
- } else {
4111
- params = args;
4112
- }
4113
- try {
4114
- _FMPDebug.logApiCall(endpoint, params, null);
4115
- const result = await method.apply(
4116
- endpointTarget,
4117
- args
4118
- );
4119
- const duration = Date.now() - startTime;
4120
- _FMPDebug.logApiCall(endpoint, params, result, duration);
4121
- return result;
4122
- } catch (error) {
4123
- _FMPDebug.logApiError(endpoint, params, error);
4124
- throw error;
4125
- }
4126
- };
4127
- }
4128
- return method;
4129
- }
4130
- });
4131
- }
4132
- return value;
4133
- }
4134
- });
4135
- }
4136
- };
4137
- _FMPDebug.isDevelopment = process.env.NODE_ENV === "development";
4138
- _FMPDebug.isDebugEnabled = process.env.FMP_DEBUG === "true";
4139
- var FMPDebug = _FMPDebug;
4140
-
4141
- exports.COUNTRIES = COUNTRIES;
4142
- exports.CalendarEndpoints = CalendarEndpoints;
4143
- exports.CompanyEndpoints = CompanyEndpoints;
4144
- exports.DEFAULT_LIMIT = DEFAULT_LIMIT;
4145
- exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
4146
- exports.ERROR_MESSAGES = ERROR_MESSAGES;
4147
- exports.ETFEndpoints = ETFEndpoints;
4148
- exports.EXCHANGES = EXCHANGES;
4149
- exports.EconomicEndpoints = EconomicEndpoints;
4150
- exports.Exchange = Exchange;
4151
- exports.FMP = FMP;
4152
- exports.FMPClient = FMPClient;
4153
- exports.FMPDebug = FMPDebug;
4154
- exports.FMPHelpers = FMPHelpers;
4155
- exports.FMPUtils = FMPUtils;
4156
- exports.FMPValidation = FMPValidation;
4157
- exports.FinancialEndpoints = FinancialEndpoints;
4158
- exports.HTTP_STATUS = HTTP_STATUS;
4159
- exports.InsiderEndpoints = InsiderEndpoints;
4160
- exports.InstitutionalEndpoints = InstitutionalEndpoints;
4161
- exports.ListEndpoints = ListEndpoints;
4162
- exports.MAX_LIMIT = MAX_LIMIT;
4163
- exports.MarketEndpoints = MarketEndpoints;
4164
- exports.MutualFundEndpoints = MutualFundEndpoints;
4165
- exports.PERIODS = PERIODS;
4166
- exports.Period = Period;
4167
- exports.QuoteEndpoints = QuoteEndpoints;
4168
- exports.SECEndpoints = SECEndpoints;
4169
- exports.SECTORS = SECTORS;
4170
- exports.SenateHouseEndpoints = SenateHouseEndpoints;
4171
- exports.StockEndpoints = StockEndpoints;
4172
- exports.TransactionType = TransactionType;
4173
- exports.formatCurrency = formatCurrency;
4174
- exports.formatDate = formatDate;
4175
- exports.formatLargeNumber = formatLargeNumber;
4176
- exports.formatNumber = formatNumber;
4177
- exports.formatPercentage = formatPercentage;
4178
- exports.formatReadableDate = formatReadableDate;
4179
- exports.formatTimestamp = formatTimestamp;
4180
- exports.formatVolume = formatVolume;
4181
- //# sourceMappingURL=index.js.map
4182
- //# sourceMappingURL=index.js.map
1
+ 'use strict';var C=require('axios');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var C__default=/*#__PURE__*/_interopDefault(C);function T(i){return Array.isArray(i)&&i.length===1?i[0]:i}function F(i){return Array.isArray(i)?i:i??[]}function v(i){return i==null?{}:Array.isArray(i)&&i.length===0?{}:i}var l=class{constructor(e){if(!e.apiKey)throw new Error("API key is required for FMPClient");this.apiKey=e.apiKey,this.v3Client=C__default.default.create({baseURL:"https://financialmodelingprep.com/api/v3",timeout:e.timeout||1e4,headers:{"Content-Type":"application/json"}}),this.v4Client=C__default.default.create({baseURL:"https://financialmodelingprep.com/api/v4",timeout:e.timeout||1e4,headers:{"Content-Type":"application/json"}}),this.stableClient=C__default.default.create({baseURL:"https://financialmodelingprep.com/stable",timeout:e.timeout||1e4,headers:{"Content-Type":"application/json"}}),[this.v3Client,this.v4Client,this.stableClient].forEach(t=>{t.interceptors.request.use(r=>(r.params={...r.params,apikey:this.apiKey},r));});}async get(e,t="v3",r){let n=this.getClientForVersion(t);try{let s=await n.get(e,{params:r}),o=s.data;return (Array.isArray(o)||o==null)&&(o=F(o)),{success:!0,data:o,error:null,status:s.status}}catch(s){return {success:false,data:null,error:s.message||"Unknown error occurred",status:s.response?.status||500}}}async getSingle(e,t="v3",r){let n=this.getClientForVersion(t);try{let s=await n.get(e,{params:r});return {success:!0,data:v(T(s.data)),error:null,status:s.status}}catch(s){return {success:false,data:null,error:s.message||"Unknown error occurred",status:s.response?.status||500}}}getClientForVersion(e){switch(e){case "v3":return this.v3Client;case "v4":return this.v4Client;case "stable":return this.stableClient;default:return this.v3Client}}};var c=class{static isValidSymbol(e){return !e||typeof e!="string"?false:/^[A-Z]{1,5}$/.test(e)}static isValidCryptoSymbol(e){return !e||typeof e!="string"?false:/^[A-Z]{2,10}(USD|EUR|GBP|JPY|CAD|AUD|CHF|CNY)$/.test(e)}static isValidForexPair(e){return !e||typeof e!="string"?false:/^[A-Z]{3}[A-Z]{3}$/.test(e)}static isValidDate(e){if(!e||typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))return false;let r=new Date(e);return !isNaN(r.getTime())&&r.toISOString().split("T")[0]===e}static isValidDateRange(e,t){if(!this.isValidDate(e)||!this.isValidDate(t))return false;let r=new Date(e),n=new Date(t);return r<=n}static isValidResponse(e){return !!(e&&typeof e=="object"&&typeof e.success=="boolean")}static isValidApiKey(e){return !e||typeof e!="string"?false:/^[a-zA-Z0-9]{32,}$/.test(e)}static isValidPeriod(e){return !e||typeof e!="string"?false:["annual","quarter","fy"].includes(e.toLowerCase())}static isValidLimit(e){return typeof e=="number"&&Number.isInteger(e)&&e>0&&e<=1e3}static validateQuoteParams(e){let t=[];return e?(e.symbol?!this.isValidSymbol(e.symbol)&&!this.isValidCryptoSymbol(e.symbol)&&!this.isValidForexPair(e.symbol)&&t.push("Invalid symbol format"):t.push("Symbol is required"),e.from&&!this.isValidDate(e.from)&&t.push("Invalid from date format (expected YYYY-MM-DD)"),e.to&&!this.isValidDate(e.to)&&t.push("Invalid to date format (expected YYYY-MM-DD)"),e.from&&e.to&&!this.isValidDateRange(e.from,e.to)&&t.push("From date must be before or equal to to date"),t):(t.push("Parameters object is required"),t)}static validateFinancialParams(e){let t=[];return e?(e.symbol?this.isValidSymbol(e.symbol)||t.push("Invalid symbol format"):t.push("Symbol is required"),e.period&&!this.isValidPeriod(e.period)&&t.push('Invalid period (must be "annual", "quarter", or "FY")'),e.limit&&!this.isValidLimit(e.limit)&&t.push("Invalid limit (must be a positive integer <= 1000)"),t):(t.push("Parameters object is required"),t)}static validateDateRangeParams(e){let t=[];return e?(e.from&&!this.isValidDate(e.from)&&t.push("Invalid from date format (expected YYYY-MM-DD)"),e.to&&!this.isValidDate(e.to)&&t.push("Invalid to date format (expected YYYY-MM-DD)"),e.from&&e.to&&!this.isValidDateRange(e.from,e.to)&&t.push("From date must be before or equal to to date"),t):(t.push("Parameters object is required"),t)}static throwIfInvalid(e,t="Validation"){if(e.length>0)throw new Error(`${t} failed: ${e.join(", ")}`)}};var m=class{constructor(e){this.client=e;}async getMarketCap(e){return this.client.getSingle(`/market-capitalization/${e}`,"v3")}async getStockSplits(e){return this.client.get(`/historical-price-full/stock_split/${e}`,"v3")}async getDividendHistory(e){return this.client.getSingle(`/historical-price-full/stock_dividend/${e}`,"v3")}async getRealTimePrice(e){let t=`stock/real-time-price/${e.join(",")}`,r=await this.client.get(t,"v3");if(r.success&&r.data&&!Array.isArray(r.data)){let s=r.data;if(typeof s=="object"&&s!==null&&"companiesPriceList"in s&&Array.isArray(s.companiesPriceList)){let o=s.companiesPriceList.filter(a=>a&&a.symbol);if(o.length>0)return {...r,data:o}}if(typeof s=="object"&&s!==null&&"stockList"in s&&Array.isArray(s.stockList)){let o=s.stockList.filter(a=>a&&a.symbol);if(o.length>0)return {...r,data:o}}return s.symbol?{...r,data:[s]}:(e.length===1&&console.warn(`No real-time price data found for symbol: ${e[0]}`),{...r,data:[]})}let n=r.data.filter(s=>s&&s.symbol);return {...r,data:n}}async getRealTimePriceForMultipleStocks(e){let t=`stock/full/real-time-price/${e.join(",")}`,r=await this.client.get(t,"v3");if(r.success&&r.data&&!Array.isArray(r.data)){let s=r.data;if(typeof s=="object"&&s!==null&&"companiesPriceList"in s&&Array.isArray(s.companiesPriceList)){let o=s.companiesPriceList.filter(a=>a&&a.symbol);if(o.length>0)return {...r,data:o}}if(typeof s=="object"&&s!==null&&"stockList"in s&&Array.isArray(s.stockList)){let o=s.stockList.filter(a=>a&&a.symbol);if(o.length>0)return {...r,data:o}}return s.symbol?{...r,data:[s]}:(e.length===1&&console.warn(`No full real-time price data found for symbol: ${e[0]}`),{...r,data:[]})}let n=r.data.filter(s=>s&&s.symbol);return {...r,data:n}}};var p=class{constructor(e){this.client=e;}async getIncomeStatement(e){let{symbol:t,period:r="annual",limit:n=5}=e;return this.client.get(`/income-statement/${t}?period=${r}&limit=${n}`,"v3")}async getBalanceSheet(e){let{symbol:t,period:r="annual",limit:n=5}=e;return this.client.get(`/balance-sheet-statement/${t}?period=${r}&limit=${n}`,"v3")}async getCashFlowStatement(e){let{symbol:t,period:r="annual",limit:n=5}=e;return this.client.get(`/cash-flow-statement/${t}?period=${r}&limit=${n}`,"v3")}async getKeyMetrics(e){let{symbol:t,period:r="annual",limit:n=5}=e;return this.client.get(`/key-metrics/${t}?period=${r}&limit=${n}`,"v3")}async getFinancialRatios(e){let{symbol:t,period:r="annual",limit:n=5}=e;return this.client.get(`/ratios/${t}?period=${r}&limit=${n}`,"v3")}async getEnterpriseValue(e){let{symbol:t,period:r="annual",limit:n=5}=e;return this.client.get(`/enterprise-value/${t}?period=${r}&limit=${n}`,"v3")}async getCashflowGrowth(e){let{symbol:t,period:r="annual",limit:n=5}=e;return this.client.get(`/cash-flow-statement-growth/${t}?period=${r}&limit=${n}`,"v3")}async getIncomeGrowth(e){let{symbol:t,period:r="annual",limit:n=5}=e;return this.client.get(`/income-statement-growth/${t}?period=${r}&limit=${n}`,"v3")}async getBalanceSheetGrowth(e){let{symbol:t,period:r="annual",limit:n=5}=e;return this.client.get(`/balance-sheet-statement-growth/${t}?period=${r}&limit=${n}`,"v3")}async getFinancialGrowth(e){let{symbol:t,period:r="annual",limit:n=5}=e;return this.client.get(`/financial-growth/${t}?period=${r}&limit=${n}`,"v3")}async getEarningsHistorical(e){let{symbol:t,limit:r=5}=e;return this.client.get(`/historical/earning_calendar/${t}?limit=${r}`,"v3")}async getEarningsSurprises(e){return this.client.get(`/earnings-surprises/${e}`,"v3")}};var u=class{constructor(e){this.client=e;}async getHoldingDates(e){return this.client.get("/etf-holdings/portfolio-date","v4",{symbol:e})}async getHoldings(e){let{symbol:t,date:r}=e,n={};return t&&(n.symbol=t),r&&(n.date=r),this.client.get("/etf-holdings","v4",n)}async getHolder(e){return this.client.get(`/etf-holder/${e}`,"v3")}async getProfile(e){return this.client.getSingle("/etf-info","v4",{symbol:e})}async getSectorWeighting(e){return this.client.get(`/etf-sector-weightings/${e}`,"v3")}async getCountryWeighting(e){return this.client.get(`/etf-country-weightings/${e}`,"v3")}async getStockExposure(e){return this.client.get(`/etf-stock-exposure/${e}`,"v3")}};var g=class{constructor(e){this.client=e;}async getTreasuryRates(e){let{from:t,to:r}=e,n={};return t&&(n.from=t),r&&(n.to=r),this.client.get("/treasury","v4",n)}async getEconomicIndicators(e){let{name:t,from:r,to:n}=e,s={name:t};return r&&(s.from=r),n&&(s.to=n),this.client.get("/economic","v4",s)}};var d=class{constructor(e){this.client=e;}async getMarketHours(){return this.client.get("/market-hours","v3")}async getMarketPerformance(){return this.client.get("/market-performance","v3")}async getGainers(){return this.client.get("/stock_market/gainers","v3")}async getLosers(){return this.client.get("/stock_market/losers","v3")}async getMostActive(){return this.client.get("/stock_market/actives","v3")}async getSectorPerformance(){return this.client.get("/sector-performance","v3")}async getMarketIndex(){return this.client.get("/quotes/index","v3")}};var f=class{constructor(e){this.client=e;}async getStockList(){return this.client.get("/stock/list")}async getETFList(){return this.client.get("/etf/list")}async getCryptoList(){return this.client.get("/symbol/available-cryptocurrencies")}async getForexList(){return this.client.get("/symbol/available-forex-currency-pairs")}async getAvailableIndexes(){return this.client.get("/symbol/available-indexes")}};var y=class{constructor(e){this.client=e;}async getEarningsCalendar(e={}){let{from:t,to:r}=e,n={};return t&&(n.from=t),r&&(n.to=r),this.client.get("/earning_calendar","v3",n)}async getEarningsConfirmed(e={}){let{from:t,to:r}=e,n={};return t&&(n.from=t),r&&(n.to=r),this.client.get("/earning-calendar-confirmed","v4",n)}async getDividendsCalendar(e={}){let{from:t,to:r}=e,n={};return t&&(n.from=t),r&&(n.to=r),this.client.get("/stock_dividend_calendar","v3",n)}async getEconomicsCalendar(e={}){let{from:t,to:r}=e,n={};return t&&(n.from=t),r&&(n.to=r),this.client.get("/economic_calendar","v3",n)}async getIPOCalendar(e={}){let{from:t,to:r}=e,n={};return t&&(n.from=t),r&&(n.to=r),this.client.get("/ipo_calendar","v3",n)}async getSplitsCalendar(e={}){let{from:t,to:r}=e,n={};return t&&(n.from=t),r&&(n.to=r),this.client.get("/stock_split_calendar","v3",n)}};var P=class{constructor(e){this.client=e;}async getCompanyProfile(e){return this.client.getSingle(`/profile/${e}`,"v3")}async getExecutiveCompensation(e){return this.client.get("/governance/executive_compensation","v4",{symbol:e})}async getCompanyNotes(e){return this.client.get("/company-notes","v4",{symbol:e})}async getHistoricalEmployeeCount(e){return this.client.get("/historical/employee_count","v4",{symbol:e})}async getSharesFloat(e){return this.client.getSingle("/shares_float","v4",{symbol:e})}async getHistoricalSharesFloat(e){return this.client.get("/historical/shares_float","v4",{symbol:e})}async getEarningsCallTranscript(e){let{symbol:t,year:r,quarter:n}=e;return this.client.getSingle(`/earning_call_transcript/${t}`,"v3",{year:r,quarter:n})}async getCompanyTranscriptData(e){return this.client.getSingle("/earning_call_transcript","v4",{symbol:e})}};var R=class{constructor(e){this.client=e;}async getQuote(e){return this.client.getSingle(`/quote/${e}`,"v3")}async getHistoricalPrice(e){let{symbol:t,from:r,to:n}=e,s={};return r&&(s.from=r),n&&(s.to=n),this.client.getSingle(`/historical-price-full/${t}`,"v3",s)}async getQuotes(e){let t=e.join(",");return this.client.get(`/quote/${t}`,"v3")}async getIntraday(e){let{symbol:t,interval:r,from:n,to:s}=e,o={};return n&&(o.from=n),s&&(o.to=s),this.client.get(`/historical-chart/${r}/${t}`,"v3",o)}};var h=class{constructor(e){this.client=e;}async getSenateTrading(e){let{symbol:t}=e;return this.client.get("/senate-trading","v4",{symbol:t})}async getSenateTradingRSSFeed(e){let{page:t}=e;return this.client.get("/senate-trading-rss-feed","v4",{page:t})}async getSenateTradingByName(e){let{name:t}=e;return this.client.get("/senate-trades-by-name","stable",{name:t})}async getHouseTrading(e){let{symbol:t}=e;return this.client.get("/senate-disclosure","v4",{symbol:t})}async getHouseTradingRSSFeed(e){let{page:t}=e;return this.client.get("/senate-disclosure-rss-feed","v4",{page:t})}async getHouseTradingByName(e){let{name:t}=e;return this.client.get("/house-trades-by-name","stable",{name:t})}};var I=class{constructor(e){this.client=e;}async getForm13F(e){let{cik:t,date:r}=e,n={};return r&&(n.date=r),this.client.get(`/form-thirteen/${t}`,"v3",n)}async getForm13FDates(e){let{cik:t}=e;return this.client.get(`/form-thirteen-date/${t}`,"v3")}async getInstitutionalHolders(e){let{symbol:t}=e;return this.client.get(`/institutional-holder/${t}`,"v3")}};var S=class{constructor(e){this.client=e;}async getInsiderTradingRSS(e){let{page:t=0}=e;return this.client.get("/insider-trading-rss-feed","v4",{page:t})}async searchInsiderTrading(e){let{symbol:t,reportingCik:r,companyCik:n,transactionType:s,page:o=0}=e,a={page:o};return t&&(a.symbol=t),r&&(a.reportingCik=r),n&&(a.companyCik=n),s&&(a.transactionType=s),this.client.get("/insider-trading","v4",a)}async getTransactionTypes(){return this.client.get("/insider-trading-transaction-type","v4")}async getInsidersBySymbol(e){let{symbol:t}=e;return this.client.get("/insider-roaster","v4",{symbol:t})}async getInsiderTradeStatistics(e){let{symbol:t}=e;return this.client.get("/insider-roaster-statistic","v4",{symbol:t})}async getCikMapper(e){let{page:t=0}=e;return this.client.get("/mapper-cik-name","v4",{page:t})}async getCikMapperByName(e){let{name:t,page:r=0}=e;return this.client.get("/mapper-cik-name","v4",{name:t,page:r})}async getCikMapperBySymbol(e){let{symbol:t}=e;return this.client.getSingle(`/mapper-cik-company/${t}`,"v4")}async getBeneficialOwnership(e){let{symbol:t}=e;return this.client.get("/insider/ownership/acquisition_of_beneficial_ownership","v4",{symbol:t})}async getFailToDeliver(e){let{symbol:t,page:r=0}=e;return this.client.get("/fail_to_deliver","v4",{symbol:t,page:r})}async getInsiderTradesBySymbol(e,t=0){return this.searchInsiderTrading({symbol:e,page:t})}async getInsiderTradesByType(e,t=0){return this.searchInsiderTrading({transactionType:e,page:t})}async getInsiderTradesByReportingCik(e,t=0){return this.searchInsiderTrading({reportingCik:e,page:t})}async getInsiderTradesByCompanyCik(e,t=0){return this.searchInsiderTrading({companyCik:e,page:t})}};var A=class{constructor(e){this.client=e;}async getRSSFeed(e){return this.client.get("/rss_feed","v4",e)}async getRSSFeedAll(e){return this.client.get("/rss_feed_all","v4",e)}async getRSSFeedV3(e){return this.client.get("/rss_feed","v3",e)}async getRSSFeed8K(e){return this.client.get("/rss_feed_8k","v4",e)}async getSECFilings({symbol:e,params:t}){return this.client.get(`/sec_filings/${e}`,"v3",t)}async getIndividualIndustryClassification(e){return this.client.getSingle("/standard_industrial_classification","v4",e)}async getAllIndustryClassifications(){return this.client.get("/standard_industrial_classification/all","v4")}async getIndustryClassificationCodes(e){return this.client.get("/standard_industrial_classification_list","v4",e)}};var b=class{constructor(e){this.client=e;}async getHolders(e){return this.client.get(`/mutual-fund-holder/${e}`,"v3")}};var E=class{constructor(e={}){let t=e.apiKey||process.env.FMP_API_KEY;if(!t)throw new Error("FMP API key is required. Please provide it in the config or set the FMP_API_KEY environment variable.");if(!c.isValidApiKey(t))throw new Error("Invalid API key format");let r=new l({...e,apiKey:t});this.stock=new m(r),this.financial=new p(r),this.etf=new u(r),this.economic=new g(r),this.market=new d(r),this.list=new f(r),this.calendar=new y(r),this.company=new P(r),this.quote=new R(r),this.senateHouse=new h(r),this.institutional=new I(r),this.insider=new S(r),this.sec=new A(r),this.mutualFund=new b(r);}getClient(){return this.stock.client}};function k(i,e="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:e}).format(i)}function M(i,e=2){return `${i.toFixed(e)}%`}function x(i){return i>=1e12?`${(i/1e12).toFixed(2)}T`:i>=1e9?`${(i/1e9).toFixed(2)}B`:i>=1e6?`${(i/1e6).toFixed(2)}M`:i>=1e3?`${(i/1e3).toFixed(2)}K`:i.toString()}function D(i){return (typeof i=="string"?new Date(i):i).toISOString().split("T")[0]}function w(i){return i>=1e9?`${(i/1e9).toFixed(2)}B`:i>=1e6?`${(i/1e6).toFixed(2)}M`:i>=1e3?`${(i/1e3).toFixed(2)}K`:i.toString()}var L=1e4,_=100,$=1e3,H={ANNUAL:"annual",QUARTER:"quarter"},N={NYSE:"NYSE",NASDAQ:"NASDAQ",AMEX:"AMEX",TSX:"TSX",LSE:"LSE",ASX:"ASX",NSE:"NSE",BSE:"BSE"},q={TECHNOLOGY:"Technology",HEALTHCARE:"Healthcare",FINANCIAL:"Financial",CONSUMER_DISCRETIONARY:"Consumer Discretionary",CONSUMER_STAPLES:"Consumer Staples",INDUSTRIALS:"Industrials",ENERGY:"Energy",MATERIALS:"Materials",UTILITIES:"Utilities",REAL_ESTATE:"Real Estate",COMMUNICATION_SERVICES:"Communication Services"};
2
+ exports.CalendarEndpoints=y;exports.CompanyEndpoints=P;exports.DEFAULT_LIMIT=_;exports.DEFAULT_TIMEOUT=L;exports.ETFEndpoints=u;exports.EXCHANGES=N;exports.EconomicEndpoints=g;exports.FMP=E;exports.FMPClient=l;exports.FMPValidation=c;exports.FinancialEndpoints=p;exports.InsiderEndpoints=S;exports.InstitutionalEndpoints=I;exports.ListEndpoints=f;exports.MAX_LIMIT=$;exports.MarketEndpoints=d;exports.MutualFundEndpoints=b;exports.PERIODS=H;exports.QuoteEndpoints=R;exports.SECEndpoints=A;exports.SECTORS=q;exports.SenateHouseEndpoints=h;exports.StockEndpoints=m;exports.formatCurrency=k;exports.formatDate=D;exports.formatLargeNumber=x;exports.formatPercentage=M;exports.formatVolume=w;