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
use chrono::NaiveDate;
use reqwest::StatusCode;
use serde::Deserialize;
use serde_json::Value;
use std::fmt;
use tokio_compat_02::FutureExt;
#[derive(Deserialize, Debug)]
pub struct RealTimeQuote {
pub code: String,
pub timestamp: u64,
pub gmtoffset: i32,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub volume: usize,
#[serde(rename = "previousClose")]
pub previous_close: f64,
pub change: f64,
pub change_p: f64,
}
#[derive(Deserialize, Debug)]
pub struct HistoricQuote {
pub date: String,
pub open: Option<f64>,
pub high: Option<f64>,
pub low: Option<f64>,
pub close: Option<f64>,
pub adjusted_close: f64,
pub volume: Option<usize>,
}
#[derive(Debug)]
pub enum EodHistDataError {
FetchFailed(StatusCode),
DeserializeFailed,
ConnectionFailed,
}
impl std::error::Error for EodHistDataError {
fn cause(&self) -> Option<&dyn std::error::Error> {
Some(self)
}
}
impl fmt::Display for EodHistDataError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FetchFailed(status) => write!(f, "fetchin the data from eodhistoricaldata failed: with status code {}", status),
Self::DeserializeFailed => write!(f, "deserializing response from eodhistoricaldata failed"),
Self::ConnectionFailed => write!(f, "connection to eodhistoricaldata server failed"),
}
}
}
pub struct EodHistConnector {
url: &'static str,
api_token: String,
}
impl EodHistConnector {
pub fn new(token: String) -> EodHistConnector {
EodHistConnector {
url: "https://eodhistoricaldata.com/api",
api_token: token,
}
}
pub async fn get_latest_quote(&self, ticker: &str) -> Result<RealTimeQuote, EodHistDataError> {
let url: String = format!(
"{}/real-time/{}?api_token={}&fmt=json",
self.url, ticker, self.api_token
);
let resp = self.send_request(&url).await?;
let quote: RealTimeQuote =
serde_json::from_value(resp).map_err(|_| EodHistDataError::DeserializeFailed)?;
Ok(quote)
}
pub async fn get_quote_history(
&self,
ticker: &str,
start: NaiveDate,
end: NaiveDate,
) -> Result<Vec<HistoricQuote>, EodHistDataError> {
let url: String = format!(
"{}/eod/{}?from={}&to={}&api_token={}&period=d&fmt=json",
self.url,
ticker,
start.format("%Y-%m-%d"),
end.format("%Y-%m-%d"),
self.api_token
);
let resp = self.send_request(&url).await?;
let quotes: Vec<HistoricQuote> =
serde_json::from_value(resp).map_err(|_| EodHistDataError::DeserializeFailed)?;
Ok(quotes)
}
async fn send_request(&self, url: &str) -> Result<Value, EodHistDataError> {
let resp = reqwest::get(url).compat().await;
if resp.is_err() {
return Err(EodHistDataError::ConnectionFailed);
}
let resp = resp.unwrap();
match resp.status() {
StatusCode::OK => match resp.json().await {
Ok(json) => Ok(json),
_ => Err(EodHistDataError::DeserializeFailed),
},
status => Err(EodHistDataError::FetchFailed(status)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio_test;
#[test]
fn test_get_single_quote() {
let token = "OeAFFmMliFG5orCUuwAKQ8l4WWFQ67YX".to_string();
let provider = EodHistConnector::new(token);
let quote = tokio_test::block_on(provider.get_latest_quote("AAPL.US")).unwrap();
assert_eq!("e.code, "AAPL.US");
}
#[test]
fn test_get_quote_history() {
let token = "OeAFFmMliFG5orCUuwAKQ8l4WWFQ67YX".to_string();
let provider = EodHistConnector::new(token);
let start = NaiveDate::from_ymd(2020, 01, 01);
let end = NaiveDate::from_ymd(2020, 01, 31);
let quotes = tokio_test::block_on(provider.get_quote_history("AAPL.US", start, end)).unwrap();
assert_eq!(quotes.len(), 21);
assert_eq!(quotes[0].date, "2020-01-02");
assert_eq!(quotes[quotes.len() - 1].date, "2020-01-31");
}
}