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
//! Indexes endpoints
use crate::{
client::FmpClient,
error::Result,
models::indexes::{IndexConstituent, IndexHistorical, IndexQuote, IndexSymbol},
};
use serde::{Deserialize, Serialize};
/// Indexes API endpoints
pub struct Indexes {
client: FmpClient,
}
impl Indexes {
pub(crate) fn new(client: FmpClient) -> Self {
Self { client }
}
/// Get list of available market indexes
///
/// Returns all available market index symbols (S&P 500, Nasdaq, Dow Jones, etc.).
///
/// # Example
/// ```no_run
/// # use fmp_rs::FmpClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = FmpClient::new()?;
/// let indexes = client.indexes().get_index_list().await?;
/// for index in indexes.iter().take(10) {
/// println!("{}: {}", index.symbol, index.name.as_deref().unwrap_or("N/A"));
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_index_list(&self) -> Result<Vec<IndexSymbol>> {
#[derive(Serialize)]
struct Query<'a> {
apikey: &'a str,
}
let url = self.client.build_url("/symbol/available-indexes");
self.client
.get_with_query(
&url,
&Query {
apikey: self.client.api_key(),
},
)
.await
}
/// Get real-time index quote
///
/// Returns current level and market data for an index.
///
/// # Arguments
/// * `symbol` - Index symbol (e.g., "^GSPC" for S&P 500, "^DJI" for Dow Jones)
///
/// # Example
/// ```no_run
/// # use fmp_rs::FmpClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = FmpClient::new()?;
/// let quote = client.indexes().get_index_quote("^GSPC").await?;
/// if let Some(q) = quote.first() {
/// println!("S&P 500: {:.2}", q.price.unwrap_or(0.0));
/// println!("Change: {:+.2}%", q.changes_percentage.unwrap_or(0.0));
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_index_quote(&self, symbol: &str) -> Result<Vec<IndexQuote>> {
#[derive(Serialize)]
struct Query<'a> {
apikey: &'a str,
}
let url = self.client.build_url(&format!("/quote/{}", symbol));
self.client
.get_with_query(
&url,
&Query {
apikey: self.client.api_key(),
},
)
.await
}
/// Get historical index data
///
/// Returns daily historical data for an index.
///
/// # Arguments
/// * `symbol` - Index symbol (e.g., "^GSPC")
/// * `from` - Start date (optional, format: YYYY-MM-DD)
/// * `to` - End date (optional, format: YYYY-MM-DD)
///
/// # Example
/// ```no_run
/// # use fmp_rs::FmpClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = FmpClient::new()?;
/// let history = client.indexes().get_index_historical("^GSPC", None, None).await?;
/// for day in history.iter().take(5) {
/// println!("{}: {:.2}", day.date, day.close);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_index_historical(
&self,
symbol: &str,
from: Option<&str>,
to: Option<&str>,
) -> Result<Vec<IndexHistorical>> {
#[derive(Serialize)]
struct Query<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
from: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
to: Option<&'a str>,
apikey: &'a str,
}
let url = self
.client
.build_url(&format!("/historical-price-full/{}", symbol));
#[derive(Deserialize)]
struct Response {
historical: Vec<IndexHistorical>,
}
let response: Response = self
.client
.get_with_query(
&url,
&Query {
from,
to,
apikey: self.client.api_key(),
},
)
.await?;
Ok(response.historical)
}
/// Get index constituents
///
/// Returns all component stocks that make up an index (e.g., S&P 500 companies).
///
/// # Arguments
/// * `symbol` - Index symbol (e.g., "^GSPC" for S&P 500 constituents)
///
/// # Example
/// ```no_run
/// # use fmp_rs::FmpClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = FmpClient::new()?;
/// let constituents = client.indexes().get_index_constituents("^GSPC").await?;
/// println!("S&P 500 has {} components", constituents.len());
/// for stock in constituents.iter().take(10) {
/// println!("{}: {} ({})",
/// stock.symbol,
/// stock.name.as_deref().unwrap_or("N/A"),
/// stock.sector.as_deref().unwrap_or("N/A"));
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_index_constituents(&self, symbol: &str) -> Result<Vec<IndexConstituent>> {
#[derive(Serialize)]
struct Query<'a> {
apikey: &'a str,
}
let url = self.client.build_url(&format!("{}_constituent", symbol));
self.client
.get_with_query(
&url,
&Query {
apikey: self.client.api_key(),
},
)
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
// Golden path tests
#[tokio::test]
#[ignore = "requires FMP API key"]
async fn test_get_index_list() {
let client = FmpClient::new().unwrap();
let result = client.indexes().get_index_list().await;
assert!(result.is_ok());
let indexes = result.unwrap();
assert!(!indexes.is_empty());
}
#[tokio::test]
#[ignore = "requires FMP API key"]
async fn test_get_index_quote() {
let client = FmpClient::new().unwrap();
let result = client.indexes().get_index_quote("^GSPC").await;
assert!(result.is_ok());
let quotes = result.unwrap();
assert!(!quotes.is_empty());
assert!(quotes[0].price.is_some());
}
#[tokio::test]
#[ignore = "requires FMP API key"]
async fn test_get_index_historical() {
let client = FmpClient::new().unwrap();
let result = client
.indexes()
.get_index_historical("^GSPC", None, None)
.await;
assert!(result.is_ok());
let history = result.unwrap();
assert!(!history.is_empty());
}
#[tokio::test]
#[ignore = "requires FMP API key"]
async fn test_get_index_constituents() {
let client = FmpClient::new().unwrap();
let result = client.indexes().get_index_constituents("^GSPC").await;
assert!(result.is_ok());
let constituents = result.unwrap();
assert!(!constituents.is_empty());
}
// Edge case tests
#[tokio::test]
#[ignore = "requires FMP API key"]
async fn test_index_historical_with_dates() {
let client = FmpClient::new().unwrap();
let result = client
.indexes()
.get_index_historical("^GSPC", Some("2024-01-01"), Some("2024-01-31"))
.await;
assert!(result.is_ok());
}
#[tokio::test]
#[ignore = "requires FMP API key"]
async fn test_various_major_indexes() {
let client = FmpClient::new().unwrap();
// S&P 500, Nasdaq, Dow Jones
for symbol in &["^GSPC", "^IXIC", "^DJI"] {
let result = client.indexes().get_index_quote(symbol).await;
assert!(result.is_ok());
}
}
#[tokio::test]
#[ignore = "requires FMP API key"]
async fn test_dow_jones_constituents() {
let client = FmpClient::new().unwrap();
let result = client.indexes().get_index_constituents("^DJI").await;
assert!(result.is_ok());
let constituents = result.unwrap();
// Dow Jones has 30 companies
assert!(constituents.len() <= 30);
}
// Error handling tests
#[tokio::test]
async fn test_invalid_api_key() {
let client = FmpClient::builder()
.api_key("invalid_key_12345")
.build()
.unwrap();
let result = client.indexes().get_index_list().await;
assert!(result.is_err());
}
#[tokio::test]
#[ignore = "requires FMP API key"]
async fn test_invalid_symbol() {
let client = FmpClient::new().unwrap();
let result = client.indexes().get_index_quote("INVALIDINDEX123").await;
// Should return empty or error
match result {
Ok(quotes) => assert!(quotes.is_empty()),
Err(_) => {} // Error is acceptable for invalid symbol
}
}
}