package com.smppw.utils;

import com.smppw.common.pojo.dto.CompoundRet;
import com.smppw.core.reta.calc.VaRFunction;
import org.apache.commons.math3.analysis.solvers.BrentSolver;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author zhengsongliang
 */
public class FunctionUtil {

	public static Double HistoricalVaR(double Prob, List<Double> dataList) {
		Collections.sort(dataList);
		int k = (int) Math.floor(Prob * dataList.size());
		double d = Prob * dataList.size() - k;
		double res = 0;
		if (k < 1)
			return null;
		res = (dataList.get(k) - dataList.get(k - 1)) * d + dataList.get(k - 1);
		return -res;
	}

	public static Double HistoricalCVaR(double Prob, List<Double> dataList) {
		double sum = 0;
		Collections.sort(dataList);
		int k = (int) Math.floor(Prob * dataList.size());
		if (k == 0)
			return null;
		for (int i = 0; i < k; i++) {
			double mean = dataList.get(i);
			sum += mean;
		}
		return -sum / k;
	}

	public static double omega(List<Double> dataList) {
		double std = Statistics.stdDevBiased(dataList);
		double theta = 0.05;
		double omega = Math.sqrt(Math.pow(1 + theta, 2) - 1) * std;
		return omega;
	}

	public static double[] List2Array(List<Double> dataList) {
		double[] rets = new double[dataList.size()];
		for (int i = 0; i < dataList.size(); i++) {
			rets[i] = dataList.get(i);
		}
		return rets;
	}

	public static double getVaR(double target, List<Double> resultList) {
		VaRFunction func = new VaRFunction(target, resultList);
		double VaR = new BrentSolver().solve(1000, func, -100, 100);
		return -VaR;
	}

	public static List<Double> getFundRetList(List<CompoundRet> list) {
		List<Double> rets = new ArrayList<>();
		for (CompoundRet value : list) {
			if (value.getRetOfFund() != null) {
				rets.add(value.getRetOfFund());
			}
		}
		return rets;
	}
}
