@fin.cx/opendata 3.0.0 → 3.2.0

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.
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@fin.cx/opendata',
6
- version: '3.0.0',
6
+ version: '3.2.0',
7
7
  description: 'A comprehensive TypeScript library for accessing business data and real-time financial information. Features include German company data management with MongoDB integration, JSONL bulk processing, automated Handelsregister interactions, and real-time stock market data from multiple providers.'
8
8
  }
@@ -0,0 +1,296 @@
1
+ import * as plugins from '../plugins.js';
2
+
3
+ /**
4
+ * Base provider entry for tracking provider state
5
+ */
6
+ export interface IBaseProviderEntry<TProvider> {
7
+ provider: TProvider;
8
+ config: IBaseProviderConfig;
9
+ lastError?: Error;
10
+ lastErrorTime?: Date;
11
+ successCount: number;
12
+ errorCount: number;
13
+ }
14
+
15
+ /**
16
+ * Base provider configuration
17
+ */
18
+ export interface IBaseProviderConfig {
19
+ enabled: boolean;
20
+ priority: number;
21
+ timeout?: number;
22
+ retryAttempts?: number;
23
+ retryDelay?: number;
24
+ cacheTTL?: number;
25
+ }
26
+
27
+ /**
28
+ * Base provider interface
29
+ */
30
+ export interface IBaseProvider {
31
+ name: string;
32
+ priority: number;
33
+ isAvailable(): Promise<boolean>;
34
+ readonly requiresAuth: boolean;
35
+ readonly rateLimit?: {
36
+ requestsPerMinute: number;
37
+ requestsPerDay?: number;
38
+ };
39
+ }
40
+
41
+ /**
42
+ * Cache entry for any data type
43
+ */
44
+ export interface IBaseCacheEntry<TData> {
45
+ data: TData;
46
+ timestamp: Date;
47
+ ttl: number;
48
+ }
49
+
50
+ /**
51
+ * Base service for managing data providers with caching
52
+ * Shared logic extracted from StockPriceService and FundamentalsService
53
+ */
54
+ export abstract class BaseProviderService<TProvider extends IBaseProvider, TData> {
55
+ protected providers = new Map<string, IBaseProviderEntry<TProvider>>();
56
+ protected cache = new Map<string, IBaseCacheEntry<TData>>();
57
+ protected logger = console;
58
+
59
+ protected cacheConfig = {
60
+ ttl: 60000, // Default 60 seconds
61
+ maxEntries: 10000
62
+ };
63
+
64
+ constructor(cacheConfig?: { ttl?: number; maxEntries?: number }) {
65
+ if (cacheConfig) {
66
+ this.cacheConfig = { ...this.cacheConfig, ...cacheConfig };
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Register a provider
72
+ */
73
+ public register(provider: TProvider, config?: Partial<IBaseProviderConfig>): void {
74
+ const defaultConfig: IBaseProviderConfig = {
75
+ enabled: true,
76
+ priority: provider.priority,
77
+ timeout: 30000,
78
+ retryAttempts: 2,
79
+ retryDelay: 1000,
80
+ cacheTTL: this.cacheConfig.ttl
81
+ };
82
+
83
+ const mergedConfig = { ...defaultConfig, ...config };
84
+
85
+ this.providers.set(provider.name, {
86
+ provider,
87
+ config: mergedConfig,
88
+ successCount: 0,
89
+ errorCount: 0
90
+ });
91
+
92
+ console.log(`Registered provider: ${provider.name}`);
93
+ }
94
+
95
+ /**
96
+ * Unregister a provider
97
+ */
98
+ public unregister(providerName: string): void {
99
+ this.providers.delete(providerName);
100
+ console.log(`Unregistered provider: ${providerName}`);
101
+ }
102
+
103
+ /**
104
+ * Get a specific provider by name
105
+ */
106
+ public getProvider(name: string): TProvider | undefined {
107
+ return this.providers.get(name)?.provider;
108
+ }
109
+
110
+ /**
111
+ * Get all registered providers
112
+ */
113
+ public getAllProviders(): TProvider[] {
114
+ return Array.from(this.providers.values()).map(entry => entry.provider);
115
+ }
116
+
117
+ /**
118
+ * Get enabled providers sorted by priority
119
+ */
120
+ public getEnabledProviders(): TProvider[] {
121
+ return Array.from(this.providers.values())
122
+ .filter(entry => entry.config.enabled)
123
+ .sort((a, b) => (b.config.priority || 0) - (a.config.priority || 0))
124
+ .map(entry => entry.provider);
125
+ }
126
+
127
+ /**
128
+ * Check health of all providers
129
+ */
130
+ public async checkProvidersHealth(): Promise<Map<string, boolean>> {
131
+ const health = new Map<string, boolean>();
132
+
133
+ for (const [name, entry] of this.providers) {
134
+ if (!entry.config.enabled) {
135
+ health.set(name, false);
136
+ continue;
137
+ }
138
+
139
+ try {
140
+ const isAvailable = await entry.provider.isAvailable();
141
+ health.set(name, isAvailable);
142
+ } catch (error) {
143
+ health.set(name, false);
144
+ console.error(`Health check failed for ${name}:`, error);
145
+ }
146
+ }
147
+
148
+ return health;
149
+ }
150
+
151
+ /**
152
+ * Get provider statistics
153
+ */
154
+ public getProviderStats(): Map<
155
+ string,
156
+ {
157
+ successCount: number;
158
+ errorCount: number;
159
+ lastError?: string;
160
+ lastErrorTime?: Date;
161
+ }
162
+ > {
163
+ const stats = new Map();
164
+
165
+ for (const [name, entry] of this.providers) {
166
+ stats.set(name, {
167
+ successCount: entry.successCount,
168
+ errorCount: entry.errorCount,
169
+ lastError: entry.lastError?.message,
170
+ lastErrorTime: entry.lastErrorTime
171
+ });
172
+ }
173
+
174
+ return stats;
175
+ }
176
+
177
+ /**
178
+ * Clear all cached data
179
+ */
180
+ public clearCache(): void {
181
+ this.cache.clear();
182
+ console.log('Cache cleared');
183
+ }
184
+
185
+ /**
186
+ * Set cache TTL
187
+ */
188
+ public setCacheTTL(ttl: number): void {
189
+ this.cacheConfig.ttl = ttl;
190
+ console.log(`Cache TTL set to ${ttl}ms`);
191
+ }
192
+
193
+ /**
194
+ * Get cache statistics
195
+ */
196
+ public getCacheStats(): {
197
+ size: number;
198
+ maxEntries: number;
199
+ ttl: number;
200
+ } {
201
+ return {
202
+ size: this.cache.size,
203
+ maxEntries: this.cacheConfig.maxEntries,
204
+ ttl: this.cacheConfig.ttl
205
+ };
206
+ }
207
+
208
+ /**
209
+ * Fetch with retry logic
210
+ */
211
+ protected async fetchWithRetry<T>(
212
+ fetchFn: () => Promise<T>,
213
+ config: IBaseProviderConfig
214
+ ): Promise<T> {
215
+ const maxAttempts = config.retryAttempts || 1;
216
+ let lastError: Error | undefined;
217
+
218
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
219
+ try {
220
+ return await fetchFn();
221
+ } catch (error) {
222
+ lastError = error as Error;
223
+
224
+ if (attempt < maxAttempts) {
225
+ const delay = (config.retryDelay || 1000) * attempt;
226
+ console.log(`Retry attempt ${attempt} after ${delay}ms`);
227
+ await plugins.smartdelay.delayFor(delay);
228
+ }
229
+ }
230
+ }
231
+
232
+ throw lastError || new Error('Unknown error during fetch');
233
+ }
234
+
235
+ /**
236
+ * Get from cache if not expired
237
+ */
238
+ protected getFromCache(key: string): TData | null {
239
+ const entry = this.cache.get(key);
240
+
241
+ if (!entry) {
242
+ return null;
243
+ }
244
+
245
+ // Check if cache entry has expired
246
+ const age = Date.now() - entry.timestamp.getTime();
247
+ if (entry.ttl !== Infinity && age > entry.ttl) {
248
+ this.cache.delete(key);
249
+ return null;
250
+ }
251
+
252
+ return entry.data;
253
+ }
254
+
255
+ /**
256
+ * Add to cache with TTL
257
+ */
258
+ protected addToCache(key: string, data: TData, ttl?: number): void {
259
+ // Enforce max entries limit
260
+ if (this.cache.size >= this.cacheConfig.maxEntries) {
261
+ // Remove oldest entry
262
+ const oldestKey = this.cache.keys().next().value;
263
+ if (oldestKey) {
264
+ this.cache.delete(oldestKey);
265
+ }
266
+ }
267
+
268
+ this.cache.set(key, {
269
+ data,
270
+ timestamp: new Date(),
271
+ ttl: ttl || this.cacheConfig.ttl
272
+ });
273
+ }
274
+
275
+ /**
276
+ * Track successful fetch for provider
277
+ */
278
+ protected trackSuccess(providerName: string): void {
279
+ const entry = this.providers.get(providerName);
280
+ if (entry) {
281
+ entry.successCount++;
282
+ }
283
+ }
284
+
285
+ /**
286
+ * Track failed fetch for provider
287
+ */
288
+ protected trackError(providerName: string, error: Error): void {
289
+ const entry = this.providers.get(providerName);
290
+ if (entry) {
291
+ entry.errorCount++;
292
+ entry.lastError = error;
293
+ entry.lastErrorTime = new Date();
294
+ }
295
+ }
296
+ }
@@ -0,0 +1,404 @@
1
+ import * as plugins from '../plugins.js';
2
+ import type {
3
+ IFundamentalsProvider,
4
+ IFundamentalsProviderConfig,
5
+ IFundamentalsProviderRegistry,
6
+ IStockFundamentals,
7
+ IFundamentalsRequest
8
+ } from './interfaces/fundamentals.js';
9
+
10
+ interface IProviderEntry {
11
+ provider: IFundamentalsProvider;
12
+ config: IFundamentalsProviderConfig;
13
+ lastError?: Error;
14
+ lastErrorTime?: Date;
15
+ successCount: number;
16
+ errorCount: number;
17
+ }
18
+
19
+ interface ICacheEntry {
20
+ fundamentals: IStockFundamentals | IStockFundamentals[];
21
+ timestamp: Date;
22
+ ttl: number;
23
+ }
24
+
25
+ /**
26
+ * Service for managing fundamental data providers and caching
27
+ * Parallel to StockPriceService but for fundamental data instead of prices
28
+ */
29
+ export class FundamentalsService implements IFundamentalsProviderRegistry {
30
+ private providers = new Map<string, IProviderEntry>();
31
+ private cache = new Map<string, ICacheEntry>();
32
+ private logger = console;
33
+
34
+ private cacheConfig = {
35
+ ttl: 90 * 24 * 60 * 60 * 1000, // 90 days default (fundamentals change quarterly)
36
+ maxEntries: 10000
37
+ };
38
+
39
+ constructor(cacheConfig?: { ttl?: number; maxEntries?: number }) {
40
+ if (cacheConfig) {
41
+ this.cacheConfig = { ...this.cacheConfig, ...cacheConfig };
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Register a fundamentals provider
47
+ */
48
+ public register(provider: IFundamentalsProvider, config?: IFundamentalsProviderConfig): void {
49
+ const defaultConfig: IFundamentalsProviderConfig = {
50
+ enabled: true,
51
+ priority: provider.priority,
52
+ timeout: 30000, // Longer timeout for fundamental data
53
+ retryAttempts: 2,
54
+ retryDelay: 1000,
55
+ cacheTTL: this.cacheConfig.ttl
56
+ };
57
+
58
+ const mergedConfig = { ...defaultConfig, ...config };
59
+
60
+ this.providers.set(provider.name, {
61
+ provider,
62
+ config: mergedConfig,
63
+ successCount: 0,
64
+ errorCount: 0
65
+ });
66
+
67
+ console.log(`Registered fundamentals provider: ${provider.name}`);
68
+ }
69
+
70
+ /**
71
+ * Unregister a provider
72
+ */
73
+ public unregister(providerName: string): void {
74
+ this.providers.delete(providerName);
75
+ console.log(`Unregistered fundamentals provider: ${providerName}`);
76
+ }
77
+
78
+ /**
79
+ * Get a specific provider by name
80
+ */
81
+ public getProvider(name: string): IFundamentalsProvider | undefined {
82
+ return this.providers.get(name)?.provider;
83
+ }
84
+
85
+ /**
86
+ * Get all registered providers
87
+ */
88
+ public getAllProviders(): IFundamentalsProvider[] {
89
+ return Array.from(this.providers.values()).map(entry => entry.provider);
90
+ }
91
+
92
+ /**
93
+ * Get enabled providers sorted by priority
94
+ */
95
+ public getEnabledProviders(): IFundamentalsProvider[] {
96
+ return Array.from(this.providers.values())
97
+ .filter(entry => entry.config.enabled)
98
+ .sort((a, b) => (b.config.priority || 0) - (a.config.priority || 0))
99
+ .map(entry => entry.provider);
100
+ }
101
+
102
+ /**
103
+ * Get fundamental data for a single ticker
104
+ */
105
+ public async getFundamentals(ticker: string): Promise<IStockFundamentals> {
106
+ const result = await this.getData({
107
+ type: 'fundamentals-current',
108
+ ticker
109
+ });
110
+ return result as IStockFundamentals;
111
+ }
112
+
113
+ /**
114
+ * Get fundamental data for multiple tickers
115
+ */
116
+ public async getBatchFundamentals(tickers: string[]): Promise<IStockFundamentals[]> {
117
+ const result = await this.getData({
118
+ type: 'fundamentals-batch',
119
+ tickers
120
+ });
121
+ return result as IStockFundamentals[];
122
+ }
123
+
124
+ /**
125
+ * Unified data fetching method
126
+ */
127
+ public async getData(
128
+ request: IFundamentalsRequest
129
+ ): Promise<IStockFundamentals | IStockFundamentals[]> {
130
+ const cacheKey = this.getCacheKey(request);
131
+ const cached = this.getFromCache(cacheKey);
132
+
133
+ if (cached) {
134
+ console.log(`Cache hit for ${this.getRequestDescription(request)}`);
135
+ return cached;
136
+ }
137
+
138
+ const providers = this.getEnabledProviders();
139
+ if (providers.length === 0) {
140
+ throw new Error('No fundamentals providers available');
141
+ }
142
+
143
+ let lastError: Error | undefined;
144
+
145
+ for (const provider of providers) {
146
+ const entry = this.providers.get(provider.name)!;
147
+
148
+ try {
149
+ const result = await this.fetchWithRetry(
150
+ () => provider.fetchData(request),
151
+ entry.config
152
+ );
153
+
154
+ entry.successCount++;
155
+
156
+ // Use provider-specific cache TTL or default
157
+ const ttl = entry.config.cacheTTL || this.cacheConfig.ttl;
158
+ this.addToCache(cacheKey, result, ttl);
159
+
160
+ console.log(`Successfully fetched ${this.getRequestDescription(request)} from ${provider.name}`);
161
+ return result;
162
+ } catch (error) {
163
+ entry.errorCount++;
164
+ entry.lastError = error as Error;
165
+ entry.lastErrorTime = new Date();
166
+ lastError = error as Error;
167
+
168
+ console.warn(
169
+ `Provider ${provider.name} failed for ${this.getRequestDescription(request)}: ${error.message}`
170
+ );
171
+ }
172
+ }
173
+
174
+ throw new Error(
175
+ `Failed to fetch ${this.getRequestDescription(request)} from all providers. Last error: ${lastError?.message}`
176
+ );
177
+ }
178
+
179
+ /**
180
+ * Enrich fundamentals with calculated metrics using current price
181
+ */
182
+ public async enrichWithPrice(
183
+ fundamentals: IStockFundamentals,
184
+ price: number
185
+ ): Promise<IStockFundamentals> {
186
+ const enriched = { ...fundamentals };
187
+
188
+ // Calculate market cap: price × shares outstanding
189
+ if (fundamentals.sharesOutstanding) {
190
+ enriched.marketCap = price * fundamentals.sharesOutstanding;
191
+ }
192
+
193
+ // Calculate P/E ratio: price / EPS
194
+ if (fundamentals.earningsPerShareDiluted && fundamentals.earningsPerShareDiluted > 0) {
195
+ enriched.priceToEarnings = price / fundamentals.earningsPerShareDiluted;
196
+ }
197
+
198
+ // Calculate price-to-book: market cap / stockholders equity
199
+ if (enriched.marketCap && fundamentals.stockholdersEquity && fundamentals.stockholdersEquity > 0) {
200
+ enriched.priceToBook = enriched.marketCap / fundamentals.stockholdersEquity;
201
+ }
202
+
203
+ return enriched;
204
+ }
205
+
206
+ /**
207
+ * Enrich batch fundamentals with prices
208
+ */
209
+ public async enrichBatchWithPrices(
210
+ fundamentalsList: IStockFundamentals[],
211
+ priceMap: Map<string, number>
212
+ ): Promise<IStockFundamentals[]> {
213
+ return Promise.all(
214
+ fundamentalsList.map(fundamentals => {
215
+ const price = priceMap.get(fundamentals.ticker);
216
+ if (price) {
217
+ return this.enrichWithPrice(fundamentals, price);
218
+ }
219
+ return Promise.resolve(fundamentals);
220
+ })
221
+ );
222
+ }
223
+
224
+ /**
225
+ * Check health of all providers
226
+ */
227
+ public async checkProvidersHealth(): Promise<Map<string, boolean>> {
228
+ const health = new Map<string, boolean>();
229
+
230
+ for (const [name, entry] of this.providers) {
231
+ if (!entry.config.enabled) {
232
+ health.set(name, false);
233
+ continue;
234
+ }
235
+
236
+ try {
237
+ const isAvailable = await entry.provider.isAvailable();
238
+ health.set(name, isAvailable);
239
+ } catch (error) {
240
+ health.set(name, false);
241
+ console.error(`Health check failed for ${name}:`, error);
242
+ }
243
+ }
244
+
245
+ return health;
246
+ }
247
+
248
+ /**
249
+ * Get provider statistics
250
+ */
251
+ public getProviderStats(): Map<
252
+ string,
253
+ {
254
+ successCount: number;
255
+ errorCount: number;
256
+ lastError?: string;
257
+ lastErrorTime?: Date;
258
+ }
259
+ > {
260
+ const stats = new Map();
261
+
262
+ for (const [name, entry] of this.providers) {
263
+ stats.set(name, {
264
+ successCount: entry.successCount,
265
+ errorCount: entry.errorCount,
266
+ lastError: entry.lastError?.message,
267
+ lastErrorTime: entry.lastErrorTime
268
+ });
269
+ }
270
+
271
+ return stats;
272
+ }
273
+
274
+ /**
275
+ * Clear all cached data
276
+ */
277
+ public clearCache(): void {
278
+ this.cache.clear();
279
+ console.log('Fundamentals cache cleared');
280
+ }
281
+
282
+ /**
283
+ * Set cache TTL
284
+ */
285
+ public setCacheTTL(ttl: number): void {
286
+ this.cacheConfig.ttl = ttl;
287
+ console.log(`Fundamentals cache TTL set to ${ttl}ms`);
288
+ }
289
+
290
+ /**
291
+ * Get cache statistics
292
+ */
293
+ public getCacheStats(): {
294
+ size: number;
295
+ maxEntries: number;
296
+ ttl: number;
297
+ } {
298
+ return {
299
+ size: this.cache.size,
300
+ maxEntries: this.cacheConfig.maxEntries,
301
+ ttl: this.cacheConfig.ttl
302
+ };
303
+ }
304
+
305
+ /**
306
+ * Fetch with retry logic
307
+ */
308
+ private async fetchWithRetry<T>(
309
+ fetchFn: () => Promise<T>,
310
+ config: IFundamentalsProviderConfig
311
+ ): Promise<T> {
312
+ const maxAttempts = config.retryAttempts || 1;
313
+ let lastError: Error | undefined;
314
+
315
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
316
+ try {
317
+ return await fetchFn();
318
+ } catch (error) {
319
+ lastError = error as Error;
320
+
321
+ if (attempt < maxAttempts) {
322
+ const delay = (config.retryDelay || 1000) * attempt;
323
+ console.log(`Retry attempt ${attempt} after ${delay}ms`);
324
+ await plugins.smartdelay.delayFor(delay);
325
+ }
326
+ }
327
+ }
328
+
329
+ throw lastError || new Error('Unknown error during fetch');
330
+ }
331
+
332
+ /**
333
+ * Generate cache key for request
334
+ */
335
+ private getCacheKey(request: IFundamentalsRequest): string {
336
+ switch (request.type) {
337
+ case 'fundamentals-current':
338
+ return `fundamentals:${request.ticker}`;
339
+ case 'fundamentals-batch':
340
+ const tickers = request.tickers.sort().join(',');
341
+ return `fundamentals-batch:${tickers}`;
342
+ default:
343
+ return `unknown:${JSON.stringify(request)}`;
344
+ }
345
+ }
346
+
347
+ /**
348
+ * Get from cache if not expired
349
+ */
350
+ private getFromCache(key: string): IStockFundamentals | IStockFundamentals[] | null {
351
+ const entry = this.cache.get(key);
352
+
353
+ if (!entry) {
354
+ return null;
355
+ }
356
+
357
+ // Check if cache entry has expired
358
+ const age = Date.now() - entry.timestamp.getTime();
359
+ if (entry.ttl !== Infinity && age > entry.ttl) {
360
+ this.cache.delete(key);
361
+ return null;
362
+ }
363
+
364
+ return entry.fundamentals;
365
+ }
366
+
367
+ /**
368
+ * Add to cache with TTL
369
+ */
370
+ private addToCache(
371
+ key: string,
372
+ fundamentals: IStockFundamentals | IStockFundamentals[],
373
+ ttl?: number
374
+ ): void {
375
+ // Enforce max entries limit
376
+ if (this.cache.size >= this.cacheConfig.maxEntries) {
377
+ // Remove oldest entry
378
+ const oldestKey = this.cache.keys().next().value;
379
+ if (oldestKey) {
380
+ this.cache.delete(oldestKey);
381
+ }
382
+ }
383
+
384
+ this.cache.set(key, {
385
+ fundamentals,
386
+ timestamp: new Date(),
387
+ ttl: ttl || this.cacheConfig.ttl
388
+ });
389
+ }
390
+
391
+ /**
392
+ * Get human-readable request description
393
+ */
394
+ private getRequestDescription(request: IFundamentalsRequest): string {
395
+ switch (request.type) {
396
+ case 'fundamentals-current':
397
+ return `fundamentals for ${request.ticker}`;
398
+ case 'fundamentals-batch':
399
+ return `fundamentals for ${request.tickers.length} tickers`;
400
+ default:
401
+ return 'fundamentals data';
402
+ }
403
+ }
404
+ }