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
use crate::{
    common::{optional_string_serialize, string_serialize, Decimal, ExpirationDate, OptionType},
    symbol::{self, OptionSymbol},
};

use chrono::{DateTime, FixedOffset, NaiveDate};
use serde::Deserialize;

use std::str::FromStr;

#[derive(Debug, Deserialize)]
pub struct Position {
    #[serde(rename = "Symbol")]
    pub symbol: String,
    #[serde(rename = "Type")]
    pub instrument_type: String,
    #[serde(rename = "Quantity", with = "string_serialize")]
    pub quantity: i32,
    #[serde(rename = "Strike Price", with = "string_serialize")]
    pub strike_price: Decimal,
    #[serde(rename = "Call/Put")]
    pub call_or_put: OptionTypePascalCase,
    #[serde(rename = "D's Opn")]
    pub days_open: String,
    #[serde(rename = "NetLiq", with = "string_serialize")]
    pub net_liq: Decimal,
}

impl Position {
    pub fn expiration_date(&self) -> ExpirationDate {
        OptionSymbol::from(&self.symbol).expiration_date()
    }

    pub fn underlying_symbol(&self) -> &str {
        OptionSymbol::from(&self.symbol).underlying_symbol()
    }

    pub fn days_open(&self) -> i32 {
        let idx = self.days_open.len() - 1;

        assert!(self.days_open.chars().nth(idx) == Some('d'));
        self.days_open
            .get(..idx)
            .map(|s| i32::from_str(s).ok())
            .flatten()
            .unwrap_or_else(|| panic!("Could not parse days open: {}", self.days_open))
    }
}

#[derive(Debug, Deserialize)]
pub struct Transaction {
    #[serde(rename = "Date", with = "string_serialize")]
    pub date: DateTime<FixedOffset>,
    #[serde(rename = "Type")]
    pub trade_type: String,
    #[serde(rename = "Action")]
    pub action: Option<TradeAction>,
    #[serde(rename = "Symbol")]
    pub symbol: Option<String>,
    #[serde(rename = "Instrument Type")]
    pub instrument_type: Option<String>,
    #[serde(rename = "Description")]
    pub description: String,
    #[serde(rename = "Value", with = "string_serialize")]
    pub value: Decimal,
    #[serde(rename = "Quantity", with = "string_serialize")]
    pub quantity: Decimal,
    #[serde(rename = "Average Price", with = "optional_string_serialize")]
    pub average_price: Option<Decimal>,
    #[serde(rename = "Commissions", with = "optional_string_serialize")]
    pub commissions: Option<Decimal>,
    #[serde(rename = "Fees", with = "string_serialize")]
    pub fees: Decimal,
    #[serde(rename = "Multiplier", with = "optional_string_serialize")]
    pub multiplier: Option<i32>,
    // pub underlying_symbol: Option<String>,
    #[serde(rename = "Expiration Date", with = "optional_string_serialize")]
    pub expiration_date: Option<TransactionExpiration>,
    #[serde(rename = "Strike Price", with = "optional_string_serialize")]
    pub strike_price: Option<Decimal>,
    #[serde(rename = "Call or Put")]
    pub call_or_put: Option<OptionTypeUpperCase>,
}

impl Transaction {
    pub fn underlying_symbol(&self) -> Option<&str> {
        self.symbol.as_ref().map(|symbol| {
            let underlying_symbol = symbol
                .split_whitespace()
                .next()
                .expect("Missing underlying symbol");
            symbol::strip_weekly(underlying_symbol)
        })
    }
}

#[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TradeAction {
    SellToOpen,  // open credit
    BuyToOpen,   // open debit
    SellToClose, // close credit
    BuyToClose,  // close debit
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TransactionExpiration(pub NaiveDate);

impl FromStr for TransactionExpiration {
    type Err = chrono::ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(TransactionExpiration(NaiveDate::parse_from_str(
            s,
            "%-m/%-d/%y",
        )?))
    }
}

impl From<TransactionExpiration> for ExpirationDate {
    fn from(d: TransactionExpiration) -> ExpirationDate {
        ExpirationDate(d.0)
    }
}

#[derive(Copy, Clone, Debug, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum OptionTypeUpperCase {
    Call,
    Put,
}

impl From<OptionTypeUpperCase> for OptionType {
    fn from(json: OptionTypeUpperCase) -> OptionType {
        match json {
            OptionTypeUpperCase::Call => OptionType::Call,
            OptionTypeUpperCase::Put => OptionType::Put,
        }
    }
}

#[derive(Copy, Clone, Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum OptionTypePascalCase {
    Call,
    Put,
}

impl From<OptionTypePascalCase> for OptionType {
    fn from(json: OptionTypePascalCase) -> OptionType {
        match json {
            OptionTypePascalCase::Call => OptionType::Call,
            OptionTypePascalCase::Put => OptionType::Put,
        }
    }
}

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

    #[test]
    fn test_trade_expiration_date_csv_from_str() {
        assert_eq!(
            TransactionExpiration::from_str("7/31/20").unwrap(),
            TransactionExpiration(NaiveDate::from_ymd(2020, 7, 31))
        );
    }
}