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
//! Watchlist data commands.

use clap::{Args, Subcommand};
use marketsurge_client::watchlist::{WatchlistDetail, WatchlistSummary};
use serde::Serialize;
use tracing::instrument;

use crate::cli::WatchlistArgs;
use crate::common::command::{api_call, run_client_command, run_command};
use crate::common::rows::{flatten_response_rows, response_columns};

/// Watchlist subcommands.
#[derive(Debug, Subcommand)]
pub enum WatchlistCommand {
    /// List saved watchlists.
    #[command(
        after_help = "Examples:\n  marketsurge-agent watchlist list\n  marketsurge-agent watchlist list --query ibd"
    )]
    List(WatchlistListArgs),
    /// Fetch symbols in a watchlist by ID.
    #[command(after_help = "Examples:\n  marketsurge-agent watchlist symbols 12345")]
    Symbols(WatchlistSymbolsArgs),
    /// Screen symbols with selected MarketSurge data columns.
    #[command(
        after_help = "Examples:\n  marketsurge-agent watchlist screen AAPL MSFT\n  marketsurge-agent watchlist screen AAPL --columns Symbol,EPSRating,RSRating"
    )]
    Screen(WatchlistScreenArgs),
}

/// Arguments for the watchlist list subcommand.
#[derive(Debug, Args)]
pub struct WatchlistListArgs {
    /// Filter watchlists by ID, name, or description.
    #[arg(long, short)]
    pub query: Option<String>,
}

/// Arguments for the watchlist symbols subcommand.
#[derive(Debug, Args)]
pub struct WatchlistSymbolsArgs {
    /// Watchlist ID from `watchlist list`.
    pub watchlist_id: String,
}

/// Arguments for the watchlist screen subcommand.
#[derive(Debug, Args)]
pub struct WatchlistScreenArgs {
    /// Symbols to screen, for example AAPL MSFT.
    #[arg(required = true)]
    pub symbols: Vec<String>,

    /// Output columns, comma-separated.
    #[arg(
        long,
        value_delimiter = ',',
        default_value = "EPSRating,RSRating,AccDisRating,CompRating,SMRRating"
    )]
    pub columns: Vec<String>,
}

/// Flat output record for a watchlist listing entry.
#[derive(Debug, Clone, Serialize)]
pub struct WatchlistRecord {
    /// Watchlist identifier.
    pub id: Option<String>,
    /// Watchlist name.
    pub name: Option<String>,
    /// Last modified timestamp in UTC.
    pub last_modified: Option<String>,
    /// Watchlist description.
    pub description: Option<String>,
}

/// Flat output record for a watchlist symbol.
#[derive(Debug, Clone, Serialize)]
pub struct WatchlistSymbolRecord {
    /// Watchlist identifier.
    pub watchlist_id: Option<String>,
    /// Watchlist name.
    pub watchlist_name: Option<String>,
    /// Symbol key (e.g. "AAPL").
    pub key: Option<String>,
    /// Dow Jones symbol key (e.g. "US:AAPL").
    pub dow_jones_key: Option<String>,
}

/// Handles the watchlist command group.
#[instrument(skip_all)]
#[cfg(not(coverage))]
pub async fn handle(args: &WatchlistArgs, fields: &[String]) -> i32 {
    match &args.command {
        WatchlistCommand::List(a) => execute_list(a, fields).await,
        WatchlistCommand::Symbols(a) => execute_symbols(a, fields).await,
        WatchlistCommand::Screen(a) => execute_screen(a, fields).await,
    }
}

/// Converts watchlist summaries into flat output records.
fn flatten_watchlist_list(watchlists: &[WatchlistSummary]) -> Vec<WatchlistRecord> {
    watchlists
        .iter()
        .map(|wl| WatchlistRecord {
            id: wl.id.clone(),
            name: wl.name.clone(),
            last_modified: wl.last_modified_date_utc.clone(),
            description: wl.description.clone(),
        })
        .collect()
}

fn filter_watchlist_list(
    records: Vec<WatchlistRecord>,
    normalized_query: Option<&str>,
) -> Vec<WatchlistRecord> {
    let Some(normalized_query) = normalized_query else {
        return records;
    };

    records
        .into_iter()
        .filter(|record| watchlist_record_matches(record, normalized_query))
        .collect()
}

fn normalized_watchlist_query(query: Option<&str>) -> Option<String> {
    query
        .map(normalized_watchlist_name)
        .filter(|query| !query.is_empty())
}

fn watchlist_record_matches(record: &WatchlistRecord, normalized_query: &str) -> bool {
    [
        record.id.as_deref(),
        record.name.as_deref(),
        record.description.as_deref(),
    ]
    .into_iter()
    .flatten()
    .any(|value| normalized_watchlist_name(value).contains(normalized_query))
}

fn normalized_watchlist_name(name: &str) -> String {
    name.chars()
        .filter(|ch| ch.is_ascii_alphanumeric())
        .flat_map(char::to_lowercase)
        .collect()
}

#[instrument(skip_all)]
#[cfg(not(coverage))]
async fn execute_list(args: &WatchlistListArgs, fields: &[String]) -> i32 {
    let query = normalized_watchlist_query(args.query.as_deref());

    run_client_command(fields, |client| async move {
        let response = api_call(client.get_all_watchlist_names()).await?;

        Ok(filter_watchlist_list(
            flatten_watchlist_list(&response.watchlists),
            query.as_deref(),
        ))
    })
    .await
}

/// Extracts symbol records from an optional watchlist detail.
fn flatten_watchlist_symbols(watchlist: Option<&WatchlistDetail>) -> Vec<WatchlistSymbolRecord> {
    watchlist
        .map(|wl| {
            wl.items
                .iter()
                .map(|item| WatchlistSymbolRecord {
                    watchlist_id: wl.id.clone(),
                    watchlist_name: wl.name.clone(),
                    key: item.key.clone(),
                    dow_jones_key: item.dow_jones_key.clone(),
                })
                .collect()
        })
        .unwrap_or_default()
}

#[instrument(skip_all)]
#[cfg(not(coverage))]
async fn execute_symbols(args: &WatchlistSymbolsArgs, fields: &[String]) -> i32 {
    let watchlist_id = args.watchlist_id.clone();

    run_client_command(fields, |client| async move {
        let response = api_call(client.flagged_symbols(&watchlist_id)).await?;

        Ok(flatten_watchlist_symbols(response.watchlist.as_ref()))
    })
    .await
}

#[instrument(skip_all)]
#[cfg(not(coverage))]
async fn execute_screen(args: &WatchlistScreenArgs, fields: &[String]) -> i32 {
    let columns = response_columns(&args.columns);

    run_command(&args.symbols, fields, |client, symbol_refs| async move {
        let response = api_call(client.screener_watchlist_items(&symbol_refs, columns)).await?;

        let empty = Vec::new();
        let rows = response
            .market_data_adhoc_screen
            .as_ref()
            .map(|result| &result.response_values)
            .unwrap_or(&empty);

        Ok(flatten_response_rows(rows))
    })
    .await
}

#[cfg(test)]
mod tests {
    use crate::common::test_support::{response_value, response_value_without_md_item};
    use marketsurge_client::watchlist::WatchlistItem;

    use super::*;

    #[test]
    fn flatten_list_maps_fields() {
        let summaries = vec![WatchlistSummary {
            id: Some("1".into()),
            name: Some("Growth".into()),
            last_modified_date_utc: Some("2025-01-01T00:00:00Z".into()),
            description: Some("Top picks".into()),
        }];

        let records = flatten_watchlist_list(&summaries);

        assert_eq!(records.len(), 1);
        assert_eq!(records[0].id.as_deref(), Some("1"));
        assert_eq!(records[0].name.as_deref(), Some("Growth"));
        assert_eq!(
            records[0].last_modified.as_deref(),
            Some("2025-01-01T00:00:00Z")
        );
        assert_eq!(records[0].description.as_deref(), Some("Top picks"));
    }

    #[test]
    fn flatten_list_empty() {
        let records = flatten_watchlist_list(&[]);
        assert!(records.is_empty());
    }

    #[test]
    fn filter_list_matches_name_without_punctuation() {
        let records = flatten_watchlist_list(&[
            WatchlistSummary {
                id: Some("1".into()),
                name: Some("EF-50".into()),
                last_modified_date_utc: None,
                description: None,
            },
            WatchlistSummary {
                id: Some("2".into()),
                name: Some("IBD 50".into()),
                last_modified_date_utc: None,
                description: None,
            },
        ]);

        let filtered = filter_watchlist_list(records, Some("ibd50"));

        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].id.as_deref(), Some("2"));
    }

    #[test]
    fn filter_list_matches_description() {
        let records = flatten_watchlist_list(&[WatchlistSummary {
            id: Some("1".into()),
            name: Some("Growth".into()),
            last_modified_date_utc: None,
            description: Some("IBD leaders".into()),
        }]);

        let filtered = filter_watchlist_list(records, Some("ibd"));

        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].id.as_deref(), Some("1"));
    }

    #[test]
    fn filter_list_matches_id() {
        let records = flatten_watchlist_list(&[WatchlistSummary {
            id: Some("watchlist-ibd-50".into()),
            name: Some("Growth".into()),
            last_modified_date_utc: None,
            description: None,
        }]);

        let filtered = filter_watchlist_list(records, Some("ibd50"));

        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].id.as_deref(), Some("watchlist-ibd-50"));
    }

    #[test]
    fn filter_list_without_query_returns_all_records() {
        let records = flatten_watchlist_list(&[WatchlistSummary {
            id: Some("1".into()),
            name: Some("Growth".into()),
            last_modified_date_utc: None,
            description: None,
        }]);

        let filtered = filter_watchlist_list(records, None);

        assert_eq!(filtered.len(), 1);
    }

    #[test]
    fn normalized_watchlist_query_ignores_empty_normalized_query() {
        assert_eq!(normalized_watchlist_query(Some(" -- ")), None);
        assert_eq!(
            normalized_watchlist_query(Some("IBD 50")).as_deref(),
            Some("ibd50")
        );
    }

    #[test]
    fn flatten_symbols_maps_fields() {
        let detail = WatchlistDetail {
            id: Some("42".into()),
            name: Some("Tech".into()),
            last_modified_date_utc: None,
            description: None,
            items: vec![
                WatchlistItem {
                    key: Some("AAPL".into()),
                    dow_jones_key: Some("US:AAPL".into()),
                },
                WatchlistItem {
                    key: Some("MSFT".into()),
                    dow_jones_key: Some("US:MSFT".into()),
                },
            ],
        };

        let records = flatten_watchlist_symbols(Some(&detail));

        assert_eq!(records.len(), 2);
        assert_eq!(records[0].watchlist_id.as_deref(), Some("42"));
        assert_eq!(records[0].watchlist_name.as_deref(), Some("Tech"));
        assert_eq!(records[0].key.as_deref(), Some("AAPL"));
        assert_eq!(records[1].key.as_deref(), Some("MSFT"));
        assert_eq!(records[1].dow_jones_key.as_deref(), Some("US:MSFT"));
    }

    #[test]
    fn flatten_symbols_none_returns_empty() {
        let records = flatten_watchlist_symbols(None);
        assert!(records.is_empty());
    }

    #[test]
    fn flatten_screen_maps_named_cells() {
        let rows = vec![vec![
            response_value("EPSRating", Some("95")),
            response_value("RSRating", Some("88")),
        ]];

        let records = flatten_response_rows(&rows);

        assert_eq!(records.len(), 1);
        assert_eq!(records[0].get("EPSRating"), Some(&Some("95".into())));
        assert_eq!(records[0].get("RSRating"), Some(&Some("88".into())));
    }

    #[test]
    fn flatten_screen_empty_rows() {
        let records = flatten_response_rows(&[]);
        assert!(records.is_empty());
    }

    #[test]
    fn flatten_screen_skips_missing_md_item() {
        let rows = vec![vec![
            response_value_without_md_item(Some("99")),
            response_value("SMRRating", Some("A")),
        ]];

        let records = flatten_response_rows(&rows);

        assert_eq!(records.len(), 1);
        assert_eq!(records[0].len(), 1);
        assert_eq!(records[0].get("SMRRating"), Some(&Some("A".into())));
    }

    #[test]
    fn flatten_screen_none_value_preserved() {
        let rows = vec![vec![response_value("CompRating", None)]];

        let records = flatten_response_rows(&rows);

        assert_eq!(records.len(), 1);
        assert_eq!(records[0].get("CompRating"), Some(&None));
    }
}