package com.strategyquant.extend.MonteCarloValues;

import com.strategyquant.lib.fitness.FitnessFunction;
import com.strategyquant.lib.language.L;
import com.strategyquant.lib.snippets.MonteCarloSim.MCStatsConst;
import com.strategyquant.lib.snippets.MonteCarloSim.MCValueComputer;
import com.strategyquant.lib.snippets.MonteCarloSim.MonteCarloStatValues;
import com.strategyquant.lib.utils.SQUtils;

public class MCPctNetProfit extends MCValueComputer {

	public MCPctNetProfit() {
		super(MCStatsConst.PCT_NET_PROFIT, FitnessFunction.MAXIMIZE);
		
		setColumnName(L.t("% Net Profit"));		
		setColumnWidth(100);
		setTooltip(L.t("% Net Profit (higher is better)"));
	}

	@Override
	protected double compute(MonteCarloStatValues statValues, double initialCapital, double[] orders, double avgTradesPerMonth) throws Exception {
		double accountBalance = initialCapital;
		double totalPctPL = 0;
		
		double pctPL[] = new double[orders.length];
		
		for(int i=0; i<orders.length; i++) {
			
			pctPL[i] = getStaticPercentagePL(orders[i], accountBalance);
			
			totalPctPL += pctPL[i];
			
			accountBalance += orders[i];
		}
				
		double twrPrevPL = 1;
		double twrTotalPLPrev = 0;
		double twrTotalPL = 0;
		totalPctPL = 0;
		
		for(int i=0; i<pctPL.length; i++) {
			//Time-Weighted Return
        	double temp = 1+(pctPL[i]/100);
        	double temp2 = temp * twrPrevPL;
			twrPrevPL = temp2;
			
			twrTotalPL = (temp2-1)*100;
			
			double PctPL_TWR = twrTotalPL - twrTotalPLPrev;
			
			twrTotalPLPrev = twrTotalPL;
			
	        // round all values to 2 decimal points
			totalPctPL += PctPL_TWR;
    	}		
		
		return totalPctPL;
	}
	
    /**
     * Gets the static percentage pl.
     *
     * @param pl the pl
     * @param accountSize the account size
     * @return the static percentage pl
     */
    private static double getStaticPercentagePL(double pl, double accountSize) {
		if(accountSize == 0) {
    		return 0;
    	}
    	
		return pl / (accountSize / 100);
	}
	
	@Override
	public String formatValue(double value) {
		return SQUtils.d2(value)+" %";
	}
}
