using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MarketData.DataAccess;
using MarketData.Utils;

namespace MarketData.ValueAtRisk
{
  public class HistoricalVaR
  {
    private int returnDays = 1;

    private HistoricalVaR()
    {
    }
    public static VaRResult GetVaR(PortfolioHoldings portfolioHoldings, double percentile,int returnDays=1)
    {
      VaRResult varResult=new VaRResult();
      if (null == portfolioHoldings || 0 == portfolioHoldings.Count) 
      {
        varResult.Success=false;
        return varResult;
      }
// This ensures that the pricing information for each holding is symmetric.  
// The piece of code that checks for jagged pricing should be handled differently.  For example, we should be able to continue the VaR analysis and simply account for no exposure to the 
// given symbol in the event of a lack of pricing data.  This would handle the current issue with securities that have been trading for less than the number of observation days.
      if (portfolioHoldings.Count > 1)    
      {
        int priceCount=-1;
        for (int index = 1; index < portfolioHoldings.Count; index++)
        {
          if(portfolioHoldings[index].Prices.Count>priceCount)priceCount=portfolioHoldings[index].Prices.Count;
        }
        for (int index = 1; index < portfolioHoldings.Count; index++)
        {
          if (portfolioHoldings[index].Prices.Count != priceCount) 
          {
            varResult.Success=false;
            varResult.Message=String.Format("Insufficient price history for {0}.  {1}/{2}",portfolioHoldings[index].Symbol,portfolioHoldings[index].Prices.Count,priceCount);
            return varResult;
          }
        }
      }
// Calculate total market value and then calculate the weightings of each holding
      double marketValue = portfolioHoldings.GetMarketValue();
      for (int index = 0; index < portfolioHoldings.Count; index++)
      {
        PortfolioHolding portfolioHolding = portfolioHoldings[index];
        portfolioHolding.Weight = portfolioHolding.MarketValue / marketValue;
      }
// Calculate the weighted returns for the observation period
      portfolioHoldings.SetReturnDays(returnDays);
      int numReturns=portfolioHoldings[0].Returns.Length;
      WeightedReturnsWithContribution weightedReturnsWithContrbution=new WeightedReturnsWithContribution();
      for (int index = 0; index < numReturns; index++)
      {
        for (int portfolioIndex = 0; portfolioIndex < portfolioHoldings.Count; portfolioIndex++)
        {
          PortfolioHolding portfolioHolding = portfolioHoldings[portfolioIndex];
          WeightedReturn weightedReturn=new WeightedReturn(portfolioHolding.Symbol,portfolioHolding.Prices[index].Date,portfolioHolding.Returns[index] * portfolioHolding.Weight);
          weightedReturnsWithContrbution.Add(index,weightedReturn);
        }
      }
      double[] weightedReturns=weightedReturnsWithContrbution.GetWeightedReturns();
      List<Contributions> contributionsList=weightedReturnsWithContrbution.GetContributions();
// Organize the weighted returns into bins so we can access the nth percentile rank
// The VaR nth percentile VaR is simply the weighted return at the given rank (i.e.) 90%, 95%, 99% within the bin
// The VaR result will be a negative percent and negative amount to show that this is a loss.  We display this as a positive number so we need to take the absolute value of the result
// ** To Do ** bring out the contributors to VaR at the given rank.
      BinManager<Contributions> binManager = new BinManager<Contributions>();
      BinResult<Contributions> binResult=binManager.GetVaRReturn(weightedReturns,contributionsList,percentile);
      Contributions contributions=binResult.Item;
      if(null==contributions){varResult.Success=false;return varResult;}
      Dictionary<String,PortfolioHolding> portfolioHoldingsBySymbol=new Dictionary<String,PortfolioHolding>();
      foreach(PortfolioHolding portfolioHolding in portfolioHoldings){if(!portfolioHoldingsBySymbol.ContainsKey(portfolioHolding.Symbol))portfolioHoldingsBySymbol.Add(portfolioHolding.Symbol,portfolioHolding);}
      foreach(Contribution contribution in contributions)
      {
        if(!portfolioHoldingsBySymbol.ContainsKey(contribution.Symbol))continue;
        portfolioHoldingsBySymbol[contribution.Symbol].Contribution=contribution.ContributionValue;
        portfolioHoldingsBySymbol[contribution.Symbol].ContributionDate=contribution.AnalysisDate;
      }
      return new VaRResult(binResult.Value, portfolioHoldings.GetMarketValue() * binResult.Value);
    }
    public int ReturnDays
    {
      get { return returnDays; }
      set { returnDays = value; }
    }
  }
}
