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
//! Module for stock time series
//!
//! This suite of APIs provide realtime and historical global equity data in 4
//! different temporal resolutions: (1) daily, (2) weekly, (3) monthly, and (4)
//! intraday. Daily, weekly, and monthly time series contain 20+ years of
//! historical data
//!
//! You can read about [Stock Time][stock_time] API and what it returns
//! on alphavantage documentation
//!
//! [stock_time]: https://www.alphavantage.co/documentation/#time-series-data

use crate::{
    user::APIKey,
    util::{Interval, OutputSize, StockFunction},
};
use reqwest::Url;
use serde_derive::Deserialize;
use std::collections::HashMap;

const LINK: &str = "https://www.alphavantage.co/query?function=";

/// Struct for storing time series data
#[derive(Debug, Default)]
pub struct TimeSeries {
    error_message: Option<String>,
    information: Option<String>,
    meta_data: Option<MetaData>,
    entry: Option<Vec<Entry>>,
}

impl TimeSeries {
    /// Return information present in meta data
    ///
    /// ```
    /// use alpha_vantage::util::*;
    /// let api = alpha_vantage::set_api("demo");
    /// let stock_time = api.stock_time(
    ///     StockFunction::IntraDay,
    ///     "MSFT",
    ///     Interval::FiveMin,
    ///     OutputSize::Full,
    /// );
    /// let information = stock_time.information();
    /// assert_eq!(
    ///     information.unwrap(),
    ///     "Intraday (5min) open, high, low, close prices and volume"
    /// );
    /// ```
    pub fn information(&self) -> Result<String, String> {
        self.return_meta_string("information")
    }

    /// Return symbol for which time series function is called
    ///
    /// ```
    /// use alpha_vantage::util::*;
    /// let api = alpha_vantage::set_api("demo");
    /// let stock_time = api.stock_time(
    ///     StockFunction::IntraDay,
    ///     "MSFT",
    ///     Interval::FiveMin,
    ///     OutputSize::Full,
    /// );
    /// let symbol = stock_time.symbol();
    /// assert_eq!(symbol.unwrap(), "MSFT");
    /// ```
    pub fn symbol(&self) -> Result<String, String> {
        self.return_meta_string("symbol")
    }

    /// last time a data was refreshed with time zone
    pub fn last_refreshed(&self) -> Result<String, String> {
        if let Some(meta) = &self.meta_data {
            Ok(format!("{} {}", meta.last_refreshed, meta.time_zone))
        } else if let Some(error) = &self.error_message {
            Err(format!("Error Message : {}", error))
        } else {
            Err(format!(
                "Information : {}",
                self.information.clone().unwrap()
            ))
        }
    }

    /// Interval for which a time series intraday
    ///
    /// ```
    /// use alpha_vantage::util::*;
    /// let api = alpha_vantage::set_api("demo");
    /// let stock_time = api.stock_time(
    ///     StockFunction::IntraDay,
    ///     "MSFT",
    ///     Interval::FiveMin,
    ///     OutputSize::Full,
    /// );
    /// let interval = stock_time.interval();
    /// assert_eq!(interval.unwrap(), "5min");
    /// ```
    pub fn interval(&self) -> Result<String, String> {
        self.operate_option_meta_value("interval")
    }

    /// Output Size of intraday which can be either Full or compact
    ///
    /// ```
    /// use alpha_vantage::util::*;
    /// let api = alpha_vantage::set_api("demo");
    /// let stock_time = api.stock_time(
    ///     StockFunction::IntraDay,
    ///     "MSFT",
    ///     Interval::FiveMin,
    ///     OutputSize::Full,
    /// );
    /// let output_size = stock_time.output_size();
    /// assert_eq!(output_size.unwrap(), "Full size");
    /// ```
    pub fn output_size(&self) -> Result<String, String> {
        self.operate_option_meta_value("output size")
    }

    /// Return Entry
    pub fn entry(&self) -> Result<Vec<Entry>, String> {
        if let Some(entry) = &self.entry {
            Ok(entry.to_vec())
        } else if let Some(error) = &self.error_message {
            Err(format!("Error Message : {}", error))
        } else {
            Err(format!(
                "Information : {}",
                self.information.clone().unwrap()
            ))
        }
    }

    /// Return a meta data value as a form of String
    fn return_meta_string(&self, which_val: &str) -> Result<String, String> {
        if let Some(meta_data) = &self.meta_data {
            let value = match which_val {
                "information" => &meta_data.information,
                "symbol" => &meta_data.symbol,
                _ => "",
            };
            Ok(value.to_string())
        } else if let Some(error) = &self.error_message {
            Err(format!("Error Message : {}", error))
        } else {
            Err(format!(
                "Information : {}",
                self.information.clone().unwrap()
            ))
        }
    }

    /// Return Option metadata value as a Result form of String
    fn operate_option_meta_value(&self, which_val: &str) -> Result<String, String> {
        if let Some(meta_data) = &self.meta_data {
            if let Some(value) = match which_val {
                "interval" => &meta_data.interval,
                "output size" => &meta_data.output_size,
                _ => &None,
            } {
                Ok(value.to_string())
            } else {
                Err("No value present".to_string())
            }
        } else if let Some(error) = &self.error_message {
            Err(format!("Error Message : {}", error))
        } else {
            Err(format!(
                "Information : {}",
                self.information.clone().unwrap()
            ))
        }
    }
}

/// Struct for storing Meta Data value
#[derive(Debug, Clone)]
pub struct MetaData {
    information: String,
    symbol: String,
    last_refreshed: String,
    interval: Option<String>,
    output_size: Option<String>,
    time_zone: String,
}

/// Struct for Entry value
#[derive(Default, Debug, Clone)]
pub struct Entry {
    time: String,
    open: String,
    high: String,
    low: String,
    close: String,
    adjusted_close: Option<String>,
    volume: String,
    dividend_amount: Option<String>,
    split_coefficient: Option<String>,
}

impl Entry {
    /// Get time
    pub fn time(&self) -> String {
        self.time.to_string()
    }

    /// Return open
    pub fn open(&self) -> f64 {
        return_f64(self.open.as_str())
    }

    /// Return high
    pub fn high(&self) -> f64 {
        return_f64(self.high.as_str())
    }

    /// Return low
    pub fn low(&self) -> f64 {
        return_f64(self.low.as_str())
    }

    /// Return close
    pub fn close(&self) -> f64 {
        return_f64(self.close.as_str())
    }

    /// Return adjusted
    pub fn adjusted(&self) -> Option<f64> {
        if let Some(data) = &self.adjusted_close {
            return Some(return_f64(&data));
        }
        None
    }

    /// Return volume
    pub fn volume(&self) -> f64 {
        return_f64(self.volume.as_str())
    }

    /// Return dividend
    pub fn dividend(&self) -> Option<f64> {
        if let Some(data) = &self.dividend_amount {
            return Some(return_f64(&data));
        }
        None
    }

    /// Return split dividend
    pub fn split(&self) -> Option<f64> {
        if let Some(data) = &self.split_coefficient {
            return Some(return_f64(&data));
        }
        None
    }
}

/// parse String to f64 and return value
fn return_f64(data: &str) -> f64 {
    data.trim().parse::<f64>().unwrap()
}

/// Helper struct to store non adjusted data
#[derive(Clone, Deserialize)]
struct EntryHelper {
    #[serde(rename = "1. open")]
    open: String,
    #[serde(rename = "2. high")]
    high: String,
    #[serde(rename = "3. low")]
    low: String,
    #[serde(rename = "4. close")]
    close: String,
    #[serde(rename = "5. volume")]
    volume: String,
}

/// Helper struct to store adjusted data
#[derive(Deserialize, Clone)]
struct AdjustedHelper {
    #[serde(rename = "1. open")]
    open: String,
    #[serde(rename = "2. high")]
    high: String,
    #[serde(rename = "3. low")]
    low: String,
    #[serde(rename = "4. close")]
    close: String,
    #[serde(rename = "5. adjusted close")]
    adjusted_close: Option<String>,
    #[serde(rename = "6. volume")]
    volume: String,
    #[serde(rename = "7. dividend amount")]
    dividend_amount: Option<String>,
    #[serde(rename = "8. split coefficient")]
    split_coefficient: Option<String>,
}

/// helper struct for `TimeSeries` which deseialize JSON
#[derive(Deserialize)]
pub(crate) struct TimeSeriesHelper {
    #[serde(rename = "Error Message")]
    error_message: Option<String>,
    #[serde(rename = "Information")]
    information: Option<String>,
    #[serde(rename = "Meta Data")]
    meta_data: Option<HashMap<String, String>>,
    #[serde(flatten)]
    time_series: Option<HashMap<String, HashMap<String, EntryHelper>>>,
    #[serde(flatten)]
    adjusted_series: Option<HashMap<String, HashMap<String, AdjustedHelper>>>,
}

impl TimeSeriesHelper {
    /// Convert TimeSeriesHelper to TimeSeries
    pub(crate) fn convert(self) -> TimeSeries {
        let mut time_series = TimeSeries::default();
        time_series.error_message = self.error_message;
        time_series.information = self.information;
        if let Some(meta_data) = self.meta_data {
            let information = &meta_data["1. Information"];
            let symbol = &meta_data["2. Symbol"];
            let last_refreshed = &meta_data["3. Last Refreshed"];
            let interval = meta_data.get("4. Interval");
            let interval = return_value(interval);
            let output_size = meta_data.get("4. Output Size");
            let mut output_size_value = return_value(output_size);
            if output_size_value.is_none() {
                let output_size = meta_data.get("5. Output Size");
                output_size_value = return_value(output_size);
            }
            let time_zone = meta_data.get("4. Time Zone");
            let mut time_zone_value = return_value(time_zone);
            if time_zone_value.is_none() {
                let time_zone = meta_data.get("5. Time Zone");
                time_zone_value = return_value(time_zone)
            }
            if time_zone_value.is_none() {
                let time_zone = meta_data.get("6. Time Zone");
                time_zone_value = return_value(time_zone)
            }
            time_series.meta_data = Some(MetaData {
                information: information.to_string(),
                symbol: symbol.to_string(),
                last_refreshed: last_refreshed.to_string(),
                interval,
                output_size: output_size_value,
                time_zone: time_zone_value.unwrap(),
            });
        }
        let mut value: Vec<Entry> = Vec::new();
        if let Some(entry) = self.time_series {
            for hash in entry.values() {
                for val in hash.keys() {
                    let mut entry: Entry = Entry::default();
                    entry.time = val.to_string();
                    let entry_helper = hash.get(val).unwrap().clone();
                    entry.open = entry_helper.open;
                    entry.high = entry_helper.high;
                    entry.low = entry_helper.low;
                    entry.close = entry_helper.close;
                    entry.volume = entry_helper.volume;
                    value.push(entry);
                }
            }
        }
        if let Some(entry) = self.adjusted_series {
            for hash in entry.values() {
                for val in hash.keys() {
                    let mut entry: Entry = Entry::default();
                    entry.time = val.to_string();
                    let entry_helper = hash.get(val).unwrap().clone();
                    entry.open = entry_helper.open;
                    entry.high = entry_helper.high;
                    entry.low = entry_helper.low;
                    entry.close = entry_helper.close;
                    entry.volume = entry_helper.volume;
                    entry.adjusted_close = entry_helper.adjusted_close;
                    entry.split_coefficient = entry_helper.split_coefficient;
                    entry.dividend_amount = entry_helper.dividend_amount;
                    value.push(entry);
                }
            }
        }
        if !value.is_empty() {
            time_series.entry = Some(value);
        }
        time_series
    }
}

/// Convert Option<&String> to Option<String>
fn return_value(value: Option<&std::string::String>) -> Option<String> {
    match value {
        Some(value) => Some(value.to_string()),
        None => None,
    }
}

/// Function used to create a [TimeSeries][TimeSeries] struct.
///
/// Instead of using this function directly calling through [APIKey][APIKey]
/// method is recommended
pub fn stock_time(
    function: StockFunction,
    symbol: &str,
    interval: Interval,
    output_size: OutputSize,
    api_data: (&str, Option<u64>),
) -> TimeSeries {
    let api;
    if let Some(timeout) = api_data.1 {
        api = APIKey::set_with_timeout(api_data.0, timeout);
    } else {
        api = APIKey::set_api(api_data.0);
    }
    api.stock_time(function, symbol, interval, output_size)
}

/// create url from user provided data
pub(crate) fn create_url(
    function: StockFunction,
    symbol: &str,
    interval: Interval,
    output_size: OutputSize,
    api: &str,
) -> Url {
    let function = match function {
        StockFunction::IntraDay => "TIME_SERIES_INTRADAY",
        StockFunction::Daily => "TIME_SERIES_DAILY",
        StockFunction::DailyAdjusted => "TIME_SERIES_DAILY_ADJUSTED",
        StockFunction::Weekly => "TIME_SERIES_WEEKLY",
        StockFunction::WeeklyAdjusted => "TIME_SERIES_WEEKLY_ADJUSTED",
        StockFunction::Monthly => "TIME_SERIES_MONTHLY",
        StockFunction::MonthlyAdjusted => "TIME_SERIES_MONTHLY_ADJUSTED",
    };

    let mut url = format!("{}{}&symbol={}", LINK, function, symbol);
    let interval = match interval {
        Interval::OneMin => "1min",
        Interval::FiveMin => "5min",
        Interval::FifteenMin => "15min",
        Interval::ThirtyMin => "30min",
        Interval::SixtyMin => "60min",
        Interval::None => "",
    };

    if interval != "" {
        url.push_str(format!("&interval={}", interval).as_str());
    }

    url.push_str(match output_size {
        OutputSize::Full => "&outputsize=full",
        _ => "",
    });
    url.push_str(format!("&apikey={}", api).as_str());
    url.parse().unwrap()
}

#[cfg(test)]
mod test {
    use crate::util::*;
    use reqwest::Url;
    #[test]
    fn test_stock_time_create_url() {
        assert_eq!(
            super::create_url(
                StockFunction::Daily,
                "USD",
                Interval::None,
                OutputSize::None,
                "random"
            ),
            Url::parse(
                "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY\
                 &symbol=USD\
                 &apikey=random"
            )
            .unwrap()
        );
        assert_eq!(
            super::create_url(
                StockFunction::Weekly,
                "NPR",
                Interval::None,
                OutputSize::None,
                "random"
            ),
            Url::parse(
                "https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY\
                 &symbol=NPR\
                 &apikey=random"
            )
            .unwrap()
        );
        assert_eq!(
            super::create_url(
                StockFunction::Monthly,
                "NPR",
                Interval::None,
                OutputSize::None,
                "random"
            ),
            Url::parse(
                "https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY\
                 &symbol=NPR\
                 &apikey=random"
            )
            .unwrap()
        );
        assert_eq!(
            super::create_url(
                StockFunction::IntraDay,
                "MSFT",
                Interval::SixtyMin,
                OutputSize::Full,
                "random"
            ),
            Url::parse(
                "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY\
                 &symbol=MSFT\
                 &interval=60min\
                 &outputsize=full\
                 &apikey=random"
            )
            .unwrap()
        );
    }
}