Real-time dashboard for monitoring global news, markets, and geopolitical events
TypeScript
Add Federal Reserve monitoring panel
Reggie7052c245f8f8
diff --git a/src/lib/api/fred.ts b/src/lib/api/fred.tsnew file mode 100644index 0000000..02d5052--- /dev/null+++ b/src/lib/api/fred.ts@@ -0,0 +1,367 @@+/**+ * FRED API - Federal Reserve Economic Data+ * Also includes Fed RSS feed fetching for news/speeches+ *+ * Get your free API key at: https://fred.stlouisfed.org/docs/api/api_key.html+ */++import { FRED_API_KEY, FRED_BASE_URL, logger, fetchWithProxy } from '$lib/config/api';++export interface FredObservation {+ date: string;+ value: string;+}++export interface FredSeriesResponse {+ observations: FredObservation[];+}++export interface EconomicIndicator {+ seriesId: string;+ name: string;+ value: number | null;+ previousValue: number | null;+ change: number | null;+ unit: string;+ date: string | null;+}++export interface FedIndicators {+ fedFundsRate: EconomicIndicator;+ cpi: EconomicIndicator;+ treasury10Y: EconomicIndicator;+}++/**+ * Check if FRED API key is configured+ */+export function isFredConfigured(): boolean {+ return FRED_API_KEY.length > 0;+}++/**+ * Create an empty indicator (used for error/missing data states)+ */+function createEmptyIndicator(seriesId: string, name: string, unit: string): EconomicIndicator {+ return {+ seriesId,+ name,+ value: null,+ previousValue: null,+ change: null,+ unit,+ date: null+ };+}++/**+ * Fetch a single FRED series with the latest 2 observations+ */+async function fetchFredSeries(seriesId: string): Promise<FredObservation[]> {+ try {+ const url = `${FRED_BASE_URL}/series/observations?series_id=${seriesId}&api_key=${FRED_API_KEY}&file_type=json&sort_order=desc&limit=2`;+ const response = await fetch(url);++ if (!response.ok) {+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);+ }++ const data: FredSeriesResponse = await response.json();+ return data.observations || [];+ } catch (error) {+ logger.error('FRED API', `Error fetching series ${seriesId}:`, error);+ return [];+ }+}++/**+ * Parse FRED observation value (handles "." for missing data)+ */+function parseValue(obs: FredObservation | undefined): number | null {+ if (!obs || obs.value === '.') return null;+ const val = parseFloat(obs.value);+ return isNaN(val) ? null : val;+}++/**+ * Fetch Federal Funds Effective Rate+ * Series: FEDFUNDS (monthly)+ */+async function fetchFedFundsRate(): Promise<EconomicIndicator> {+ const seriesId = 'FEDFUNDS';+ const name = 'Fed Funds Rate';+ const unit = '%';++ if (!isFredConfigured()) {+ return createEmptyIndicator(seriesId, name, unit);+ }++ const observations = await fetchFredSeries(seriesId);+ const current = parseValue(observations[0]);+ const previous = parseValue(observations[1]);++ return {+ seriesId,+ name,+ value: current,+ previousValue: previous,+ change: current !== null && previous !== null ? current - previous : null,+ unit,+ date: observations[0]?.date || null+ };+}++/**+ * Fetch Consumer Price Index (Year-over-Year % Change)+ * Series: CPIAUCSL (monthly, we calculate YoY change)+ */+async function fetchCPI(): Promise<EconomicIndicator> {+ const seriesId = 'CPIAUCSL';+ const name = 'CPI Inflation';+ const unit = '%';++ if (!isFredConfigured()) {+ return createEmptyIndicator(seriesId, name, unit);+ }++ try {+ // Fetch 14 observations: current + 12 months ago, plus previous month + 13 months ago+ const url = `${FRED_BASE_URL}/series/observations?series_id=${seriesId}&api_key=${FRED_API_KEY}&file_type=json&sort_order=desc&limit=14`;+ const response = await fetch(url);++ if (!response.ok) {+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);+ }++ const data: FredSeriesResponse = await response.json();+ const observations = data.observations || [];++ if (observations.length < 13) {+ return createEmptyIndicator(seriesId, name, unit);+ }++ const currentCPI = parseValue(observations[0]);+ const yearAgoCPI = parseValue(observations[12]);+ const previousMonthCPI = parseValue(observations[1]);+ const prevYearAgoCPI = observations.length >= 14 ? parseValue(observations[13]) : yearAgoCPI;++ if (currentCPI === null || yearAgoCPI === null) {+ return createEmptyIndicator(seriesId, name, unit);+ }++ const yoyChange = ((currentCPI - yearAgoCPI) / yearAgoCPI) * 100;+ const prevYoyChange =+ previousMonthCPI !== null && prevYearAgoCPI !== null+ ? ((previousMonthCPI - prevYearAgoCPI) / prevYearAgoCPI) * 100+ : null;++ return {+ seriesId,+ name,+ value: Math.round(yoyChange * 100) / 100,+ previousValue: prevYoyChange !== null ? Math.round(prevYoyChange * 100) / 100 : null,+ change: prevYoyChange !== null ? Math.round((yoyChange - prevYoyChange) * 100) / 100 : null,+ unit,+ date: observations[0]?.date || null+ };+ } catch (error) {+ logger.error('FRED API', 'Error fetching CPI:', error);+ return createEmptyIndicator(seriesId, name, unit);+ }+}++/**+ * Fetch 10-Year Treasury Constant Maturity Rate+ * Series: DGS10 (daily)+ */+async function fetchTreasury10Y(): Promise<EconomicIndicator> {+ const seriesId = 'DGS10';+ const name = '10Y Treasury';+ const unit = '%';++ if (!isFredConfigured()) {+ return createEmptyIndicator(seriesId, name, unit);+ }++ const observations = await fetchFredSeries(seriesId);+ const current = parseValue(observations[0]);+ const previous = parseValue(observations[1]);++ return {+ seriesId,+ name,+ value: current,+ previousValue: previous,+ change:+ current !== null && previous !== null ? Math.round((current - previous) * 100) / 100 : null,+ unit,+ date: observations[0]?.date || null+ };+}++/**+ * Fetch all Fed economic indicators+ */+export async function fetchFedIndicators(): Promise<FedIndicators> {+ logger.log('FRED API', 'Fetching Fed indicators');++ const [fedFundsRate, cpi, treasury10Y] = await Promise.all([+ fetchFedFundsRate(),+ fetchCPI(),+ fetchTreasury10Y()+ ]);++ return { fedFundsRate, cpi, treasury10Y };+}++// ============================================================================+// Fed RSS News Fetching+// ============================================================================++const FED_BASE_URL = 'https://www.federalreserve.gov';++/**+ * Fed RSS feed configuration+ */+const FED_RSS_FEEDS = [+ { url: `${FED_BASE_URL}/feeds/press_monetary.xml`, type: 'monetary', label: 'Monetary Policy' },+ { url: `${FED_BASE_URL}/feeds/s_t_powell.xml`, type: 'powell', label: 'Chair Powell' },+ { url: `${FED_BASE_URL}/feeds/speeches.xml`, type: 'speech', label: 'Speeches' },+ { url: `${FED_BASE_URL}/feeds/testimony.xml`, type: 'testimony', label: 'Testimony' },+ { url: `${FED_BASE_URL}/feeds/press_other.xml`, type: 'announcement', label: 'Announcements' }+] as const;++export type FedNewsType = (typeof FED_RSS_FEEDS)[number]['type'];++export interface FedNewsItem {+ id: string;+ title: string;+ link: string;+ description: string;+ pubDate: string;+ timestamp: number;+ type: FedNewsType;+ typeLabel: string;+ isPowellRelated: boolean;+ hasVideo: boolean;+}++/**+ * Simple hash for generating unique IDs+ */+function hashString(str: string): string {+ let hash = 0;+ for (let i = 0; i < str.length; i++) {+ const char = str.charCodeAt(i);+ hash = (hash << 5) - hash + char;+ hash = hash & hash;+ }+ return Math.abs(hash).toString(36);+}++/**+ * Parse RSS XML and extract items+ */+function parseRssXml(xml: string, type: FedNewsType, typeLabel: string): FedNewsItem[] {+ const items: FedNewsItem[] = [];++ // Simple regex-based XML parsing for RSS items+ const itemRegex = /<item>([\s\S]*?)<\/item>/gi;+ const titleRegex = /<title>(?:<!\[CDATA\[)?([\s\S]*?)(?:\]\]>)?<\/title>/i;+ const linkRegex = /<link>(?:<!\[CDATA\[)?([\s\S]*?)(?:\]\]>)?<\/link>/i;+ const descRegex = /<description>(?:<!\[CDATA\[)?([\s\S]*?)(?:\]\]>)?<\/description>/i;+ const pubDateRegex = /<pubDate>([\s\S]*?)<\/pubDate>/i;++ let match;+ while ((match = itemRegex.exec(xml)) !== null) {+ const itemXml = match[1];++ const titleMatch = titleRegex.exec(itemXml);+ const linkMatch = linkRegex.exec(itemXml);+ const descMatch = descRegex.exec(itemXml);+ const pubDateMatch = pubDateRegex.exec(itemXml);++ const title = titleMatch?.[1]?.trim() || '';+ const link = linkMatch?.[1]?.trim() || '';+ const description = descMatch?.[1]?.trim().replace(/<[^>]*>/g, '') || '';+ const pubDate = pubDateMatch?.[1]?.trim() || '';++ if (!title || !link) continue;++ const fullText = `${title} ${description}`.toLowerCase();+ const isPowellRelated = type === 'powell' || /powell|chair(?:man)?/.test(fullText);+ const hasVideo = /video|webcast|watch|broadcast|live/.test(fullText);++ items.push({+ id: `fed-${type}-${hashString(link)}`,+ title,+ link: link.startsWith('http') ? link : `${FED_BASE_URL}${link}`,+ description,+ pubDate,+ timestamp: pubDate ? new Date(pubDate).getTime() : Date.now(),+ type,+ typeLabel,+ isPowellRelated,+ hasVideo+ });+ }++ return items;+}++/**+ * Fetch a single Fed RSS feed+ */+async function fetchFedRssFeed(+ url: string,+ type: FedNewsType,+ typeLabel: string+): Promise<FedNewsItem[]> {+ try {+ logger.log('Fed RSS', `Fetching ${typeLabel} from ${url}`);+ const response = await fetchWithProxy(url);++ if (!response.ok) {+ throw new Error(`HTTP ${response.status}`);+ }++ const xml = await response.text();+ return parseRssXml(xml, type, typeLabel);+ } catch (error) {+ logger.error('Fed RSS', `Error fetching ${typeLabel}:`, error);+ return [];+ }+}++/**+ * Fetch all Fed news from RSS feeds+ */+export async function fetchFedNews(): Promise<FedNewsItem[]> {+ logger.log('Fed RSS', 'Fetching all Fed news feeds');++ const results = await Promise.all(+ FED_RSS_FEEDS.map((feed) => fetchFedRssFeed(feed.url, feed.type, feed.label))+ );++ // Flatten and dedupe by link+ const seen = new Set<string>();+ const allItems: FedNewsItem[] = [];++ for (const items of results) {+ for (const item of items) {+ if (!seen.has(item.link)) {+ seen.add(item.link);+ allItems.push(item);+ }+ }+ }++ // Sort by timestamp (newest first), with Powell items boosted+ return allItems.sort((a, b) => {+ // Powell items get priority+ if (a.isPowellRelated && !b.isPowellRelated) return -1;+ if (!a.isPowellRelated && b.isPowellRelated) return 1;+ // Then by timestamp+ return b.timestamp - a.timestamp;+ });+}diff --git a/src/lib/api/index.ts b/src/lib/api/index.tsindex a689992..1fd6869 100644--- a/src/lib/api/index.ts+++ b/src/lib/api/index.ts@@ -13,3 +13,5 @@ export {export { fetchPolymarket, fetchWhaleTransactions, fetchGovContracts, fetchLayoffs } from './misc';export type { Prediction, WhaleTransaction, Contract, Layoff } from './misc';export { fetchWorldLeaders } from './leaders';+export { fetchFedIndicators, fetchFedNews, isFredConfigured } from './fred';+export type { FedIndicators, EconomicIndicator, FedNewsItem, FedNewsType } from './fred';diff --git a/src/lib/components/panels/FedPanel.svelte b/src/lib/components/panels/FedPanel.sveltenew file mode 100644index 0000000..e5f3e2e--- /dev/null+++ b/src/lib/components/panels/FedPanel.svelte@@ -0,0 +1,396 @@+<script lang="ts">+ import { Panel, Badge } from '$lib/components/common';+ import { getRelativeTime } from '$lib/utils';+ import { fedNews, fedIndicators, fedVideos } from '$lib/stores';+ import { isFredConfigured } from '$lib/api/fred';+ import type { EconomicIndicator } from '$lib/api/fred';++ // Store state+ const newsState = $derived($fedNews);+ const indicatorsState = $derived($fedIndicators);+ const videoItems = $derived($fedVideos);++ const loading = $derived(newsState.loading || indicatorsState.loading);+ const error = $derived(newsState.error || indicatorsState.error);+ const hasApiKey = isFredConfigured();++ const indicatorList = $derived(+ indicatorsState.data+ ? [+ indicatorsState.data.fedFundsRate,+ indicatorsState.data.cpi,+ indicatorsState.data.treasury10Y+ ]+ : []+ );++ type BadgeVariant = 'default' | 'success' | 'warning' | 'danger' | 'info';++ const TYPE_VARIANTS: Record<string, BadgeVariant> = {+ powell: 'warning',+ monetary: 'danger',+ speech: 'info',+ testimony: 'success',+ announcement: 'default'+ };++ function formatValue(indicator: EconomicIndicator): string {+ if (indicator.value === null) return '--';+ return `${indicator.value.toFixed(2)}${indicator.unit}`;+ }++ function formatChange(indicator: EconomicIndicator): string {+ if (indicator.change === null) return '';+ const sign = indicator.change >= 0 ? '+' : '';+ return `${sign}${indicator.change.toFixed(2)}`;+ }++ function getChangeClass(change: number | null): string {+ if (change === null) return '';+ if (change > 0) return 'up';+ if (change < 0) return 'down';+ return '';+ }++ function getTypeVariant(type: string): BadgeVariant {+ return TYPE_VARIANTS[type] || 'default';+ }+</script>++<Panel id="fed" title="Federal Reserve" count={newsState.items.length} {loading} {error}>+ <!-- Economic Indicators -->+ {#if hasApiKey && indicatorList.length > 0}+ <div class="indicators-section">+ <div class="indicator-cards">+ {#each indicatorList as indicator (indicator.seriesId)}+ <div class="indicator-card">+ <div class="indicator-label">{indicator.name}</div>+ <div class="indicator-value">{formatValue(indicator)}</div>+ <div class="indicator-change {getChangeClass(indicator.change)}">+ {formatChange(indicator)}+ </div>+ </div>+ {/each}+ </div>+ </div>+ {:else if !hasApiKey && !loading}+ <div class="no-api-key">+ <span class="no-api-key-text">Add VITE_FRED_API_KEY for economic indicators</span>+ </div>+ {/if}++ <!-- Video/Speeches Section -->+ {#if videoItems.length > 0}+ <div class="video-section">+ <div class="section-header">+ <span class="section-title">Speeches & Video</span>+ <a+ href="https://www.federalreserve.gov/live-broadcast.htm"+ target="_blank"+ rel="noopener noreferrer"+ class="live-link"+ >+ Live Broadcast+ </a>+ </div>+ <div class="video-list">+ {#each videoItems.slice(0, 3) as item (item.id)}+ <a href={item.link} target="_blank" rel="noopener noreferrer" class="video-item">+ <div class="video-icon">►</div>+ <div class="video-content">+ <div class="video-title">{item.title}</div>+ <div class="video-meta">+ {#if item.isPowellRelated}+ <Badge text="POWELL" variant="warning" />+ {/if}+ <span>{getRelativeTime(item.pubDate)}</span>+ </div>+ </div>+ </a>+ {/each}+ </div>+ </div>+ {/if}++ <!-- News Feed -->+ <div class="news-section">+ {#if newsState.items.length === 0 && !loading && !error}+ <div class="empty-state">No Fed news available</div>+ {:else}+ <div class="fed-news-list">+ {#each newsState.items as item (item.id)}+ <div class="fed-news-item" class:powell={item.isPowellRelated}>+ <div class="fed-news-header">+ <div class="fed-news-badges">+ <Badge text={item.typeLabel} variant={getTypeVariant(item.type)} />+ {#if item.isPowellRelated && item.type !== 'powell'}+ <Badge text="POWELL" variant="warning" />+ {/if}+ {#if item.hasVideo}+ <Badge text="VIDEO" variant="info" />+ {/if}+ </div>+ {#if item.pubDate}+ <span class="fed-news-time">{getRelativeTime(item.pubDate)}</span>+ {/if}+ </div>+ <a href={item.link} target="_blank" rel="noopener noreferrer" class="fed-news-title">+ {item.title}+ </a>+ {#if item.description}+ <div class="fed-news-desc">+ {item.description.slice(0, 120)}{item.description.length > 120 ? '...' : ''}+ </div>+ {/if}+ </div>+ {/each}+ </div>+ {/if}+ </div>+</Panel>++<style>+ /* Indicators Section */+ .indicators-section {+ padding-bottom: 0.5rem;+ margin-bottom: 0.5rem;+ border-bottom: 1px solid var(--border);+ }++ .indicator-cards {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 0.5rem;+ }++ .indicator-card {+ text-align: center;+ padding: 0.4rem;+ background: var(--bg-secondary);+ border-radius: 4px;+ }++ .indicator-label {+ font-size: 0.5rem;+ color: var(--text-muted);+ text-transform: uppercase;+ letter-spacing: 0.03em;+ margin-bottom: 0.2rem;+ }++ .indicator-value {+ font-size: 0.85rem;+ font-weight: 700;+ color: var(--text-primary);+ font-variant-numeric: tabular-nums;+ }++ .indicator-change {+ font-size: 0.55rem;+ font-weight: 500;+ }++ .indicator-change.up {+ color: var(--success);+ }++ .indicator-change.down {+ color: var(--danger);+ }++ .no-api-key {+ padding: 0.5rem;+ margin-bottom: 0.5rem;+ background: var(--bg-secondary);+ border-radius: 4px;+ text-align: center;+ }++ .no-api-key-text {+ font-size: 0.55rem;+ color: var(--text-muted);+ }++ /* Video Section */+ .video-section {+ padding-bottom: 0.5rem;+ margin-bottom: 0.5rem;+ border-bottom: 1px solid var(--border);+ }++ .section-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 0.4rem;+ }++ .section-title {+ font-size: 0.55rem;+ font-weight: 600;+ color: var(--text-secondary);+ text-transform: uppercase;+ letter-spacing: 0.03em;+ }++ .live-link {+ font-size: 0.5rem;+ color: var(--danger);+ text-decoration: none;+ display: flex;+ align-items: center;+ gap: 0.25rem;+ }++ .live-link::before {+ content: '';+ width: 6px;+ height: 6px;+ background: var(--danger);+ border-radius: 50%;+ animation: pulse 1.5s ease-in-out infinite;+ }++ .live-link:hover {+ text-decoration: underline;+ }++ @keyframes pulse {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.4;+ }+ }++ .video-list {+ display: flex;+ flex-direction: column;+ gap: 0.4rem;+ }++ .video-item {+ display: flex;+ gap: 0.5rem;+ padding: 0.4rem;+ background: var(--bg-secondary);+ border-radius: 4px;+ text-decoration: none;+ transition: background 0.15s;+ }++ .video-item:hover {+ background: var(--bg-tertiary, var(--border));+ }++ .video-icon {+ color: var(--danger);+ font-size: 0.7rem;+ flex-shrink: 0;+ width: 1.2rem;+ height: 1.2rem;+ display: flex;+ align-items: center;+ justify-content: center;+ background: rgba(239, 68, 68, 0.1);+ border-radius: 4px;+ }++ .video-content {+ flex: 1;+ min-width: 0;+ }++ .video-title {+ font-size: 0.6rem;+ color: var(--text-primary);+ line-height: 1.3;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .video-meta {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ margin-top: 0.2rem;+ font-size: 0.5rem;+ color: var(--text-muted);+ }++ /* News Section */+ .news-section {+ flex: 1;+ }++ .fed-news-list {+ display: flex;+ flex-direction: column;+ }++ .fed-news-item {+ padding: 0.5rem 0;+ border-bottom: 1px solid var(--border);+ }++ .fed-news-item:last-child {+ border-bottom: none;+ }++ .fed-news-item.powell {+ background: rgba(255, 165, 0, 0.08);+ margin: 0 -0.5rem;+ padding: 0.5rem;+ border-radius: 4px;+ border: 1px solid rgba(255, 165, 0, 0.2);+ }++ .fed-news-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 0.3rem;+ gap: 0.5rem;+ }++ .fed-news-badges {+ display: flex;+ gap: 0.25rem;+ flex-wrap: wrap;+ }++ .fed-news-time {+ font-size: 0.5rem;+ color: var(--text-muted);+ flex-shrink: 0;+ }++ .fed-news-title {+ display: block;+ font-size: 0.65rem;+ color: var(--text-primary);+ text-decoration: none;+ line-height: 1.35;+ }++ .fed-news-title:hover {+ color: var(--accent);+ }++ .fed-news-desc {+ margin-top: 0.25rem;+ font-size: 0.55rem;+ color: var(--text-muted);+ line-height: 1.4;+ }++ .empty-state {+ text-align: center;+ color: var(--text-secondary);+ font-size: 0.7rem;+ padding: 1rem;+ }+</style>diff --git a/src/lib/components/panels/index.ts b/src/lib/components/panels/index.tsindex 4181ec8..434c499 100644--- a/src/lib/components/panels/index.ts+++ b/src/lib/components/panels/index.ts@@ -17,3 +17,4 @@ export { default as NarrativePanel } from './NarrativePanel.svelte';export { default as MonitorsPanel } from './MonitorsPanel.svelte';export { default as MapPanel } from './MapPanel.svelte';export { default as WorldLeadersPanel } from './WorldLeadersPanel.svelte';+export { default as FedPanel } from './FedPanel.svelte';diff --git a/src/lib/config/api.ts b/src/lib/config/api.tsindex a80873c..15ecb81 100644--- a/src/lib/config/api.ts+++ b/src/lib/config/api.ts@@ -15,6 +15,17 @@ export const FINNHUB_API_KEY = browserexport const FINNHUB_BASE_URL = 'https://finnhub.io/api/v1';+/**+ * FRED API key (St. Louis Fed)+ * Get your free key at: https://fred.stlouisfed.org/docs/api/api_key.html+ * Free tier: Unlimited requests+ */+export const FRED_API_KEY = browser+ ? (import.meta.env?.VITE_FRED_API_KEY ?? '')+ : (process.env.VITE_FRED_API_KEY ?? '');++export const FRED_BASE_URL = 'https://api.stlouisfed.org/fred';+/*** Check if we're in development mode* Uses import.meta.env which is available in both browser and test environmentsdiff --git a/src/lib/config/panels.ts b/src/lib/config/panels.tsindex 3d00fbf..bae67c3 100644--- a/src/lib/config/panels.ts+++ b/src/lib/config/panels.ts@@ -31,7 +31,8 @@ export type PanelId =| 'leaders'| 'intel'| 'correlation'- | 'narrative';+ | 'narrative'+ | 'fed';export const PANELS: Record<PanelId, PanelConfig> = {map: { name: 'Global Map', priority: 1 },@@ -57,7 +58,8 @@ export const PANELS: Record<PanelId, PanelConfig> = {leaders: { name: 'World Leaders', priority: 1 },intel: { name: 'Intel Feed', priority: 2 },correlation: { name: 'Correlation Engine', priority: 1 },- narrative: { name: 'Narrative Tracker', priority: 1 }+ narrative: { name: 'Narrative Tracker', priority: 1 },+ fed: { name: 'Federal Reserve', priority: 1 }};export const NON_DRAGGABLE_PANELS: PanelId[] = ['map'];diff --git a/src/lib/stores/fed.ts b/src/lib/stores/fed.tsnew file mode 100644index 0000000..3c56f10--- /dev/null+++ b/src/lib/stores/fed.ts@@ -0,0 +1,123 @@+/**+ * Federal Reserve store - manages Fed news and economic indicators+ */++import { writable, derived } from 'svelte/store';+import type { FedIndicators, FedNewsItem } from '$lib/api/fred';++// ============================================================================+// State Types+// ============================================================================++export interface FedIndicatorsState {+ data: FedIndicators | null;+ loading: boolean;+ error: string | null;+ lastUpdated: number | null;+}++export interface FedNewsState {+ items: FedNewsItem[];+ loading: boolean;+ error: string | null;+ lastUpdated: number | null;+}++// ============================================================================+// Indicators Store+// ============================================================================++function createFedIndicatorsStore() {+ const { subscribe, update } = writable<FedIndicatorsState>({+ data: null,+ loading: false,+ error: null,+ lastUpdated: null+ });++ return {+ subscribe,++ setLoading(loading: boolean) {+ update((state) => ({+ ...state,+ loading,+ error: loading ? null : state.error+ }));+ },++ setError(error: string | null) {+ update((state) => ({+ ...state,+ loading: false,+ error+ }));+ },++ setData(data: FedIndicators) {+ update(() => ({+ data,+ loading: false,+ error: null,+ lastUpdated: Date.now()+ }));+ }+ };+}++export const fedIndicators = createFedIndicatorsStore();++// ============================================================================+// News Store+// ============================================================================++function createFedNewsStore() {+ const { subscribe, update } = writable<FedNewsState>({+ items: [],+ loading: false,+ error: null,+ lastUpdated: null+ });++ return {+ subscribe,++ setLoading(loading: boolean) {+ update((state) => ({+ ...state,+ loading,+ error: loading ? null : state.error+ }));+ },++ setError(error: string | null) {+ update((state) => ({+ ...state,+ loading: false,+ error+ }));+ },++ setItems(items: FedNewsItem[]) {+ update(() => ({+ items,+ loading: false,+ error: null,+ lastUpdated: Date.now()+ }));+ }+ };+}++export const fedNews = createFedNewsStore();++// ============================================================================+// Derived Stores+// ============================================================================++export const isFedLoading = derived(+ [fedIndicators, fedNews],+ ([$indicators, $news]) => $indicators.loading || $news.loading+);++export const fedVideos = derived(fedNews, ($news) => $news.items.filter((item) => item.hasVideo));diff --git a/src/lib/stores/index.ts b/src/lib/stores/index.tsindex 5ef632f..49711f0 100644--- a/src/lib/stores/index.ts+++ b/src/lib/stores/index.ts@@ -67,3 +67,13 @@ export {type StageConfig,type RefreshState} from './refresh';++// Fed store+export {+ fedIndicators,+ fedNews,+ isFedLoading,+ fedVideos,+ type FedIndicatorsState,+ type FedNewsState+} from './fed';diff --git a/src/routes/+page.svelte b/src/routes/+page.svelteindex f15d8a2..90e045f 100644--- a/src/routes/+page.svelte+++ b/src/routes/+page.svelte@@ -20,9 +20,19 @@IntelPanel,SituationPanel,WorldLeadersPanel,- PrinterPanel+ PrinterPanel,+ FedPanel} from '$lib/components/panels';- import { news, markets, monitors, settings, refresh, allNewsItems } from '$lib/stores';+ import {+ news,+ markets,+ monitors,+ settings,+ refresh,+ allNewsItems,+ fedIndicators,+ fedNews+ } from '$lib/stores';import {fetchAllNews,fetchAllMarkets,@@ -30,7 +40,9 @@fetchWhaleTransactions,fetchGovContracts,fetchLayoffs,- fetchWorldLeaders+ fetchWorldLeaders,+ fetchFedIndicators,+ fetchFedNews} from '$lib/api';import type { Prediction, WhaleTransaction, Contract, Layoff } from '$lib/api';import type { CustomMonitor, WorldLeader } from '$lib/types';@@ -107,6 +119,21 @@}}+ async function loadFedData() {+ if (!isPanelVisible('fed')) return;+ fedIndicators.setLoading(true);+ fedNews.setLoading(true);+ try {+ const [indicatorsData, newsData] = await Promise.all([fetchFedIndicators(), fetchFedNews()]);+ fedIndicators.setData(indicatorsData);+ fedNews.setItems(newsData);+ } catch (error) {+ console.error('Failed to load Fed data:', error);+ fedIndicators.setError(String(error));+ fedNews.setError(String(error));+ }+ }+// Refresh handlersasync function handleRefresh() {refresh.startRefresh();@@ -168,7 +195,13 @@async function initialLoad() {refresh.startRefresh();try {- await Promise.all([loadNews(), loadMarkets(), loadMiscData(), loadWorldLeaders()]);+ await Promise.all([+ loadNews(),+ loadMarkets(),+ loadMiscData(),+ loadWorldLeaders(),+ loadFedData()+ ]);refresh.endRefresh();} catch (error) {refresh.endRefresh([String(error)]);@@ -282,6 +315,13 @@</div>{/if}+ <!-- Fed Panel -->+ {#if isPanelVisible('fed')}+ <div class="panel-slot">+ <FedPanel />+ </div>+ {/if}+<!-- World Leaders Panel -->{#if isPanelVisible('leaders')}<div class="panel-slot">