import { YahooClient } from './YahooClient.js'; export class BenchmarkProvider { constructor() { this.client = new YahooClient(); this.cache = { data: null, expiresAt: 0 }; this.TTL_MS = 60 * 60 * 1000; // Cache for 1 hour } async getMarketContext() { // 1. Return cached data if still valid if (this.cache.data && Date.now() < this.cache.expiresAt) { return this.cache.data; } try { const [sp500, tn10y] = await Promise.all([ this.client.fetchSummary('^GSPC'), this.client.fetchSummary('^TNX'), ]); const context = { sp500Price: sp500.price?.regularMarketPrice ?? 0, riskFreeRate: tn10y.price?.regularMarketPrice ?? 0, timestamp: new Date().toISOString(), }; // 2. Validate data sanity (prevent 0-value errors) if (context.sp500Price === 0 || context.riskFreeRate === 0) { throw new Error('Invalid market data received (zero values)'); } // 3. Update cache this.cache = { data: context, expiresAt: Date.now() + this.TTL_MS }; return context; } catch (error) { console.error( 'Market data fetch failed, using last known or empty state:', error, ); // If we have stale cache, use it even if expired, otherwise return safe defaults return this.cache.data || { sp500Price: 4500, riskFreeRate: 4.0 }; } } }