package com.smppw.core.reta.calc;

import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;

import java.util.List;

/**
 * @author zhengsongliang
 */
public class VaRFunction implements UnivariateFunction {
	private double p;
	private List<Double> dataList;

	public VaRFunction(double p, List<Double> dataList) {
		this.p = p;
		this.dataList=dataList;
	}
	
	@Override
	public double value(double VaR) {
		return p - cdfUltimate(VaR, dataList);
	}
	
	private double cdfUltimate(double VaR, List<Double> resultList) {
		double[] rets = List2Array(resultList) ;
		StandardDeviation standardDeviation = new StandardDeviation();
		standardDeviation.setBiasCorrected(false);
		double std = standardDeviation.evaluate(rets);
		double omega = Math.sqrt(Math.pow(1 + 0.05, 2) - 1) * std;
		double sum = 0;
		for (double mean : rets) {
			NormalDistribution normalDistributioin = new NormalDistribution(mean, omega);
			double cdf = normalDistributioin.cumulativeProbability(VaR);
			sum += cdf;
		}
		return sum / rets.length;
	}
	private double[] List2Array(List<Double> resultList){
		double[] rets = new double[resultList.size()];
		for(int i=0;i<resultList.size();i++){
			rets[i]=resultList.get(i);
		}
		return rets;
	}
}
