Skip to content

Commit

Permalink
fix blocking and formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
xemwebe committed Jan 27, 2024
1 parent 389271c commit 95a5024
Show file tree
Hide file tree
Showing 9 changed files with 97 additions and 85 deletions.
4 changes: 2 additions & 2 deletions examples/get_fxrates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ use yahoo_finance_api as yahoo;
fn get_history() -> Result<yahoo::YResponse, yahoo::YahooError> {
let provider = yahoo::YahooConnector::new();
let start = time::OffsetDateTime::UNIX_EPOCH;
let end= time::OffsetDateTime::now_utc();
let end = time::OffsetDateTime::now_utc();
tokio_test::block_on(provider.get_quote_history("EUR=x", start, end))
}

#[cfg(feature = "blocking")]
fn get_history() -> Result<yahoo::YResponse, yahoo::YahooError> {
let provider = yahoo::YahooConnector::new();
let start = time::OffsetDateTime::UNIX_EPOCH;
let end= time::OffsetDateTime::now_utc();
let end = time::OffsetDateTime::now_utc();
provider.get_quote_history("EUR=x", start, end)
}

Expand Down
4 changes: 2 additions & 2 deletions examples/get_quote_history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ use yahoo_finance_api as yahoo;
fn get_history() -> Result<yahoo::YResponse, yahoo::YahooError> {
let provider = yahoo::YahooConnector::new();
let start = time::OffsetDateTime::UNIX_EPOCH;
let end= time::OffsetDateTime::now_utc();
let end = time::OffsetDateTime::now_utc();
tokio_test::block_on(provider.get_quote_history("VTI", start, end))
}

#[cfg(feature = "blocking")]
fn get_history() -> Result<yahoo::YResponse, yahoo::YahooError> {
let provider = yahoo::YahooConnector::new();
let start = time::OffsetDateTime::UNIX_EPOCH;
let end= time::OffsetDateTime::now_utc();
let end = time::OffsetDateTime::now_utc();
provider.get_quote_history("VTI", start, end)
}

Expand Down
2 changes: 1 addition & 1 deletion examples/get_quote_period_interval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ fn get_history() -> Result<yahoo::YResponse, yahoo::YahooError> {
#[cfg(feature = "blocking")]
fn get_history() -> Result<yahoo::YResponse, yahoo::YahooError> {
let provider = yahoo::YahooConnector::new();
provider.get_quote_history_interval("AAPL", "1d", "1m", true)
provider.get_quote_period_interval("AAPL", "1d", "1m", true)
}

fn main() {
Expand Down
5 changes: 2 additions & 3 deletions src/async_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@ impl YahooConnector {
YResponse::from_json(self.send_request(&url).await?)
}

/// Retrieve the quote history for the given ticker form date start to end (inclusive), if available; specifying the interval of the ticker.
/// Retrieve the quote history for the given ticker for a given period and ticker interval and optionally before and after regular trading hours
pub async fn get_quote_period_interval(
&self,
ticker: &str,
period: &str,
interval: &str,
prepost: bool
prepost: bool,
) -> Result<YResponse, YahooError> {
let url = format!(
YCHART_PERIOD_INTERVAL_QUERY!(),
Expand All @@ -73,7 +73,6 @@ impl YahooConnector {
interval = interval,
prepost = prepost,
);
println!("result: {:?}", self.send_request(&url).await?);
YResponse::from_json(self.send_request(&url).await?)
}

Expand Down
21 changes: 19 additions & 2 deletions src/blocking_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ impl YahooConnector {
start: OffsetDateTime,
end: OffsetDateTime,
interval: &str,
prepost: bool,
) -> Result<YResponse, YahooError> {
let url = format!(
YCHART_PERIOD_QUERY!(),
Expand All @@ -49,7 +48,25 @@ impl YahooConnector {
start = start.unix_timestamp(),
end = end.unix_timestamp(),
interval = interval,
prepost = prepost
);
YResponse::from_json(self.send_request(&url)?)
}

/// Retrieve the quote history for the given ticker for a given period and ticker interval and optionally before and after regular trading hours
pub fn get_quote_period_interval(
&self,
ticker: &str,
period: &str,
interval: &str,
prepost: bool,
) -> Result<YResponse, YahooError> {
let url = format!(
YCHART_PERIOD_INTERVAL_QUERY!(),
url = self.url,
symbol = ticker,
period = period,
interval = interval,
prepost = prepost,
);
YResponse::from_json(self.send_request(&url)?)
}
Expand Down
12 changes: 5 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,7 @@ fn main() {
"
)]

use std::{
time::Duration,
};
use std::time::Duration;
use time::OffsetDateTime;

#[cfg(feature = "blocking")]
Expand All @@ -173,15 +171,15 @@ use reqwest::{Client, ClientBuilder};
// re-export time crate
pub use time;

mod quotes;
mod quote_summary;
mod quotes;
mod search_result;
mod yahoo_error;
pub use quote_summary::{YQuoteResponse, YQuoteSummary};
pub use quotes::{
AdjClose, Dividend, CapitalGain, PeriodInfo, Quote, QuoteBlock, QuoteList, Split, TradingPeriods, YChart,
YMetaData, YQuoteBlock, YResponse,
AdjClose, CapitalGain, Dividend, PeriodInfo, Quote, QuoteBlock, QuoteList, Split,
TradingPeriods, YChart, YMetaData, YQuoteBlock, YResponse,
};
pub use quote_summary::{YQuoteResponse, YQuoteSummary};
pub use search_result::{
YNewsItem, YOptionResult, YOptionResults, YQuoteItem, YQuoteItemOpt, YSearchResult,
YSearchResultOpt,
Expand Down
7 changes: 4 additions & 3 deletions src/quote_summary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ impl YQuoteResponse {
pub fn from_json(json: serde_json::Value) -> Result<YQuoteResponse, YahooError> {
Ok(serde_json::from_value(
json.get("quoteResponse")
.ok_or(YahooError::DataInconsistency)?
.to_owned())?)
.ok_or(YahooError::DataInconsistency)?
.to_owned(),
)?)
}
}

Expand Down Expand Up @@ -104,4 +105,4 @@ pub struct YQuoteSummary {
pub to_currency: Option<String>,
pub coin_market_cap_link: Option<String>,
pub start_date: Option<u32>,
}
}
85 changes: 42 additions & 43 deletions src/quotes.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
use std::{
collections::HashMap,
fmt
};
use std::{collections::HashMap, fmt};

use serde::{Deserialize,
de::{self, Deserializer, Visitor, SeqAccess, MapAccess}
use serde::{
de::{self, Deserializer, MapAccess, SeqAccess, Visitor},
Deserialize,
};

use super::YahooError;
Expand Down Expand Up @@ -75,7 +73,7 @@ impl YResponse {
pub fn metadata(&self) -> Result<YMetaData, YahooError> {
self.check_consistency()?;
let stock = &self.chart.result[0];
Ok( stock.meta.to_owned())
Ok(stock.meta.to_owned())
}

/// This method retrieves information about the splits that might have
Expand Down Expand Up @@ -181,20 +179,23 @@ pub struct YMetaData {

#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct TradingPeriods {
pub pre: Option<Vec<Vec<PeriodInfo>>>,
pub regular: Option<Vec<Vec<PeriodInfo>>>,
pub post: Option<Vec<Vec<PeriodInfo>>>,
pub pre: Option<Vec<Vec<PeriodInfo>>>,
pub regular: Option<Vec<Vec<PeriodInfo>>>,
pub post: Option<Vec<Vec<PeriodInfo>>>,
}

impl<'de> Deserialize<'de> for TradingPeriods
{
impl<'de> Deserialize<'de> for TradingPeriods {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field { Regular, Pre, Post }
enum Field {
Regular,
Pre,
Post,
}

struct TradingPeriodsVisitor;

Expand All @@ -209,12 +210,13 @@ impl<'de> Deserialize<'de> for TradingPeriods
where
V: SeqAccess<'de>,
{
let regular: Vec<PeriodInfo> = seq.next_element()?
let regular: Vec<PeriodInfo> = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(0, &self))?;
Ok(TradingPeriods{
Ok(TradingPeriods {
pre: None,
regular: Some(vec![regular]),
post: None
post: None,
})
}

Expand All @@ -232,27 +234,22 @@ impl<'de> Deserialize<'de> for TradingPeriods
return Err(de::Error::duplicate_field("pre"));
}
pre = Some(map.next_value()?);
},
}
Field::Post => {
if post.is_some() {
return Err(de::Error::duplicate_field("post"));
}
post = Some(map.next_value()?);
},
}
Field::Regular => {
if regular.is_some() {
return Err(de::Error::duplicate_field("regular"));
}
regular = Some(map.next_value()?);
},

}
}
}
Ok(TradingPeriods{
pre,
post,
regular,
})
Ok(TradingPeriods { pre, post, regular })
}
}

Expand Down Expand Up @@ -361,14 +358,14 @@ pub struct Dividend {
pub struct CapitalGain {
/// This is the amount of capital gain distributed by the fund
pub amount: f64,
/// This is the recorded date of the capital gain
/// This is the recorded date of the capital gain
pub date: u64,
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_deserialize_period_info() {
let period_info_json = r#"
Expand All @@ -379,7 +376,7 @@ mod tests {
"gmtoffset": -18000
}
"#;
let period_info_expected = PeriodInfo{
let period_info_expected = PeriodInfo {
timezone: "EST".to_string(),
start: 1705501800,
end: 1705525200,
Expand All @@ -388,7 +385,7 @@ mod tests {
let period_info_deserialized: PeriodInfo = serde_json::from_str(period_info_json).unwrap();
assert_eq!(&period_info_deserialized, &period_info_expected);
}

#[test]
fn test_deserialize_trading_periods_simple() {
let trading_periods_json = r#"
Expand All @@ -404,17 +401,18 @@ mod tests {
]
]
"#;
let trading_periods_expected = TradingPeriods{
let trading_periods_expected = TradingPeriods {
pre: None,
regular: Some(vec![vec![PeriodInfo{
regular: Some(vec![vec![PeriodInfo {
timezone: "EST".to_string(),
start: 1705501800,
end: 1705525200,
gmtoffset: -18000,
}]]),
post: None,
post: None,
};
let trading_periods_deserialized: TradingPeriods = serde_json::from_str(trading_periods_json).unwrap();
let trading_periods_deserialized: TradingPeriods =
serde_json::from_str(trading_periods_json).unwrap();
assert_eq!(&trading_periods_expected, &trading_periods_deserialized);
}

Expand All @@ -434,17 +432,18 @@ mod tests {
]
}
"#;
let trading_periods_expected = TradingPeriods{
let trading_periods_expected = TradingPeriods {
pre: None,
regular: Some(vec![vec![PeriodInfo{
regular: Some(vec![vec![PeriodInfo {
timezone: "EST".to_string(),
start: 1705501800,
end: 1705525200,
gmtoffset: -18000,
}]]),
post: None
post: None,
};
let trading_periods_deserialized: TradingPeriods = serde_json::from_str(trading_periods_json).unwrap();
let trading_periods_deserialized: TradingPeriods =
serde_json::from_str(trading_periods_json).unwrap();
assert_eq!(&trading_periods_expected, &trading_periods_deserialized);
}

Expand Down Expand Up @@ -484,28 +483,28 @@ mod tests {
]
}
"#;
let trading_periods_expected = TradingPeriods{
pre: Some(vec![vec![PeriodInfo{
let trading_periods_expected = TradingPeriods {
pre: Some(vec![vec![PeriodInfo {
timezone: "EST".to_string(),
start: 1705482000,
end: 1705501800,
gmtoffset: -18000,
}]]),
regular: Some(vec![vec![PeriodInfo{
regular: Some(vec![vec![PeriodInfo {
timezone: "EST".to_string(),
start: 1705501800,
end: 1705525200,
gmtoffset: -18000,
}]]),
post: Some(vec![vec![PeriodInfo{
post: Some(vec![vec![PeriodInfo {
timezone: "EST".to_string(),
start: 1705525200,
end: 1705539600,
gmtoffset: -18000,
}]]),
};
let trading_periods_deserialized: TradingPeriods = serde_json::from_str(trading_periods_json).unwrap();
let trading_periods_deserialized: TradingPeriods =
serde_json::from_str(trading_periods_json).unwrap();
assert_eq!(&trading_periods_expected, &trading_periods_deserialized);
}
}

Loading

0 comments on commit 95a5024

Please sign in to comment.