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
use std::collections::HashMap;
use std::str::FromStr;

use serde;
use serde::{Deserialize, Serialize};

use fin_model::analysis::*;
use fin_model::prelude::*;
use fin_model::reporting::FinancialPeriod;
use fin_model::symbol::is_valid;

use crate::internal::convert::*;
use crate::internal::metric::{record_api_use, ApiName};
use crate::internal::request;
use crate::IEXProvider;

// ------------------------------------------------------------------------------------------------
// API Types (internal)
// ------------------------------------------------------------------------------------------------

#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize, Debug)]
struct IEXPriceTarget {
    symbol: String,
    updated_date: String,
    price_target_average: f64,
    price_target_high: f64,
    price_target_low: f64,
    number_of_analysts: f64,
}

#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize, Debug)]
struct IEXRecommendationTrends {
    consensus_end_date: f64,
    consensus_start_date: f64,
    corporate_actions_applied_date: f64,
    rating_buy: f64,
    rating_hold: f64,
    rating_none: f64,
    rating_sell: f64,
    rating_overweight: f64,
    rating_underweight: f64,
    rating_scale_mark: f64,
}

#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize, Debug)]
struct IEXEstimates {
    symbol: String,
    estimates: Vec<IEXEstimateData>,
}

#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize, Debug)]
struct IEXEstimateData {
    #[serde(rename = "consensusEPS")]
    consensus_eps: f64,
    number_of_estimates: f64,
    fiscal_period: String,
    fiscal_end_date: String,
    report_date: String,
}

// ------------------------------------------------------------------------------------------------
// Trait Implementations
// ------------------------------------------------------------------------------------------------

impl Peers for IEXProvider {
    fn peers(&self, for_symbol: Symbol) -> RequestResult<Symbols> {
        debug!("IEXProvider::<Peers>::peers for_symbol: {}", for_symbol);
        assert_is_valid!(for_symbol);

        let api_url = self.make_api_url(format!("/stock/{}/peers", for_symbol), None);

        let response: RequestResult<Symbols> = request::make_json_call(api_url);
        match response {
            Ok(values) => {
                record_api_use(ApiName::Peers);
                Ok(values)
            }
            Err(err) => {
                println!("IEXProvider::<Peers>::peers returned error: {:?}", err);
                Err(err)
            }
        }
    }
}

impl AnalystRecommendations for IEXProvider {
    fn target_price(&self, for_symbol: Symbol) -> RequestResult<Snapshot<PriceTarget>> {
        debug!(
            "IEXProvider::<AnalystRecommendations>::target_price for_symbol: {}",
            for_symbol
        );
        assert_is_valid!(for_symbol);

        let api_url = self.make_api_url(format!("/stock/{}/price-target", for_symbol), None);

        let response: RequestResult<IEXPriceTarget> = request::make_json_call(api_url);
        let dc = self.get_default_currency();
        match response {
            Ok(target) => {
                record_api_use(ApiName::TargetPrice);
                Ok(Snapshot {
                    date: datetime_from_date_string(&target.updated_date)?,
                    data: PriceTarget {
                        high: price_from_float(dc, target.price_target_high)?,
                        low: price_from_float(dc, target.price_target_low)?,
                        average: price_from_float(dc, target.price_target_average)?,
                        number_of_analysts: target.number_of_analysts as u32,
                    },
                })
            }
            Err(err) => {
                println!(
                    "IEXProvider::<AnalystRecommendations>::target_price returned error: {:?}",
                    err
                );
                Err(err)
            }
        }
    }

    fn consensus_rating(&self, for_symbol: Symbol) -> RequestResult<Vec<Bounded<Ratings>>> {
        debug!(
            "IEXProvider::<AnalystRecommendations>::consensus_rating for_symbol: {}",
            for_symbol
        );
        assert_is_valid!(for_symbol);

        let api_url =
            self.make_api_url(format!("/stock/{}/recommendation-trends", for_symbol), None);

        let response: RequestResult<Vec<IEXRecommendationTrends>> =
            request::make_json_call(api_url);
        match response {
            Ok(consensus) => {
                record_api_use(ApiName::ConsensusRatings);
                let series: RequestResult<Vec<Bounded<Ratings>>> =
                    consensus.iter().map(|v| to_rating(v)).collect();
                match series {
                    Ok(data) => Ok(data),
                    Err(err) => Err(err),
                }
            }
            Err(err) => {
                warn!(
                    "IEXProvider::<AnalystRecommendations>::consensus_rating returning error: {:?}",
                    err
                );
                Err(err)
            }
        }
    }

    fn consensus_eps(&self, for_symbol: Symbol) -> RequestResult<Vec<EPSConsensus>> {
        debug!(
            "IEXProvider::<AnalystRecommendations>::consensus_eps for_symbol: {}",
            for_symbol
        );
        assert_is_valid!(for_symbol);

        let api_url =
            self.make_api_url(format!("/stock/{}/recommendation-trends", for_symbol), None);

        let response: RequestResult<IEXEstimates> = request::make_json_call(api_url);
        let dc = self.get_default_currency();
        match response {
            Ok(estimates) => {
                record_api_use(ApiName::ConsensusEPS);
                let series: RequestResult<Vec<EPSConsensus>> = estimates
                    .estimates
                    .iter()
                    .map(|v| to_estimate(dc, v))
                    .collect();
                match series {
                    Ok(data) => Ok(data),
                    Err(err) => Err(err),
                }
            }
            Err(err) => {
                warn!(
                    "IEXProvider::<AnalystRecommendations>::consensus_eps returning error: {:?}",
                    err
                );
                Err(err)
            }
        }
    }
}

// ------------------------------------------------------------------------------------------------
// Private Implementations
// ------------------------------------------------------------------------------------------------

fn to_rating(v: &IEXRecommendationTrends) -> RequestResult<Bounded<Ratings>> {
    let mut ratings: HashMap<RatingType, Counter> = HashMap::new();
    ratings.insert(RatingType::Buy, v.rating_buy as Counter);
    ratings.insert(RatingType::Hold, v.rating_hold as Counter);
    ratings.insert(RatingType::Sell, v.rating_sell as Counter);
    ratings.insert(RatingType::Underperform, v.rating_underweight as Counter);
    ratings.insert(RatingType::Outperform, v.rating_overweight as Counter);

    Ok(Bounded {
        start_date: date_from_timestamp(v.consensus_start_date)?,
        end_date: date_from_timestamp(v.consensus_end_date)?,
        data: Ratings {
            ratings,
            scale_mark: Some(v.rating_scale_mark as f32),
        },
    })
}

fn to_estimate(dc: &String, v: &IEXEstimateData) -> RequestResult<EPSConsensus> {
    Ok(EPSConsensus {
        consensus: price_from_float(dc, v.consensus_eps)?,
        number_of_estimates: v.number_of_estimates as Counter,
        fiscal_period: FinancialPeriod::from_str(v.fiscal_period.as_str()).unwrap(),
        fiscal_end_date: date_from_string(&v.fiscal_end_date)?,
        next_report_date: date_from_string(&v.report_date)?,
    })
}