finance-query 2.5.0

A Rust library for querying financial data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
use crate::models::quote::FormattedValue;
use serde::{Deserialize, Serialize};

// ============================================================================
// Raw response structs (private) - for parsing Yahoo's nested structure
// ============================================================================

#[derive(Debug, Clone, Deserialize)]
struct RawSectorResponse {
    data: RawSectorData,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawSectorData {
    name: String,
    symbol: Option<String>,
    key: String,
    overview: Option<RawOverview>,
    performance: Option<RawPerformance>,
    #[serde(default)]
    performance_overview_benchmark: Option<RawBenchmarkPerformance>,
    #[serde(default)]
    top_companies: Vec<RawCompany>,
    #[serde(default, rename = "topETFs")]
    top_etfs: Vec<RawETF>,
    #[serde(default)]
    top_mutual_funds: Vec<RawMutualFund>,
    #[serde(default)]
    industries: Vec<RawIndustry>,
    #[serde(default)]
    research_reports: Vec<RawResearchReport>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawOverview {
    companies_count: Option<i64>,
    market_cap: Option<FormattedValue<f64>>,
    description: Option<String>,
    industries_count: Option<i64>,
    market_weight: Option<FormattedValue<f64>>,
    employee_count: Option<FormattedValue<i64>>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawPerformance {
    ytd_change_percent: Option<FormattedValue<f64>>,
    reg_market_change_percent: Option<FormattedValue<f64>>,
    three_year_change_percent: Option<FormattedValue<f64>>,
    one_year_change_percent: Option<FormattedValue<f64>>,
    five_year_change_percent: Option<FormattedValue<f64>>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawBenchmarkPerformance {
    name: Option<String>,
    ytd_change_percent: Option<FormattedValue<f64>>,
    reg_market_change_percent: Option<FormattedValue<f64>>,
    three_year_change_percent: Option<FormattedValue<f64>>,
    one_year_change_percent: Option<FormattedValue<f64>>,
    five_year_change_percent: Option<FormattedValue<f64>>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawCompany {
    symbol: String,
    name: Option<String>,
    market_cap: Option<FormattedValue<f64>>,
    market_weight: Option<FormattedValue<f64>>,
    last_price: Option<FormattedValue<f64>>,
    target_price: Option<FormattedValue<f64>>,
    reg_market_change_percent: Option<FormattedValue<f64>>,
    ytd_return: Option<FormattedValue<f64>>,
    rating: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawETF {
    symbol: String,
    name: Option<String>,
    net_assets: Option<FormattedValue<f64>>,
    expense_ratio: Option<FormattedValue<f64>>,
    last_price: Option<FormattedValue<f64>>,
    ytd_return: Option<FormattedValue<f64>>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawMutualFund {
    symbol: String,
    name: Option<String>,
    net_assets: Option<FormattedValue<f64>>,
    expense_ratio: Option<FormattedValue<f64>>,
    last_price: Option<FormattedValue<f64>>,
    ytd_return: Option<FormattedValue<f64>>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawIndustry {
    symbol: Option<String>,
    key: Option<String>,
    name: String,
    market_weight: Option<FormattedValue<f64>>,
    reg_market_change_percent: Option<FormattedValue<f64>>,
    ytd_return: Option<FormattedValue<f64>>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawResearchReport {
    id: String,
    head_html: Option<String>,
    provider: Option<String>,
    report_date: Option<String>,
    report_title: Option<String>,
    report_type: Option<String>,
    target_price: Option<f64>,
    target_price_status: Option<String>,
    investment_rating: Option<String>,
}

// ============================================================================
// Public response structs - clean, user-friendly types
// ============================================================================

/// Complete sector data with all available information
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SectorData {
    /// Sector name (e.g., "Technology")
    pub name: String,

    /// Yahoo Finance sector symbol (e.g., "^YH311")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,

    /// Sector key for API calls (e.g., "technology")
    pub key: String,

    /// Sector overview with market statistics
    #[serde(skip_serializing_if = "Option::is_none")]
    pub overview: Option<SectorOverview>,

    /// Sector performance metrics
    #[serde(skip_serializing_if = "Option::is_none")]
    pub performance: Option<SectorPerformance>,

    /// Benchmark (S&P 500) comparison performance
    #[serde(skip_serializing_if = "Option::is_none")]
    pub benchmark: Option<SectorPerformance>,

    /// Benchmark name (usually "S&P 500")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub benchmark_name: Option<String>,

    /// Top companies in the sector
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_companies: Vec<SectorCompany>,

    /// Top ETFs tracking this sector
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_etfs: Vec<SectorETF>,

    /// Top mutual funds in this sector
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_mutual_funds: Vec<SectorMutualFund>,

    /// Industries within this sector
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub industries: Vec<SectorIndustry>,

    /// Recent research reports
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub research_reports: Vec<ResearchReport>,
}

/// Sector overview statistics
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "dataframe", derive(crate::ToDataFrame))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SectorOverview {
    /// Number of companies in the sector
    #[serde(skip_serializing_if = "Option::is_none")]
    pub companies_count: Option<i64>,

    /// Total market capitalization
    #[serde(skip_serializing_if = "Option::is_none")]
    pub market_cap: Option<FormattedValue<f64>>,

    /// Sector description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Number of industries in the sector
    #[serde(skip_serializing_if = "Option::is_none")]
    pub industries_count: Option<i64>,

    /// Market weight (percentage of total market)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub market_weight: Option<FormattedValue<f64>>,

    /// Total employee count across sector
    #[serde(skip_serializing_if = "Option::is_none")]
    pub employee_count: Option<FormattedValue<i64>>,
}

/// Sector performance metrics
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "dataframe", derive(crate::ToDataFrame))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SectorPerformance {
    /// Year-to-date change percentage
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ytd_change_percent: Option<FormattedValue<f64>>,

    /// Regular market change percentage (today)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub day_change_percent: Option<FormattedValue<f64>>,

    /// One year change percentage
    #[serde(skip_serializing_if = "Option::is_none")]
    pub one_year_change_percent: Option<FormattedValue<f64>>,

    /// Three year change percentage
    #[serde(skip_serializing_if = "Option::is_none")]
    pub three_year_change_percent: Option<FormattedValue<f64>>,

    /// Five year change percentage
    #[serde(skip_serializing_if = "Option::is_none")]
    pub five_year_change_percent: Option<FormattedValue<f64>>,
}

/// A company in the sector's top companies list
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "dataframe", derive(crate::ToDataFrame))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SectorCompany {
    /// Stock symbol
    pub symbol: String,

    /// Company name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Market capitalization
    #[serde(skip_serializing_if = "Option::is_none")]
    pub market_cap: Option<FormattedValue<f64>>,

    /// Weight in sector (percentage)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub market_weight: Option<FormattedValue<f64>>,

    /// Last traded price
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_price: Option<FormattedValue<f64>>,

    /// Analyst target price
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_price: Option<FormattedValue<f64>>,

    /// Day change percentage
    #[serde(skip_serializing_if = "Option::is_none")]
    pub day_change_percent: Option<FormattedValue<f64>>,

    /// Year-to-date return
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ytd_return: Option<FormattedValue<f64>>,

    /// Analyst rating (e.g., "Strong Buy", "Buy", "Hold")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rating: Option<String>,
}

/// An ETF tracking the sector
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "dataframe", derive(crate::ToDataFrame))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SectorETF {
    /// ETF symbol
    pub symbol: String,

    /// ETF name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Net assets under management
    #[serde(skip_serializing_if = "Option::is_none")]
    pub net_assets: Option<FormattedValue<f64>>,

    /// Expense ratio
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expense_ratio: Option<FormattedValue<f64>>,

    /// Last traded price
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_price: Option<FormattedValue<f64>>,

    /// Year-to-date return
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ytd_return: Option<FormattedValue<f64>>,
}

/// A mutual fund in the sector
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "dataframe", derive(crate::ToDataFrame))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SectorMutualFund {
    /// Fund symbol
    pub symbol: String,

    /// Fund name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Net assets under management
    #[serde(skip_serializing_if = "Option::is_none")]
    pub net_assets: Option<FormattedValue<f64>>,

    /// Expense ratio
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expense_ratio: Option<FormattedValue<f64>>,

    /// Last traded price (NAV)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_price: Option<FormattedValue<f64>>,

    /// Year-to-date return
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ytd_return: Option<FormattedValue<f64>>,
}

/// An industry within the sector
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "dataframe", derive(crate::ToDataFrame))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SectorIndustry {
    /// Industry symbol
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,

    /// Industry key for API calls
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,

    /// Industry name
    pub name: String,

    /// Weight in sector (percentage)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub market_weight: Option<FormattedValue<f64>>,

    /// Day change percentage
    #[serde(skip_serializing_if = "Option::is_none")]
    pub day_change_percent: Option<FormattedValue<f64>>,

    /// Year-to-date return
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ytd_return: Option<FormattedValue<f64>>,
}

/// A research report about the sector
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "dataframe", derive(crate::ToDataFrame))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ResearchReport {
    /// Report ID
    pub id: String,

    /// Report headline/summary (may contain HTML)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headline: Option<String>,

    /// Research provider (e.g., "Argus Research", "Morningstar")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,

    /// Report publication date (ISO 8601)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub report_date: Option<String>,

    /// Full report title
    #[serde(skip_serializing_if = "Option::is_none")]
    pub report_title: Option<String>,

    /// Report type (e.g., "Technical Analysis", "Analyst Report")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub report_type: Option<String>,

    /// Target price (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_price: Option<f64>,

    /// Target price status (e.g., "Maintained", "Raised")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_price_status: Option<String>,

    /// Investment rating (e.g., "Bullish", "Bearish")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub investment_rating: Option<String>,
}

// ============================================================================
// Conversion implementations
// ============================================================================

impl SectorData {
    /// Parse Yahoo Finance sector response JSON
    pub(crate) fn from_response(json: &serde_json::Value) -> Result<Self, String> {
        let raw: RawSectorResponse = serde_json::from_value(json.clone())
            .map_err(|e| format!("Failed to parse sector response: {}", e))?;

        let data = raw.data;

        // Convert overview
        let overview = data.overview.map(|o| SectorOverview {
            companies_count: o.companies_count,
            market_cap: o.market_cap,
            description: o.description,
            industries_count: o.industries_count,
            market_weight: o.market_weight,
            employee_count: o.employee_count,
        });

        // Convert performance
        let performance = data.performance.map(|p| SectorPerformance {
            ytd_change_percent: p.ytd_change_percent,
            day_change_percent: p.reg_market_change_percent,
            one_year_change_percent: p.one_year_change_percent,
            three_year_change_percent: p.three_year_change_percent,
            five_year_change_percent: p.five_year_change_percent,
        });

        // Convert benchmark
        let (benchmark, benchmark_name) = match data.performance_overview_benchmark {
            Some(b) => (
                Some(SectorPerformance {
                    ytd_change_percent: b.ytd_change_percent,
                    day_change_percent: b.reg_market_change_percent,
                    one_year_change_percent: b.one_year_change_percent,
                    three_year_change_percent: b.three_year_change_percent,
                    five_year_change_percent: b.five_year_change_percent,
                }),
                b.name,
            ),
            None => (None, None),
        };

        // Convert top companies
        let top_companies = data
            .top_companies
            .into_iter()
            .map(|c| SectorCompany {
                symbol: c.symbol,
                name: c.name,
                market_cap: c.market_cap,
                market_weight: c.market_weight,
                last_price: c.last_price,
                target_price: c.target_price,
                day_change_percent: c.reg_market_change_percent,
                ytd_return: c.ytd_return,
                rating: c.rating,
            })
            .collect();

        // Convert ETFs
        let top_etfs = data
            .top_etfs
            .into_iter()
            .map(|e| SectorETF {
                symbol: e.symbol,
                name: e.name,
                net_assets: e.net_assets,
                expense_ratio: e.expense_ratio,
                last_price: e.last_price,
                ytd_return: e.ytd_return,
            })
            .collect();

        // Convert mutual funds
        let top_mutual_funds = data
            .top_mutual_funds
            .into_iter()
            .map(|f| SectorMutualFund {
                symbol: f.symbol,
                name: f.name,
                net_assets: f.net_assets,
                expense_ratio: f.expense_ratio,
                last_price: f.last_price,
                ytd_return: f.ytd_return,
            })
            .collect();

        // Convert industries
        let industries = data
            .industries
            .into_iter()
            .map(|i| SectorIndustry {
                symbol: i.symbol,
                key: i.key,
                name: i.name,
                market_weight: i.market_weight,
                day_change_percent: i.reg_market_change_percent,
                ytd_return: i.ytd_return,
            })
            .collect();

        // Convert research reports
        let research_reports = data
            .research_reports
            .into_iter()
            .map(|r| ResearchReport {
                id: r.id,
                headline: r.head_html,
                provider: r.provider,
                report_date: r.report_date,
                report_title: r.report_title,
                report_type: r.report_type,
                target_price: r.target_price,
                target_price_status: r.target_price_status,
                investment_rating: r.investment_rating,
            })
            .collect();

        Ok(Self {
            name: data.name,
            symbol: data.symbol,
            key: data.key,
            overview,
            performance,
            benchmark,
            benchmark_name,
            top_companies,
            top_etfs,
            top_mutual_funds,
            industries,
            research_reports,
        })
    }
}