package com.smppw.core.reta.calc;


import com.smppw.common.pojo.dto.CompoundRet;
import com.smppw.common.pojo.enums.Frequency;
import com.smppw.core.reta.Rate;
import com.smppw.utils.DataUtil;

import java.util.List;

public class SortinoRatioMAR extends Rate {

	@Override
	public Double calc(List<CompoundRet> list, Frequency frequency, boolean ifAnnualized) {
		if (list == null || list.size() == 0) {
			return null;
		}
		Double min = list.get(0).getRetOfFund();
		for (CompoundRet value : list) {
			if (value.getRetOfFund() == null || value.getRetOfRf() == null) {
				continue;
			}
			if (min == null || min.compareTo(value.getRetOfFund()) > 0) {
				min = value.getRetOfFund();
			}
		}

		Double SortinoRatioMAR = 0.0;
		for (CompoundRet value : list) {
			if (value.getRetOfFund() != null && min != null) {
				SortinoRatioMAR += value.getRetOfFund() - min;
			}
		}
		SortinoRatioMAR /= (list.size() - 1);

		Double downSideStdDev = new DownsideStdDev().calc(list, frequency, false);
//		if (downSideStdDev == null) {
//			return null;
//		} else if (downSideStdDev == 0) {
//			return DataUtil.handleZeroValue(SortinoRatioMAR);
//		}
//		SortinoRatioMAR /= downSideStdDev;
		SortinoRatioMAR = DataUtil.divNearZeroValue(SortinoRatioMAR, downSideStdDev);
		if (SortinoRatioMAR == null) {
			return null;
		}

		Double result = ifAnnualized ? Rate.AnnualizedBySqrt(SortinoRatioMAR, frequency) : SortinoRatioMAR;
		return DataUtil.handleOverflowData(result);
	}
}
