@fin.cx/opendata 1.5.3 → 1.5.4

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/readme.hints.md CHANGED
@@ -0,0 +1,45 @@
1
+ # OpenData Project Hints
2
+
3
+ ## Stocks Module
4
+
5
+ ### Overview
6
+ The stocks module provides real-time stock price data through various provider implementations. Currently supports Yahoo Finance with an extensible architecture for additional providers.
7
+
8
+ ### Architecture
9
+ - **Provider Pattern**: Each stock data source implements the `IStockProvider` interface
10
+ - **Service Registry**: `StockPriceService` manages providers with priority-based selection
11
+ - **Caching**: Built-in cache with configurable TTL to reduce API calls
12
+ - **Fallback Logic**: Automatic failover between providers if one fails
13
+
14
+ ### Yahoo Finance Provider Notes
15
+ - Uses public API endpoints (no authentication required)
16
+ - Two main endpoints:
17
+ - `/v8/finance/chart/{ticker}` - Single ticker with full data
18
+ - `/v8/finance/spark?symbols={tickers}` - Multiple tickers with basic data
19
+ - Response data is in `response.body` when using smartrequest
20
+ - Requires User-Agent header to avoid rate limiting
21
+
22
+ ### Usage Example
23
+ ```typescript
24
+ import { StockPriceService, YahooFinanceProvider } from '@fin.cx/opendata';
25
+
26
+ const stockService = new StockPriceService({ ttl: 60000 });
27
+ const yahooProvider = new YahooFinanceProvider();
28
+ stockService.register(yahooProvider);
29
+
30
+ const price = await stockService.getPrice({ ticker: 'AAPL' });
31
+ console.log(`${price.ticker}: $${price.price}`);
32
+ ```
33
+
34
+ ### Testing
35
+ - Tests use real API calls (be mindful of rate limits)
36
+ - Mock invalid ticker 'INVALID_TICKER_XYZ' for error testing
37
+ - Clear cache between tests to ensure fresh data
38
+ - The spark endpoint may return fewer results than requested
39
+
40
+ ### Future Providers
41
+ To add a new provider:
42
+ 1. Create `ts/stocks/providers/provider.{name}.ts`
43
+ 2. Implement the `IStockProvider` interface
44
+ 3. Register with `StockPriceService`
45
+ 4. No changes needed to existing code
package/readme.plan.md ADDED
@@ -0,0 +1,193 @@
1
+ # Stock Prices Module Implementation Plan
2
+
3
+ Command to reread guidelines: Read /home/philkunz/.claude/CLAUDE.md
4
+
5
+ ## Overview
6
+ Implementation of a stocks module for fetching current stock prices using various APIs. The architecture will support multiple providers, but we'll start with implementing only Yahoo Finance API. The design will make it easy to add additional providers (Alpha Vantage, IEX Cloud, etc.) in the future without changing the core architecture.
7
+
8
+ ## Phase 1: Yahoo Finance Implementation
9
+
10
+ ### 1.1 Research & Documentation
11
+ - [ ] Research Yahoo Finance API endpoints (no official API, using public endpoints)
12
+ - [ ] Document available data fields and formats
13
+ - [ ] Identify rate limits and restrictions
14
+ - [ ] Test endpoints manually with curl
15
+
16
+ ### 1.2 Module Structure
17
+ ```
18
+ ts/
19
+ ├── index.ts # Main exports
20
+ ├── plugins.ts # External dependencies
21
+ └── stocks/
22
+ ├── index.ts # Stocks module exports
23
+ ├── classes.stockservice.ts # Main StockPriceService class
24
+ ├── interfaces/
25
+ │ ├── stockprice.ts # IStockPrice interface
26
+ │ └── provider.ts # IStockProvider interface (for all providers)
27
+ └── providers/
28
+ ├── provider.yahoo.ts # Yahoo Finance implementation
29
+ └── (future: provider.alphavantage.ts, provider.iex.ts, etc.)
30
+ ```
31
+
32
+ ### 1.3 Core Interfaces
33
+ ```typescript
34
+ // IStockPrice - Standardized stock price data
35
+ interface IStockPrice {
36
+ ticker: string;
37
+ price: number;
38
+ currency: string;
39
+ change: number;
40
+ changePercent: number;
41
+ timestamp: Date;
42
+ provider: string;
43
+ }
44
+
45
+ // IStockProvider - Provider implementation contract
46
+ interface IStockProvider {
47
+ name: string;
48
+ fetchPrice(ticker: string): Promise<IStockPrice>;
49
+ fetchPrices(tickers: string[]): Promise<IStockPrice[]>;
50
+ isAvailable(): Promise<boolean>;
51
+ }
52
+ ```
53
+
54
+ ### 1.4 Yahoo Finance Provider Implementation
55
+ - [ ] Create YahooFinanceProvider class
56
+ - [ ] Implement HTTP requests to Yahoo Finance endpoints
57
+ - [ ] Parse response data into IStockPrice format
58
+ - [ ] Handle errors and edge cases
59
+ - [ ] Add request throttling/rate limiting
60
+
61
+ ### 1.5 Main Service Class
62
+ - [ ] Create StockPriceService class with provider registry
63
+ - [ ] Implement provider interface for pluggable providers
64
+ - [ ] Register Yahoo provider (with ability to add more later)
65
+ - [ ] Add method for single ticker lookup
66
+ - [ ] Add method for batch ticker lookup
67
+ - [ ] Implement error handling with graceful degradation
68
+ - [ ] Design fallback mechanism (ready for multiple providers)
69
+
70
+ ## Phase 2: Core Features
71
+
72
+ ### 2.1 Service Architecture
73
+ - [ ] Create provider registry pattern for managing multiple providers
74
+ - [ ] Implement provider priority and selection logic
75
+ - [ ] Design provider health check interface
76
+ - [ ] Create provider configuration system
77
+ - [ ] Implement provider discovery mechanism
78
+ - [ ] Add provider capability querying (which tickers/markets supported)
79
+
80
+ ## Phase 3: Advanced Features
81
+
82
+ ### 3.1 Caching System
83
+ - [ ] Design cache interface
84
+ - [ ] Implement in-memory cache with TTL
85
+ - [ ] Add cache invalidation logic
86
+ - [ ] Make cache configurable per ticker
87
+
88
+ ### 3.2 Configuration
89
+ - [ ] Provider configuration (timeout, retry settings)
90
+ - [ ] Cache configuration (TTL, max entries)
91
+ - [ ] Request timeout configuration
92
+ - [ ] Error handling configuration
93
+
94
+ ### 3.3 Error Handling
95
+ - [ ] Define custom error types
96
+ - [ ] Implement retry logic with exponential backoff
97
+ - [ ] Add circuit breaker pattern for failing providers
98
+ - [ ] Comprehensive error logging
99
+
100
+ ## Phase 4: Testing
101
+
102
+ ### 4.1 Unit Tests
103
+ - [ ] Test each provider independently
104
+ - [ ] Mock HTTP requests for predictable testing
105
+ - [ ] Test error scenarios
106
+ - [ ] Test data transformation logic
107
+
108
+ ### 4.2 Integration Tests
109
+ - [ ] Test with real API calls (rate limit aware)
110
+ - [ ] Test provider fallback scenarios
111
+ - [ ] Test batch operations
112
+ - [ ] Test cache behavior
113
+
114
+ ### 4.3 Performance Tests
115
+ - [ ] Measure response times
116
+ - [ ] Test concurrent request handling
117
+ - [ ] Validate cache effectiveness
118
+
119
+ ## Implementation Order
120
+
121
+ 1. **Week 1: Yahoo Finance Provider**
122
+ - Research and test Yahoo endpoints
123
+ - Implement basic provider and service
124
+ - Create core interfaces
125
+ - Basic error handling
126
+
127
+ 2. **Week 2: Service Architecture**
128
+ - Create extensible provider system
129
+ - Implement provider interface
130
+ - Add provider registration
131
+
132
+ 3. **Week 3: Advanced Features**
133
+ - Implement caching system
134
+ - Add configuration management
135
+ - Enhance error handling
136
+
137
+ 4. **Week 4: Testing & Documentation**
138
+ - Write comprehensive tests
139
+ - Create usage documentation
140
+ - Performance optimization
141
+
142
+ ## Dependencies
143
+
144
+ ### Required
145
+ - `@push.rocks/smartrequest` - HTTP requests
146
+ - `@push.rocks/smartpromise` - Promise utilities
147
+ - `@push.rocks/smartlog` - Logging
148
+
149
+ ### Development
150
+ - `@git.zone/tstest` - Testing framework
151
+ - `@git.zone/tsrun` - TypeScript execution
152
+
153
+ ## API Endpoints Research
154
+
155
+ ### Yahoo Finance
156
+ - Base URL: `https://query1.finance.yahoo.com/v8/finance/chart/{ticker}`
157
+ - No authentication required
158
+ - Returns JSON with price data
159
+ - Rate limits unknown (need to test)
160
+ - Alternative endpoints to explore:
161
+ - `/v7/finance/quote` - Simplified quote data
162
+ - `/v10/finance/quoteSummary` - Detailed company data
163
+
164
+ ## Success Criteria
165
+
166
+ 1. Can fetch current stock prices for any valid ticker
167
+ 2. Extensible architecture for future providers
168
+ 3. Response time < 1 second for cached data
169
+ 4. Response time < 3 seconds for fresh data
170
+ 5. Proper error handling and recovery
171
+ 6. Comprehensive test coverage (>80%)
172
+
173
+ ## Notes
174
+
175
+ - Yahoo Finance provides free stock data without authentication
176
+ - **Architecture designed for multiple providers**: While only implementing Yahoo Finance initially, all interfaces, classes, and patterns are designed to support multiple stock data providers
177
+ - The provider registry pattern allows adding new providers without modifying existing code
178
+ - Each provider implements the same IStockProvider interface for consistency
179
+ - Future providers can be added by simply creating a new provider class and registering it
180
+ - Implement proper TypeScript types for all data structures
181
+ - Follow the project's coding standards (prefix interfaces with 'I')
182
+ - Use plugins.ts for all external dependencies
183
+ - Keep filenames lowercase
184
+ - Write tests using @git.zone/tstest with smartexpect syntax
185
+ - Focus on clean, extensible architecture for future growth
186
+
187
+ ## Future Provider Addition Example
188
+
189
+ When ready to add a new provider (e.g., Alpha Vantage), the process will be:
190
+ 1. Create `ts/stocks/providers/provider.alphavantage.ts`
191
+ 2. Implement the `IStockProvider` interface
192
+ 3. Register the provider in the StockPriceService
193
+ 4. No changes needed to existing code or interfaces
package/ts/index.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from './classes.main.opendata.js';
2
+ export * from './stocks/index.js';
package/ts/plugins.ts CHANGED
@@ -14,6 +14,7 @@ import * as smartbrowser from '@push.rocks/smartbrowser';
14
14
  import * as smartdata from '@push.rocks/smartdata';
15
15
  import * as smartdelay from '@push.rocks/smartdelay';
16
16
  import * as smartfile from '@push.rocks/smartfile';
17
+ import * as smartlog from '@push.rocks/smartlog';
17
18
  import * as smartpath from '@push.rocks/smartpath';
18
19
  import * as smartpromise from '@push.rocks/smartpromise';
19
20
  import * as smartrequest from '@push.rocks/smartrequest';
@@ -30,6 +31,7 @@ export {
30
31
  smartdata,
31
32
  smartdelay,
32
33
  smartfile,
34
+ smartlog,
33
35
  smartpath,
34
36
  smartpromise,
35
37
  smartrequest,
@@ -0,0 +1,309 @@
1
+ import * as plugins from '../plugins.js';
2
+ import type { IStockProvider, IProviderConfig, IProviderRegistry } from './interfaces/provider.js';
3
+ import type { IStockPrice, IStockQuoteRequest, IStockBatchQuoteRequest, IStockPriceError } from './interfaces/stockprice.js';
4
+
5
+ interface IProviderEntry {
6
+ provider: IStockProvider;
7
+ config: IProviderConfig;
8
+ lastError?: Error;
9
+ lastErrorTime?: Date;
10
+ successCount: number;
11
+ errorCount: number;
12
+ }
13
+
14
+ interface ICacheEntry {
15
+ price: IStockPrice;
16
+ timestamp: Date;
17
+ }
18
+
19
+ export class StockPriceService implements IProviderRegistry {
20
+ private providers = new Map<string, IProviderEntry>();
21
+ private cache = new Map<string, ICacheEntry>();
22
+ private logger = console;
23
+
24
+ private cacheConfig = {
25
+ ttl: 60000, // 60 seconds default
26
+ maxEntries: 1000
27
+ };
28
+
29
+ constructor(cacheConfig?: { ttl?: number; maxEntries?: number }) {
30
+ if (cacheConfig) {
31
+ this.cacheConfig = { ...this.cacheConfig, ...cacheConfig };
32
+ }
33
+ }
34
+
35
+ public register(provider: IStockProvider, config?: IProviderConfig): void {
36
+ const defaultConfig: IProviderConfig = {
37
+ enabled: true,
38
+ priority: provider.priority,
39
+ timeout: 10000,
40
+ retryAttempts: 2,
41
+ retryDelay: 1000
42
+ };
43
+
44
+ const mergedConfig = { ...defaultConfig, ...config };
45
+
46
+ this.providers.set(provider.name, {
47
+ provider,
48
+ config: mergedConfig,
49
+ successCount: 0,
50
+ errorCount: 0
51
+ });
52
+
53
+ console.log(`Registered provider: ${provider.name}`);
54
+ }
55
+
56
+ public unregister(providerName: string): void {
57
+ this.providers.delete(providerName);
58
+ console.log(`Unregistered provider: ${providerName}`);
59
+ }
60
+
61
+ public getProvider(name: string): IStockProvider | undefined {
62
+ return this.providers.get(name)?.provider;
63
+ }
64
+
65
+ public getAllProviders(): IStockProvider[] {
66
+ return Array.from(this.providers.values()).map(entry => entry.provider);
67
+ }
68
+
69
+ public getEnabledProviders(): IStockProvider[] {
70
+ return Array.from(this.providers.values())
71
+ .filter(entry => entry.config.enabled)
72
+ .sort((a, b) => (b.config.priority || 0) - (a.config.priority || 0))
73
+ .map(entry => entry.provider);
74
+ }
75
+
76
+ public async getPrice(request: IStockQuoteRequest): Promise<IStockPrice> {
77
+ const cacheKey = this.getCacheKey(request);
78
+ const cached = this.getFromCache(cacheKey);
79
+
80
+ if (cached) {
81
+ console.log(`Cache hit for ${request.ticker}`);
82
+ return cached;
83
+ }
84
+
85
+ const providers = this.getEnabledProviders();
86
+ if (providers.length === 0) {
87
+ throw new Error('No stock price providers available');
88
+ }
89
+
90
+ let lastError: Error | undefined;
91
+
92
+ for (const provider of providers) {
93
+ const entry = this.providers.get(provider.name)!;
94
+
95
+ try {
96
+ const price = await this.fetchWithRetry(
97
+ () => provider.fetchPrice(request),
98
+ entry.config
99
+ );
100
+
101
+ entry.successCount++;
102
+ this.addToCache(cacheKey, price);
103
+ console.log(`Successfully fetched ${request.ticker} from ${provider.name}`);
104
+ return price;
105
+ } catch (error) {
106
+ entry.errorCount++;
107
+ entry.lastError = error as Error;
108
+ entry.lastErrorTime = new Date();
109
+ lastError = error as Error;
110
+
111
+ console.warn(
112
+ `Provider ${provider.name} failed for ${request.ticker}: ${error.message}`
113
+ );
114
+ }
115
+ }
116
+
117
+ throw new Error(
118
+ `Failed to fetch price for ${request.ticker} from all providers. Last error: ${lastError?.message}`
119
+ );
120
+ }
121
+
122
+ public async getPrices(request: IStockBatchQuoteRequest): Promise<IStockPrice[]> {
123
+ const cachedPrices: IStockPrice[] = [];
124
+ const tickersToFetch: string[] = [];
125
+
126
+ // Check cache for each ticker
127
+ for (const ticker of request.tickers) {
128
+ const cacheKey = this.getCacheKey({ ticker, includeExtendedHours: request.includeExtendedHours });
129
+ const cached = this.getFromCache(cacheKey);
130
+
131
+ if (cached) {
132
+ cachedPrices.push(cached);
133
+ } else {
134
+ tickersToFetch.push(ticker);
135
+ }
136
+ }
137
+
138
+ if (tickersToFetch.length === 0) {
139
+ console.log(`All ${request.tickers.length} tickers served from cache`);
140
+ return cachedPrices;
141
+ }
142
+
143
+ const providers = this.getEnabledProviders();
144
+ if (providers.length === 0) {
145
+ throw new Error('No stock price providers available');
146
+ }
147
+
148
+ let lastError: Error | undefined;
149
+ let fetchedPrices: IStockPrice[] = [];
150
+
151
+ for (const provider of providers) {
152
+ const entry = this.providers.get(provider.name)!;
153
+
154
+ try {
155
+ fetchedPrices = await this.fetchWithRetry(
156
+ () => provider.fetchPrices({
157
+ tickers: tickersToFetch,
158
+ includeExtendedHours: request.includeExtendedHours
159
+ }),
160
+ entry.config
161
+ );
162
+
163
+ entry.successCount++;
164
+
165
+ // Cache the fetched prices
166
+ for (const price of fetchedPrices) {
167
+ const cacheKey = this.getCacheKey({
168
+ ticker: price.ticker,
169
+ includeExtendedHours: request.includeExtendedHours
170
+ });
171
+ this.addToCache(cacheKey, price);
172
+ }
173
+
174
+ console.log(
175
+ `Successfully fetched ${fetchedPrices.length} prices from ${provider.name}`
176
+ );
177
+ break;
178
+ } catch (error) {
179
+ entry.errorCount++;
180
+ entry.lastError = error as Error;
181
+ entry.lastErrorTime = new Date();
182
+ lastError = error as Error;
183
+
184
+ console.warn(
185
+ `Provider ${provider.name} failed for batch request: ${error.message}`
186
+ );
187
+ }
188
+ }
189
+
190
+ if (fetchedPrices.length === 0 && lastError) {
191
+ throw new Error(
192
+ `Failed to fetch prices from all providers. Last error: ${lastError.message}`
193
+ );
194
+ }
195
+
196
+ return [...cachedPrices, ...fetchedPrices];
197
+ }
198
+
199
+ public async checkProvidersHealth(): Promise<Map<string, boolean>> {
200
+ const health = new Map<string, boolean>();
201
+
202
+ for (const [name, entry] of this.providers) {
203
+ if (!entry.config.enabled) {
204
+ health.set(name, false);
205
+ continue;
206
+ }
207
+
208
+ try {
209
+ const isAvailable = await entry.provider.isAvailable();
210
+ health.set(name, isAvailable);
211
+ } catch (error) {
212
+ health.set(name, false);
213
+ console.error(`Health check failed for ${name}:`, error);
214
+ }
215
+ }
216
+
217
+ return health;
218
+ }
219
+
220
+ public getProviderStats(): Map<string, {
221
+ successCount: number;
222
+ errorCount: number;
223
+ lastError?: string;
224
+ lastErrorTime?: Date;
225
+ }> {
226
+ const stats = new Map();
227
+
228
+ for (const [name, entry] of this.providers) {
229
+ stats.set(name, {
230
+ successCount: entry.successCount,
231
+ errorCount: entry.errorCount,
232
+ lastError: entry.lastError?.message,
233
+ lastErrorTime: entry.lastErrorTime
234
+ });
235
+ }
236
+
237
+ return stats;
238
+ }
239
+
240
+ public clearCache(): void {
241
+ this.cache.clear();
242
+ console.log('Cache cleared');
243
+ }
244
+
245
+ public setCacheTTL(ttl: number): void {
246
+ this.cacheConfig.ttl = ttl;
247
+ console.log(`Cache TTL set to ${ttl}ms`);
248
+ }
249
+
250
+ private async fetchWithRetry<T>(
251
+ fetchFn: () => Promise<T>,
252
+ config: IProviderConfig
253
+ ): Promise<T> {
254
+ const maxAttempts = config.retryAttempts || 1;
255
+ let lastError: Error | undefined;
256
+
257
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
258
+ try {
259
+ return await fetchFn();
260
+ } catch (error) {
261
+ lastError = error as Error;
262
+
263
+ if (attempt < maxAttempts) {
264
+ const delay = (config.retryDelay || 1000) * attempt;
265
+ console.log(`Retry attempt ${attempt} after ${delay}ms`);
266
+ await plugins.smartdelay.delayFor(delay);
267
+ }
268
+ }
269
+ }
270
+
271
+ throw lastError || new Error('Unknown error during fetch');
272
+ }
273
+
274
+ private getCacheKey(request: IStockQuoteRequest): string {
275
+ return `${request.ticker}:${request.includeExtendedHours || false}`;
276
+ }
277
+
278
+ private getFromCache(key: string): IStockPrice | null {
279
+ const entry = this.cache.get(key);
280
+
281
+ if (!entry) {
282
+ return null;
283
+ }
284
+
285
+ const age = Date.now() - entry.timestamp.getTime();
286
+ if (age > this.cacheConfig.ttl) {
287
+ this.cache.delete(key);
288
+ return null;
289
+ }
290
+
291
+ return entry.price;
292
+ }
293
+
294
+ private addToCache(key: string, price: IStockPrice): void {
295
+ // Enforce max entries limit
296
+ if (this.cache.size >= this.cacheConfig.maxEntries) {
297
+ // Remove oldest entry
298
+ const oldestKey = this.cache.keys().next().value;
299
+ if (oldestKey) {
300
+ this.cache.delete(oldestKey);
301
+ }
302
+ }
303
+
304
+ this.cache.set(key, {
305
+ price,
306
+ timestamp: new Date()
307
+ });
308
+ }
309
+ }
@@ -0,0 +1,9 @@
1
+ // Export all interfaces
2
+ export * from './interfaces/stockprice.js';
3
+ export * from './interfaces/provider.js';
4
+
5
+ // Export main service
6
+ export * from './classes.stockservice.js';
7
+
8
+ // Export providers
9
+ export * from './providers/provider.yahoo.js';
@@ -0,0 +1,36 @@
1
+ import type { IStockPrice, IStockQuoteRequest, IStockBatchQuoteRequest } from './stockprice.js';
2
+
3
+ export interface IStockProvider {
4
+ name: string;
5
+ priority: number;
6
+
7
+ fetchPrice(request: IStockQuoteRequest): Promise<IStockPrice>;
8
+ fetchPrices(request: IStockBatchQuoteRequest): Promise<IStockPrice[]>;
9
+ isAvailable(): Promise<boolean>;
10
+
11
+ supportsMarket?(market: string): boolean;
12
+ supportsTicker?(ticker: string): boolean;
13
+
14
+ readonly requiresAuth: boolean;
15
+ readonly rateLimit?: {
16
+ requestsPerMinute: number;
17
+ requestsPerDay?: number;
18
+ };
19
+ }
20
+
21
+ export interface IProviderConfig {
22
+ enabled: boolean;
23
+ priority?: number;
24
+ apiKey?: string;
25
+ timeout?: number;
26
+ retryAttempts?: number;
27
+ retryDelay?: number;
28
+ }
29
+
30
+ export interface IProviderRegistry {
31
+ register(provider: IStockProvider, config?: IProviderConfig): void;
32
+ unregister(providerName: string): void;
33
+ getProvider(name: string): IStockProvider | undefined;
34
+ getAllProviders(): IStockProvider[];
35
+ getEnabledProviders(): IStockProvider[];
36
+ }
@@ -0,0 +1,30 @@
1
+ export interface IStockPrice {
2
+ ticker: string;
3
+ price: number;
4
+ currency: string;
5
+ change: number;
6
+ changePercent: number;
7
+ previousClose: number;
8
+ timestamp: Date;
9
+ provider: string;
10
+ marketState: 'PRE' | 'REGULAR' | 'POST' | 'CLOSED';
11
+ exchange?: string;
12
+ exchangeName?: string;
13
+ }
14
+
15
+ export interface IStockPriceError {
16
+ ticker: string;
17
+ error: string;
18
+ provider: string;
19
+ timestamp: Date;
20
+ }
21
+
22
+ export interface IStockQuoteRequest {
23
+ ticker: string;
24
+ includeExtendedHours?: boolean;
25
+ }
26
+
27
+ export interface IStockBatchQuoteRequest {
28
+ tickers: string[];
29
+ includeExtendedHours?: boolean;
30
+ }