marketsurge-agent 0.3.0

Unofficial agent-oriented CLI for MarketSurge data
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
//! Industry group data commands.

use clap::Subcommand;
use serde::Serialize;
use tracing::instrument;

use marketsurge_client::industry::{IndustryGroupRsItem, IndustryOverviewItem};

use crate::cli::{IndustryArgs, SymbolsArgs};
use crate::common::command::{api_call, run_command, zip_symbols};

/// Industry subcommands.
#[derive(Debug, Subcommand)]
pub enum IndustryCommand {
    /// Fetch industry group relative strength ratings for symbols.
    #[command(after_help = "Examples:\n  marketsurge-agent industry rs AAPL MSFT")]
    Rs(SymbolsArgs),
    /// Fetch industry rankings, sector, and breadth data for symbols.
    #[command(after_help = "Examples:\n  marketsurge-agent industry overview AAPL MSFT")]
    Overview(SymbolsArgs),
}

/// Flat output record for industry group relative strength.
#[derive(Debug, Clone, Serialize)]
pub struct IndustryRsRecord {
    /// Ticker symbol.
    pub symbol: String,
    /// Industry group RS value (6-month current).
    pub group_rs: Option<i64>,
}

/// Flat output record for industry overview data.
#[derive(Debug, Clone, Serialize)]
pub struct IndustryOverviewRecord {
    /// Requested ticker symbol.
    pub ticker: String,
    /// MarketSurge industry identifier returned by the API.
    pub industry_id: String,
    /// Industry group name.
    pub name: Option<String>,
    /// Sector name.
    pub sector: Option<String>,
    /// Numeric industry code.
    pub ind_code: Option<i64>,
    /// Group market value in billions (formatted).
    pub group_market_value_billions: Option<String>,
    /// Number of stocks at new highs in the group.
    pub num_new_highs: Option<i64>,
    /// Number of stocks at new lows in the group.
    pub num_new_lows: Option<i64>,
    /// Total number of stocks in the group.
    pub num_stocks: Option<i64>,
    /// Current group rank.
    pub group_rank: Option<i64>,
    /// Price percent change vs 1 day ago (formatted).
    pub pct_change_1d: Option<String>,
    /// Price percent change year-to-date (formatted).
    pub pct_change_ytd: Option<String>,
    /// EPS rank within industry group.
    pub eps_rank: Option<i64>,
    /// RS rank within industry group.
    pub rs_rank: Option<i64>,
    /// Accumulation/Distribution rank within industry group.
    pub ad_rank: Option<i64>,
    /// SMR rank within industry group.
    pub smr_rank: Option<i64>,
    /// Composite rank within industry group.
    pub comp_rank: Option<i64>,
}

/// Handles the industry command group.
#[instrument(skip_all)]
#[cfg(not(coverage))]
pub async fn handle(args: &IndustryArgs, fields: &[String]) -> i32 {
    match &args.command {
        IndustryCommand::Rs(a) => execute_rs(a, fields).await,
        IndustryCommand::Overview(a) => execute_overview(a, fields).await,
    }
}

/// Transforms raw industry group RS response items into flat output records.
fn flatten_industry_rs(
    symbols: &[&str],
    market_data: &[IndustryGroupRsItem],
) -> Vec<IndustryRsRecord> {
    zip_symbols(symbols, market_data)
        .map(|(symbol, item)| {
            let group_rs = item
                .industry
                .as_ref()
                .and_then(|ind| ind.group_rs.first())
                .and_then(|v| v.value);

            IndustryRsRecord {
                symbol: symbol.to_string(),
                group_rs,
            }
        })
        .collect()
}

#[instrument(skip_all)]
#[cfg(not(coverage))]
async fn execute_rs(args: &SymbolsArgs, fields: &[String]) -> i32 {
    run_command(&args.symbols, fields, |client, symbol_refs| async move {
        let response = api_call(client.industry_group_rs(&symbol_refs, None)).await?;

        Ok(flatten_industry_rs(&symbol_refs, &response.market_data))
    })
    .await
}

/// Transforms raw industry overview response items into flat output records.
fn flatten_industry_overview(
    symbols: &[&str],
    market_data: &[IndustryOverviewItem],
) -> Vec<IndustryOverviewRecord> {
    zip_symbols(symbols, market_data)
        .map(|(symbol, item)| {
            let industry_id = item.id.clone().unwrap_or_default();
            let industry = item.industry.as_ref();
            let ratings = item.ratings.as_ref();
            let rank = ratings.and_then(|r| r.industry.as_ref());

            let group_rank = industry
                .map(|ind| ind.group_ranks.as_slice())
                .unwrap_or_default()
                .first()
                .and_then(|r| r.value);

            let pct_change_1d = industry
                .map(|ind| ind.price_percent_change_vs.as_slice())
                .unwrap_or_default()
                .iter()
                .find(|v| v.subject.as_deref() == Some("VS_1D_AGO"))
                .and_then(|v| v.formatted_value.clone());

            let pct_change_ytd = industry
                .map(|ind| ind.price_percent_change_vs.as_slice())
                .unwrap_or_default()
                .iter()
                .find(|v| v.subject.as_deref() == Some("VS_YTD"))
                .and_then(|v| v.formatted_value.clone());

            IndustryOverviewRecord {
                ticker: symbol.to_string(),
                industry_id,
                name: industry.and_then(|i| i.name.clone()),
                sector: industry.and_then(|i| i.sector.clone()),
                ind_code: industry.and_then(|i| i.ind_code),
                group_market_value_billions: industry
                    .and_then(|i| i.group_market_value_in_billions.as_ref())
                    .and_then(|v| v.formatted_value.clone()),
                num_new_highs: industry.and_then(|i| i.num_new_highs_in_group),
                num_new_lows: industry.and_then(|i| i.num_new_lows_in_group),
                num_stocks: industry.and_then(|i| i.number_of_stocks_in_group),
                group_rank,
                pct_change_1d,
                pct_change_ytd,
                eps_rank: rank.and_then(|r| r.eps_rank_in_industry_group),
                rs_rank: rank.and_then(|r| r.rs_rank_in_industry_group),
                ad_rank: rank.and_then(|r| r.ad_rank_in_industry_group),
                smr_rank: rank.and_then(|r| r.smr_rank_in_industry_group),
                comp_rank: rank.and_then(|r| r.comp_rank_in_industry_group),
            }
        })
        .collect()
}

#[instrument(skip_all)]
#[cfg(not(coverage))]
async fn execute_overview(args: &SymbolsArgs, fields: &[String]) -> i32 {
    run_command(&args.symbols, fields, |client, symbol_refs| async move {
        let response = api_call(client.industry_overview(&symbol_refs, None)).await?;

        Ok(flatten_industry_overview(
            &symbol_refs,
            &response.market_data,
        ))
    })
    .await
}

#[cfg(test)]
mod tests {
    use super::*;
    use marketsurge_client::industry::{
        IndustryGroupRsIndustry, IndustryGroupRsValue, IndustryOverviewIndustry,
        IndustryOverviewRatings, IndustryRankInGroup,
    };
    use marketsurge_client::market_data::{MdGroupRank, MdPercentChangeVs};
    use marketsurge_client::types::FormattedFloat;

    // -----------------------------------------------------------------------
    // flatten_industry_rs
    // -----------------------------------------------------------------------

    #[test]
    fn flatten_industry_rs_happy_path() {
        let items = vec![
            IndustryGroupRsItem {
                origin_request: None,
                industry: Some(IndustryGroupRsIndustry {
                    group_rs: vec![IndustryGroupRsValue { value: Some(85) }],
                }),
            },
            IndustryGroupRsItem {
                origin_request: None,
                industry: Some(IndustryGroupRsIndustry {
                    group_rs: vec![IndustryGroupRsValue { value: Some(42) }],
                }),
            },
        ];
        let symbols = ["AAPL", "MSFT"];

        let records = flatten_industry_rs(&symbols, &items);

        assert_eq!(records.len(), 2);
        assert_eq!(records[0].symbol, "AAPL");
        assert_eq!(records[0].group_rs, Some(85));
        assert_eq!(records[1].symbol, "MSFT");
        assert_eq!(records[1].group_rs, Some(42));
    }

    #[test]
    fn flatten_industry_rs_empty_market_data() {
        let records = flatten_industry_rs(&["AAPL"], &[]);
        assert!(records.is_empty());
    }

    #[test]
    fn flatten_industry_rs_none_industry() {
        let items = vec![IndustryGroupRsItem {
            origin_request: None,
            industry: None,
        }];

        let records = flatten_industry_rs(&["AAPL"], &items);

        assert_eq!(records.len(), 1);
        assert_eq!(records[0].symbol, "AAPL");
        assert_eq!(records[0].group_rs, None);
    }

    // -----------------------------------------------------------------------
    // flatten_industry_overview
    // -----------------------------------------------------------------------

    #[test]
    fn flatten_industry_overview_happy_path() {
        let items = vec![IndustryOverviewItem {
            id: Some("13-4698".to_string()),
            industry: Some(IndustryOverviewIndustry {
                name: Some("Elec-Semicondctor Fablss".to_string()),
                ind_code: Some(7010),
                news_code: Some("I/SEMF".to_string()),
                sector: Some("CHIPS".to_string()),
                group_market_value_in_billions: None,
                num_new_highs_in_group: Some(1),
                num_new_lows_in_group: Some(0),
                number_of_stocks_in_group: Some(45),
                group_ranks: vec![MdGroupRank {
                    value: Some(16),
                    period: Some("P6M".to_string()),
                    period_offset: Some("CURRENT".to_string()),
                }],
                price_percent_change_vs: vec![
                    MdPercentChangeVs {
                        value: None,
                        formatted_value: Some("-1.22%".to_string()),
                        subject: Some("VS_1D_AGO".to_string()),
                        period: None,
                    },
                    MdPercentChangeVs {
                        value: None,
                        formatted_value: Some("27.07%".to_string()),
                        subject: Some("VS_YTD".to_string()),
                        period: None,
                    },
                ],
            }),
            ratings: Some(IndustryOverviewRatings {
                has_ratings_data: Some(true),
                industry: Some(IndustryRankInGroup {
                    ad_rank_in_industry_group: Some(10),
                    comp_rank_in_industry_group: Some(1),
                    eps_rank_in_industry_group: Some(4),
                    number_of_stocks_in_group: Some(45),
                    rs_rank_in_industry_group: Some(2),
                    smr_rank_in_industry_group: Some(8),
                }),
            }),
        }];

        let records = flatten_industry_overview(&["AAPL"], &items);

        assert_eq!(records.len(), 1);
        let r = &records[0];
        assert_eq!(r.ticker, "AAPL");
        assert_eq!(r.industry_id, "13-4698");
        assert_eq!(r.name.as_deref(), Some("Elec-Semicondctor Fablss"));
        assert_eq!(r.sector.as_deref(), Some("CHIPS"));
        assert_eq!(r.ind_code, Some(7010));
        assert_eq!(r.num_stocks, Some(45));
        assert_eq!(r.group_rank, Some(16));
        assert_eq!(r.pct_change_1d.as_deref(), Some("-1.22%"));
        assert_eq!(r.pct_change_ytd.as_deref(), Some("27.07%"));
        assert_eq!(r.eps_rank, Some(4));
        assert_eq!(r.rs_rank, Some(2));
        assert_eq!(r.comp_rank, Some(1));
    }

    #[test]
    fn flatten_industry_overview_empty_market_data() {
        let records = flatten_industry_overview(&[], &[]);
        assert!(records.is_empty());
    }

    #[test]
    fn flatten_industry_overview_none_fields() {
        let items = vec![IndustryOverviewItem {
            id: None,
            industry: None,
            ratings: None,
        }];

        let records = flatten_industry_overview(&["AAPL"], &items);

        assert_eq!(records.len(), 1);
        let r = &records[0];
        assert_eq!(r.ticker, "AAPL");
        assert_eq!(r.industry_id, "");
        assert!(r.name.is_none());
        assert!(r.sector.is_none());
        assert!(r.group_rank.is_none());
        assert!(r.pct_change_1d.is_none());
        assert!(r.pct_change_ytd.is_none());
        assert!(r.eps_rank.is_none());
    }

    #[test]
    fn flatten_industry_overview_subject_filter() {
        // Only VS_YTD present, no VS_1D_AGO - verifies the .find() filter
        let items = vec![IndustryOverviewItem {
            id: Some("TEST".to_string()),
            industry: Some(IndustryOverviewIndustry {
                name: None,
                ind_code: None,
                news_code: None,
                sector: None,
                group_market_value_in_billions: None,
                num_new_highs_in_group: None,
                num_new_lows_in_group: None,
                number_of_stocks_in_group: None,
                group_ranks: vec![],
                price_percent_change_vs: vec![MdPercentChangeVs {
                    value: None,
                    formatted_value: Some("15.00%".to_string()),
                    subject: Some("VS_YTD".to_string()),
                    period: None,
                }],
            }),
            ratings: None,
        }];

        let records = flatten_industry_overview(&["TEST"], &items);

        assert_eq!(records.len(), 1);
        assert!(records[0].pct_change_1d.is_none());
        assert_eq!(records[0].pct_change_ytd.as_deref(), Some("15.00%"));
    }

    #[test]
    fn flatten_industry_overview_keeps_market_value_with_missing_rank_details() {
        let items = vec![IndustryOverviewItem {
            id: Some("13-4698".to_string()),
            industry: Some(IndustryOverviewIndustry {
                name: None,
                ind_code: None,
                news_code: None,
                sector: None,
                group_market_value_in_billions: Some(FormattedFloat {
                    value: Some(12.34),
                    formatted_value: Some("$12.34B".to_string()),
                }),
                num_new_highs_in_group: Some(3),
                num_new_lows_in_group: Some(1),
                number_of_stocks_in_group: Some(45),
                group_ranks: vec![],
                price_percent_change_vs: vec![],
            }),
            ratings: Some(IndustryOverviewRatings {
                has_ratings_data: Some(false),
                industry: None,
            }),
        }];

        let records = flatten_industry_overview(&["AAPL", "EXTRA"], &items);

        assert_eq!(records.len(), 1);
        let r = &records[0];
        assert_eq!(r.ticker, "AAPL");
        assert_eq!(r.industry_id, "13-4698");
        assert_eq!(r.group_market_value_billions.as_deref(), Some("$12.34B"));
        assert_eq!(r.num_new_highs, Some(3));
        assert_eq!(r.num_new_lows, Some(1));
        assert_eq!(r.num_stocks, Some(45));
        assert!(r.group_rank.is_none());
        assert!(r.eps_rank.is_none());
        assert!(r.comp_rank.is_none());
    }
}