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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Contains functions for computing the partial expectation, quantile, and cumulative density
//! function given a characteristic function.  
extern crate fang_oost;
extern crate roots;
use roots::find_root_regula_falsi;
use roots::SimpleConvergency;
use std::error::Error;
use std::fmt;
extern crate num_complex;
extern crate rayon;
#[macro_use]
#[cfg(test)]
extern crate approx;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
use num_complex::Complex;

use rayon::prelude::*;

#[derive(Debug)]
pub struct ValueAtRiskError {
    msg: String
}
impl ValueAtRiskError {
    pub fn new(msg:&str)->Self{
        ValueAtRiskError{msg:msg.to_string()}
    }
}
impl Error for ValueAtRiskError{
    fn description(&self)->&str {
        &self.msg
    }
}

impl fmt::Display for ValueAtRiskError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.msg)
    }
}

const ALPHA_ERROR: &str = "Alpha must be between 0 and 1.";

#[derive(Serialize, Deserialize, Debug)]
pub struct RiskMetric {
    pub expected_shortfall: f64,
    pub value_at_risk: f64,
}

/**
    Function to compute the CDF of a distribution; see
    http://danielhstahl.com/static/media/CreditRiskExtensions.c31991d2.pdf

*/
fn vk_cdf(u: f64, x: f64, a: f64, k: usize) -> f64 {
    if k == 0 {
        x - a
    } else {
        ((x - a) * u).sin() / u
    }
}

fn diff_pow(x: f64, a: f64) -> f64 {
    0.5 * (x.powi(2) - a.powi(2))
}

/**
    Function to compute the partial expectation of a distribution; see
    http://danielhstahl.com/static/media/CreditRiskExtensions.c31991d2.pdf.
*/
fn vk_pe(u: f64, x: f64, a: f64, k: usize) -> f64 {
    let arg = (x - a) * u;
    let u_den = 1.0 / u;
    if k == 0 {
        diff_pow(x, a)
    } else {
        x * arg.sin() * u_den + u_den.powi(2) * (arg.cos() - 1.0)
    }
}
/**
    Function to compute the partial expectation squared of a distribution.
*/
fn vk_pv(u: f64, x: f64, c: f64, a: f64, k: usize) -> f64 {
    let arg = (x - a) * u;
    let u_den = 1.0 / u;
    if k == 0 {
        -(a - x).powi(3) / 3.0 - (a - x).powi(2) * (x - c) - (a - x) * (x - c).powi(2)
    } else {
        (x - c).powi(2) * arg.sin() * u_den - 2.0 * arg.sin() * u_den.powi(3)
            + 2.0 * ((x - c) * arg.cos() + c - a) * u_den.powi(2)
    }
}

fn compute_value_at_risk(
    alpha: f64,
    x_min: f64,
    x_max: f64,
    max_iterations: usize,
    tolerance: f64,
    discrete_cf: &[Complex<f64>],
) -> Result<f64, ValueAtRiskError> {
    let vf = |u, x, u_index| vk_cdf(u, x, x_min, u_index);
    let in_f = |x: f64| {
        fang_oost::get_expectation_single_element_real(x_min, x_max, x, discrete_cf, vf) - alpha
    };
    let mut convergency = SimpleConvergency {
        eps: tolerance,
        max_iter: max_iterations,
    };
    match find_root_regula_falsi(x_min, x_max, &in_f, &mut convergency) {
        Ok(v) => Ok(-v),
        Err(e) => Err(ValueAtRiskError::new(e.description())),
    }
}
fn compute_expected_shortfall(
    alpha: f64,
    x_min: f64,
    x_max: f64,
    value_at_risk: f64,
    discrete_cf: &[Complex<f64>],
) -> f64 {
    -fang_oost::get_expectation_single_element_real(
        x_min,
        x_max,
        -value_at_risk,
        discrete_cf,
        |u, x, u_index| vk_pe(u, x, x_min, u_index),
    ) / alpha
}
/// Returns expected shortfall (partial expectation) and value at risk (quantile)
/// given a discrete characteristic function.
///
/// # Remarks
/// Technically there is no guarantee of convergence for value at risk.
/// The cosine expansion oscillates and the value at risk may be under
/// or over stated.  However, in tests it appears to converge for a wide
/// range of distributions
///
/// # Examples
/// ```
/// extern crate num_complex;
/// use num_complex::Complex;
/// #[macro_use]
/// extern crate approx;
/// extern crate cf_dist_utils;
/// # fn main(){
/// let mu=2.0;
/// let sigma=5.0;
/// let num_u=128;
/// let x_min=-20.0;
/// let x_max=25.0;
/// let alpha=0.05;
/// let max_iterations=1000;
/// let tolerance=0.0001;
/// let norm_cf=vec![Complex::new(1.0, 1.0), Complex::new(-1.0, 1.0)];
/// let cf_dist_utils::RiskMetric{
///     expected_shortfall,
///     value_at_risk
/// }=cf_dist_utils::get_expected_shortfall_and_value_at_risk_discrete_cf(
///     alpha, x_min, x_max, max_iterations, tolerance, &norm_cf
/// ).unwrap();
/// # }
/// ```
pub fn get_expected_shortfall_and_value_at_risk_discrete_cf(
    alpha: f64,
    x_min: f64,
    x_max: f64,
    max_iterations: usize,
    tolerance: f64,
    discrete_cf: &[Complex<f64>],
) -> Result<RiskMetric, ValueAtRiskError> {
    if alpha > 0.0 && alpha < 1.0 {
        let value_at_risk =
            compute_value_at_risk(alpha, x_min, x_max, max_iterations, tolerance, &discrete_cf)?;
        let expected_shortfall =
            compute_expected_shortfall(alpha, x_min, x_max, value_at_risk, &discrete_cf);
        Ok(RiskMetric {
            expected_shortfall,
            value_at_risk,
        })
    } else {
        Err(ValueAtRiskError::new(ALPHA_ERROR))
    }
}
/// Returns expectation
/// given a discrete characteristic function.
///
/// # Examples
/// ```
/// extern crate num_complex;
/// use num_complex::Complex;
/// #[macro_use]
/// extern crate approx;
/// extern crate cf_dist_utils;
/// # fn main(){
/// let mu=2.0;
/// let sigma=5.0;
/// let num_u=128;
/// let x_min=-20.0;
/// let x_max=25.0;
/// let norm_cf=vec![Complex::new(1.0, 1.0), Complex::new(-1.0, 1.0)];
/// let expectation=cf_dist_utils::get_expectation_discrete_cf(
///     x_min, x_max, &norm_cf
/// );
/// # }
/// ```
pub fn get_expectation_discrete_cf(x_min: f64, x_max: f64, discrete_cf: &[Complex<f64>]) -> f64 {
    fang_oost::get_expectation_single_element_real(
        x_min,
        x_max,
        x_max,
        discrete_cf,
        |u, x, u_index| vk_pe(u, x, x_min, u_index),
    )
}
/// Returns variance
/// given a discrete characteristic function.
///
/// # Examples
/// ```
/// extern crate num_complex;
/// use num_complex::Complex;
/// #[macro_use]
/// extern crate approx;
/// extern crate cf_dist_utils;
/// # fn main(){
/// let mu=2.0;
/// let sigma=5.0;
/// let num_u=128;
/// let x_min=-20.0;
/// let x_max=25.0;
/// let norm_cf=vec![Complex::new(1.0, 1.0), Complex::new(-1.0, 1.0)];
/// let variance=cf_dist_utils::get_variance_discrete_cf(
///     x_min, x_max, &norm_cf
/// );
/// # }
/// ```
pub fn get_variance_discrete_cf(x_min: f64, x_max: f64, discrete_cf: &[Complex<f64>]) -> f64 {
    let expectation = fang_oost::get_expectation_single_element_real(
        x_min,
        x_max,
        x_max,
        discrete_cf,
        |u, x, u_index| vk_pe(u, x, x_min, u_index),
    );
    fang_oost::get_expectation_single_element_real(
        x_min,
        x_max,
        x_max,
        discrete_cf,
        |u, x, u_index| vk_pv(u, x, expectation, x_min, u_index),
    )
}

/// Returns expected shortfall (partial expectation) and value at risk (quantile)
/// given a characteristic function.
///
/// # Remarks
/// Technically there is no guarantee of convergence for value at risk.
/// The cosine expansion oscillates and the value at risk may be under
/// or over stated.  However, in tests it appears to converge for a wide
/// range of distributions
///
/// # Examples
/// ```
/// extern crate num_complex;
/// use num_complex::Complex;
/// #[macro_use]
/// extern crate approx;
/// extern crate cf_dist_utils;
/// # fn main(){
/// let mu=2.0;
/// let sigma=5.0;
/// let num_u=128;
/// let x_min=-20.0;
/// let x_max=25.0;
/// let max_iterations=1000;
/// let tolerance=0.0000001;
/// let alpha=0.05;
/// let norm_cf=|u:&Complex<f64>| (u*mu+0.5*sigma*sigma*u*u).exp();
/// let reference_var=6.224268;
/// let reference_es=8.313564;
/// let cf_dist_utils::RiskMetric{
///     expected_shortfall,
///     value_at_risk
/// }=cf_dist_utils::get_expected_shortfall_and_value_at_risk(
///     alpha, num_u, x_min, x_max, max_iterations, tolerance, norm_cf
/// ).unwrap();
/// assert_abs_diff_eq!(reference_var, value_at_risk, epsilon=0.0001);
/// assert_abs_diff_eq!(reference_es, expected_shortfall, epsilon=0.001);
/// # }
/// ```
pub fn get_expected_shortfall_and_value_at_risk<T>(
    alpha: f64,
    num_u: usize,
    x_min: f64,
    x_max: f64,
    max_iterations: usize,
    tolerance: f64,
    fn_inv: T,
) -> Result<RiskMetric, ValueAtRiskError>
where
    T: Fn(&Complex<f64>) -> Complex<f64> + std::marker::Sync + std::marker::Send,
{
    let discrete_cf = fang_oost::get_discrete_cf(num_u, x_min, x_max, fn_inv);
    get_expected_shortfall_and_value_at_risk_discrete_cf(
        alpha,
        x_min,
        x_max,
        max_iterations,
        tolerance,
        &discrete_cf,
    )
}

/// Returns vector of cumulative density function given a characteristic function.
///  
/// # Examples
/// ```
/// extern crate num_complex;
/// use num_complex::Complex;
/// extern crate cf_dist_utils;
/// # fn main(){
/// let mu = 2.0;
/// let sigma = 5.0;
/// let num_u = 128;
/// let num_x = 1024;
/// let x_min=-20.0;
/// let x_max=25.0;
/// let norm_cf=|u:&Complex<f64>| (u*mu+0.5*sigma*sigma*u*u).exp();
/// let cdf=cf_dist_utils::get_cdf(
///     num_x, num_u, x_min, x_max, &norm_cf
/// );
/// # }
/// ```
pub fn get_cdf<T>(num_x: usize, num_u: usize, x_min: f64, x_max: f64, cf: T) -> Vec<f64>
where
    T: Fn(&Complex<f64>) -> Complex<f64> + std::marker::Sync + std::marker::Send,
{
    let x_domain = fang_oost::get_x_domain(num_x, x_min, x_max);
    let discrete_cf = fang_oost::get_discrete_cf(num_u, x_min, x_max, &cf);
    let result =
        fang_oost::get_expectation_real(x_min, x_max, x_domain, &discrete_cf, |u, x, u_index| {
            vk_cdf(u, x, x_min, u_index)
        })
        .collect();
    result
}

/// Returns cumulative density function at given x.
///  
/// # Examples
/// ```
/// extern crate num_complex;
/// use num_complex::Complex;
/// extern crate cf_dist_utils;
/// # fn main(){
/// let mu = 2.0;
/// let sigma = 5.0;
/// let num_u = 128;
/// let x = 0.0;
/// let x_min=-20.0;
/// let x_max=25.0;
/// let norm_cf_discrete=vec![Complex::new(1.0, 1.0), Complex::new(-1.0, 1.0)];
/// let cdf=cf_dist_utils::get_cdf_discrete_cf(
///     x, x_min, x_max, &norm_cf_discrete
/// );
/// # }
/// ```
pub fn get_cdf_discrete_cf(x: f64, x_min: f64, x_max: f64, discrete_cf: &[Complex<f64>]) -> f64 {
    fang_oost::get_expectation_single_element_real(x_min, x_max, x, discrete_cf, |u, x, u_index| {
        vk_cdf(u, x, x_min, u_index)
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn var_works() {
        let mu = 2.0;
        let sigma = 5.0;
        let num_u = 128;
        let x_min = -20.0;
        let x_max = 25.0;
        let alpha = 0.05;
        let norm_cf = |u: &Complex<f64>| (u * mu + 0.5 * sigma * sigma * u * u).exp();
        let reference_var = 6.224268;
        let reference_es = 8.313564;
        let RiskMetric {
            expected_shortfall,
            value_at_risk,
        } = get_expected_shortfall_and_value_at_risk(
            alpha, num_u, x_min, x_max, 100, 0.0000001, &norm_cf,
        )
        .unwrap();
        assert_abs_diff_eq!(reference_var, value_at_risk, epsilon = 0.0001);
        assert_abs_diff_eq!(reference_es, expected_shortfall, epsilon = 0.001);
    }
    #[test]
    fn expectation_works() {
        let mu = 2.0;
        let sigma = 5.0;
        let num_u = 128;
        let x_min = -20.0;
        let x_max = 25.0;
        let norm_cf = |u: &Complex<f64>| (u * mu + 0.5 * sigma * sigma * u * u).exp();
        let discrete_cf = fang_oost::get_discrete_cf(num_u, x_min, x_max, norm_cf);
        let expected = get_expectation_discrete_cf(x_min, x_max, &discrete_cf);
        assert_abs_diff_eq!(expected, mu, epsilon = 0.0001);
    }
    #[test]
    fn error_works() {
        let mu = 2.0;
        let sigma = 5.0;
        let num_u = 128;
        let x_min = -20.0;
        let x_max = 25.0;
        let alpha = -0.5;
        let norm_cf = |u: &Complex<f64>| (u * mu + 0.5 * sigma * sigma * u * u).exp();
        let err = get_expected_shortfall_and_value_at_risk(
            alpha, num_u, x_min, x_max, 100, 0.0000001, &norm_cf,
        )
        .unwrap_err();
        assert_eq!(&err.to_string(), "Alpha must be between 0 and 1.");
    }
    #[test]
    fn variance_works() {
        let mu = 2.0;
        let sigma = 5.0;
        let num_u = 128;
        let x_min = -40.0;
        let x_max = 45.0;
        let norm_cf = |u: &Complex<f64>| (u * mu + 0.5 * sigma * sigma * u * u).exp();
        let discrete_cf = fang_oost::get_discrete_cf(num_u, x_min, x_max, norm_cf);
        let expected = get_variance_discrete_cf(x_min, x_max, &discrete_cf);
        assert_abs_diff_eq!(expected, sigma * sigma, epsilon = 0.0001);
    }
}