/// <summary> /// Calculates the specified metric for the fast bootstrapper. /// </summary> /// <param name="interpolatedSpace">The intepolated Space.</param> /// <returns></returns> public override decimal CalculateImpliedQuote(IInterpolatedSpace interpolatedSpace) { if (AnalyticsModel == null) { AnalyticsModel = new InflationAssetAnalytic(); // DependencyCreator.Resolve<IModelAnalytic<ISimpleAssetParameters, RateMetrics>>(_modelIdentifier); } ISimpleDualAssetParameters analyticModelParameters = new DualRateAssetParameters { YearFraction = YearFraction, StartDiscountFactor = GetDiscountFactor(interpolatedSpace, AdjustedStartDate, BaseDate), EndDiscountFactor = GetDiscountFactor(interpolatedSpace, GetRiskMaturityDate(), BaseDate) }; //3. Get the Rate // if (FixedRate != null) { analyticModelParameters.Rate = MarketQuoteHelper.NormalisePriceUnits(FixedRate, "DecimalRate").value; } AnalyticResults = new RateAssetResults(); //4. Set the anaytic input parameters and Calculate the respective metrics // AnalyticResults = AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters, new[] { RateMetrics.ImpliedQuote }); return(AnalyticResults.ImpliedQuote); }
/// <summary> /// Calculates the specified metric for the fast bootstrapper. /// </summary> /// <param name="interpolatedSpace">The intepolated Space.</param> /// <returns></returns> public override decimal CalculateImpliedQuote(IInterpolatedSpace interpolatedSpace) { if (AnalyticsModel == null) { AnalyticsModel = new CommoditySpreadAssetAnalytic(); // DependencyCreator.Resolve<IModelAnalytic<ISimpleAssetParameters, RateMetrics>>(_modelIdentifier); } //3. Get the Rate var endDF = GetIndex(interpolatedSpace, RiskMaturityDate, BaseDate); var analyticModelParameters = new CommodityAssetParameters { CommodityForward = endDF }; Values = new[] { endDF }; if (Spread != null) { analyticModelParameters.Spread = MarketQuoteHelper.NormaliseGeneralPriceUnits(SpreadQuotationType, Spread, "MarketQuote").value; } AnalyticResults = new CommoditySpreadAssetResults(); //4. Set the anaytic input parameters and Calculate the respective metrics // AnalyticResults = AnalyticsModel.Calculate <ICommoditySpreadAssetResults, CommoditySpreadAssetResults>(analyticModelParameters, new[] { CommoditySpreadMetrics.ImpliedQuote }); return(AnalyticResults.ImpliedQuote); }
/// <summary> /// Calculates the specified metric for the fast bootstrapper. /// </summary> /// <param name="interpolatedSpace">The intepolated Space.</param> /// <returns></returns> public override decimal CalculateImpliedQuote(IInterpolatedSpace interpolatedSpace) { ISimpleOptionAssetParameters analyticModelParameters = new SimpleRateOptionAssetParameters(); //{ // YearFraction = YearFraction, // TimeToExpiry = TimeToExpiry, // StartDiscountFactor = // GetDiscountFactor(interpolatedSpace, // AdjustedStartDate, BaseDate), // EndDiscountFactor = // GetDiscountFactor(interpolatedSpace, // GetRiskMaturityDate(), BaseDate), // Volatility = Volatility //}; //3. Get the Rate // //if (Volatility != null) //{ // analyticModelParameters.Rate = MarketQuoteHelper.NormalisePriceUnits(FixedRate, "DecimalRate").value; //} AnalyticResults = new SimpleRateOptionAssetResults(); //4. Set the anaytic input parameters and Calculate the respective metrics // AnalyticResults = AnalyticsModel.Calculate <ISimpleRateOptionAssetResults, SimpleRateOptionAssetResults>(analyticModelParameters, new[] { RateOptionMetrics.ImpliedQuote }); return(AnalyticResults.ImpliedQuote); }
/// <summary> /// Calculates the specified metric for the fast bootstrapper. /// </summary> /// <param name="interpolatedSpace">The intepolated Space.</param> /// <returns></returns> public override decimal CalculateImpliedQuote(IInterpolatedSpace interpolatedSpace) { if (UseSimpleModel) { return(IndexAtMaturity); } if (AnalyticsModel == null) { AnalyticsModel = new CommodityAverageAssetAnalytic(); } ICommodityAverageAssetParameters analyticModelParameters = new CommodityAverageAssetParameters { StartIndex = GetIndexAtMaturity(interpolatedSpace, AdjustedStartDate, BaseDate), }; //3. Get the Index // if (MarketQuote != null) { analyticModelParameters.AverageIndex = MarketQuoteHelper.NormalisePriceUnits(MarketQuote, "DecimalRate").value; } //4. Set the anaytic input parameters and Calculate the respective metrics // AnalyticResults = AnalyticsModel.Calculate <ICommodityAssetResults, CommodityAssetResults>(analyticModelParameters, new[] { CommodityMetrics.IndexAtMaturity }); return(CalculationResults.IndexAtMaturity); }
/// <summary> /// Calculates the specified metric for the fast bootstrapper. /// </summary> /// <param name="interpolatedSpace">The intepolated Space.</param> /// <returns></returns> public override decimal CalculateImpliedQuote(IInterpolatedSpace interpolatedSpace) { if (AnalyticsModel == null) { AnalyticsModel = new RateSpreadAssetAnalytic(); // DependencyCreator.Resolve<IModelAnalytic<ISimpleAssetParameters, RateMetrics>>(_modelIdentifier); } //3. Get the Rate StartDiscountFactor = GetDiscountFactor(interpolatedSpace, AdjustedStartDate, BaseDate); EndDiscountFactor = GetDiscountFactor(interpolatedSpace, RiskMaturityDate, BaseDate); ISimpleRateAssetParameters analyticModelParameters = new RateAssetParameters { YearFraction = YearFraction, StartDiscountFactor = StartDiscountFactor, EndDiscountFactor = EndDiscountFactor }; var fixedRate = GetRate(StartDiscountFactor, EndDiscountFactor, YearFraction); if (Spread != null) { analyticModelParameters.Rate = fixedRate + MarketQuoteHelper .NormaliseGeneralPriceUnits(SpreadQuotationType, Spread, "DecimalRate").value; } AnalyticResults = new RateSpreadAssetResults(); //4. Set the anaytic input parameters and Calculate the respective metrics // AnalyticResults = AnalyticsModel.Calculate <IRateSpreadAssetResults, RateSpreadAssetResults>(analyticModelParameters, new[] { RateSpreadMetrics.ImpliedQuote }); return(AnalyticResults.ImpliedQuote); }
/// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> public override BasicAssetValuation Calculate(IAssetControllerData modelData) { ModelData = modelData; if (AnalyticsModel == null) { AnalyticsModel = new EquityAssetAnalytic(); //DependencyCreator.Resolve<IModelAnalytic<ISimpleAssetParameters, RateMetrics>>(_modelIdentifier); } var metrics = MetricsHelper.GetMetricsToEvaluate(Metrics, AnalyticsModel.Metrics); // Determine if DFAM has been requested - if so thats all we evaluate - every other metric is ignored // var bEvalIndexAtMaturity = false; if (metrics.Contains(EquityMetrics.IndexAtMaturity)) { bEvalIndexAtMaturity = true; // Remove all metrics except DFAM // metrics.RemoveAll(metricItem => metricItem != EquityMetrics.IndexAtMaturity); } var metricsToEvaluate = metrics.ToArray(); IEquityAssetParameters analyticModelParameters = new EquityAssetParameters(); CalculationResults = new EquityAssetResults(); var marketEnvironment = modelData.MarketEnvironment; IEquityCurve equitycurve = null; //1. instantiate curve if (marketEnvironment.GetType() == typeof(SimpleMarketEnvironment)) { equitycurve = (IEquityCurve)((ISimpleMarketEnvironment)marketEnvironment).GetPricingStructure(); } if (marketEnvironment.GetType() == typeof(MarketEnvironment)) { equitycurve = (IEquityCurve)modelData.MarketEnvironment.GetPricingStructure(EquityCurveName); } if (equitycurve != null) { //1. Get the current equity value from the curve. var equityValue = GetEquityFactor(equitycurve, modelData.ValuationDate, SettlementDate); //2. Set the market rate analyticModelParameters.Multiplier = Multiplier; analyticModelParameters.Quote = QuoteValue; analyticModelParameters.EquityPrice = equityValue; analyticModelParameters.NotionalAmount = Notional; //3. Set the anaytic input parameters and Calculate the respective metrics AnalyticModelParameters = analyticModelParameters; CalculationResults = AnalyticsModel.Calculate <IEquityAssetResults, EquityAssetResults>(analyticModelParameters, metricsToEvaluate); if (bEvalIndexAtMaturity) { //4. Set the anaytic input parameters and Calculate the respective metrics // IndexAtMaturity = CalculationResults.IndexAtMaturity; } return(GetValue(CalculationResults)); } return(null); }
/// <summary> /// /// </summary> /// <param name="forecastcurve"></param> /// <param name="parameters"></param> /// <returns></returns> protected IRateOptionAssetResults ForecastRiskCalculationHelper(IRateCurve forecastcurve, IRateOptionAssetParameters parameters) { parameters.ForecastDiscountFactors = GetDiscountFactors(forecastcurve, AdjustedPeriodDates.ToArray(), BaseDate); //Set the analytic input parameters and Calculate the respective metrics // return(AnalyticsModel.Calculate <IRateOptionAssetResults, RateOptionAssetResults>(parameters, new[] { RateOptionMetrics.NPV })); }
/// <summary> /// /// </summary> /// <param name="logger"></param> /// <param name="cache"></param> /// <param name="ratecurve"></param> /// <param name="fixingCalendar"></param> /// <param name="paymentCalendar"></param> /// <returns></returns> public virtual decimal[] CalculatePDH(ILogger logger, ICoreCache cache, CurveBase ratecurve, IBusinessCalendar fixingCalendar, IBusinessCalendar paymentCalendar) { if (AnalyticsModel == null) { switch (ModelIdentifier) { case "SimpleSwapAsset": case "ClearedSwapAsset": AnalyticsModel = new SimpleSwapAssetAnalytic(); break; case "SimpleDiscountSwapAsset": case "DiscountClearedSwapAsset": AnalyticsModel = new SimpleDiscountSwapAssetAnalytic(); break; } } var result = new List <decimal>(); if (ratecurve != null) { var riskCurves = ratecurve.CreateCurveRiskSet(1); ISwapAssetParameters analyticModelParameters = new IRSwapAssetParameters { NotionalAmount = Notional, //2. Get the discount factors DiscountFactors = GetDiscountFactors(ratecurve, AdjustedPeriodDates.ToArray(), BaseDate), //3. Get the respective year fractions YearFractions = YearFractions, Rate = MarketQuoteHelper.NormalisePriceUnits( FixedRate, "DecimalRate").value }; //4. Get the Weightings analyticModelParameters.Weightings = CreateWeightings(CDefaultWeightingValue, analyticModelParameters.DiscountFactors.Length - 1); //4. Set the anaytic input parameters and Calculate the respective metrics // if (AnalyticsModel != null) { var analyticResults = AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters, new[] { RateMetrics.NPV }); var baseNPV = analyticResults.NPV; //Now loop through the risk curves. foreach (var curve in riskCurves) { analyticResults = RiskCalculationHelper((IRateCurve)curve, analyticModelParameters); result.Add(analyticResults.NPV - baseNPV); } } } return(result.ToArray()); }
/// <summary> /// /// </summary> /// <param name="ratecurve"></param> /// <param name="parameters"></param> /// <returns></returns> protected virtual IRateAssetResults RiskCalculationHelper(IRateCurve ratecurve, ISwapAssetParameters parameters) { parameters.DiscountFactors = GetDiscountFactors(ratecurve, AdjustedPeriodDates.ToArray(), BaseDate); //Set the anaytic input parameters and Calculate the respective metrics // return(AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(parameters, new[] { RateMetrics.NPV })); }
/// <summary> /// /// </summary> /// <param name="discountCurve"></param> /// <param name="parameters"></param> /// <returns></returns> protected override IRateAssetResults RiskCalculationHelper(IRateCurve discountCurve, ISwapAssetParameters parameters) { parameters.FloatingLegDiscountFactors = GetDiscountFactors(discountCurve, AdjustedPeriodDates.ToArray(), BaseDate); parameters.DiscountFactors = GetDiscountFactors(discountCurve, FloatingLegAdjustedPeriodDates.ToArray(), BaseDate); //Set the analytic input parameters and Calculate the respective metrics // return(AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(parameters, new[] { RateMetrics.NPVChange })); }
/// <summary> /// Calculates the specified metric for the fast bootstrapper. /// </summary> /// <param name="interpolatedSpace">The intepolated Space.</param> /// <returns></returns> public override decimal CalculateImpliedQuote(IInterpolatedSpace interpolatedSpace) { if (AnalyticsModel == null) { switch (ModelIdentifier) { case "SwapAsset": case "SimpleSwapAsset": case "ClearedSwapAsset": AnalyticsModel = new SimpleSwapAssetAnalytic(); break; case "DiscountSwapAsset": case "SimpleDiscountSwapAsset": case "DiscountClearedSwapAsset": AnalyticsModel = new SimpleDiscountSwapAssetAnalytic(); break; } } ISwapAssetParameters analyticModelParameters = new IRSwapAssetParameters { NotionalAmount = Notional, //2. Get the discount factors DiscountFactors = GetDiscountFactors(interpolatedSpace, AdjustedPeriodDates.ToArray(), BaseDate), //3. Get the respective year fractions YearFractions = YearFractions, Rate = MarketQuoteHelper.NormalisePriceUnits( FixedRate, "DecimalRate").value }; //4. Get the Weightings analyticModelParameters.Weightings = CreateWeightings(CDefaultWeightingValue, analyticModelParameters.DiscountFactors.Length - 1); AnalyticResults = new RateAssetResults(); //4. Set the anaytic input parameters and Calculate the respective metrics // if (AnalyticsModel != null) { AnalyticResults = AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters, new[] { RateMetrics.ImpliedQuote }); } return(AnalyticResults.ImpliedQuote); }
/// <summary> /// Calculates the specified metric for the fast bootstrapper. /// </summary> /// <param name="interpolatedSpace">The intepolated Space.</param> /// <returns></returns> public override decimal CalculateDiscountFactorAtMaturity(IInterpolatedSpace interpolatedSpace) { if (AnalyticsModel == null) { switch (ModelIdentifier) { case "SwapAsset": case "SimpleSwapAsset": case "ClearedSwapAsset": AnalyticsModel = new SimpleSwapAssetAnalytic(); break; case "DiscountSwapAsset": case "SimpleDiscountSwapAsset": case "DiscountClearedSwapAsset": AnalyticsModel = new SimpleDiscountSwapAssetAnalytic(); break; } } ISwapAssetParameters analyticModelParameters = new IRSwapAssetParameters() { YearFractions = YearFractions, StartDiscountFactor = GetDiscountFactor(interpolatedSpace, AdjustedStartDate, BaseDate) }; //3. Get the Rate // if (FixedRate != null) { analyticModelParameters.Rate = MarketQuoteHelper.NormalisePriceUnits(FixedRate, "DecimalRate").value; } AnalyticResults = new RateAssetResults(); //4. Set the anaytic input parameters and Calculate the respective metrics // if (AnalyticsModel == null) { return(1.0m); } AnalyticResults = AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters, new[] { RateMetrics.DiscountFactorAtMaturity }); return(AnalyticResults.DiscountFactorAtMaturity); }
/// <summary> /// Calculates the specified metric for the fast bootstrapper. /// </summary> /// <param name="interpolatedSpace">The interpolated Space.</param> /// <returns></returns> public override decimal CalculateDiscountFactorAtMaturity(IInterpolatedSpace interpolatedSpace) { if (AnalyticsModel == null) { switch (ModelIdentifier) { case "SwapAsset": case "ClearedSwapAsset": AnalyticsModel = new SimpleSwapAssetAnalytic(); // break; } } ISwapAssetParameters analyticModelParameters = new IRSwapAssetParameters { YearFractions = YearFractions, StartDiscountFactor = GetDiscountFactor(interpolatedSpace, AdjustedStartDate, BaseDate), Rate = CalculateImpliedQuote(interpolatedSpace) + MarketQuoteHelper .NormaliseGeneralPriceUnits(QuotationType, Spread, "DecimalRate").value }; //3. Set the implied Rate with a spread // AnalyticResults = new RateAssetResults(); //4. Set the anaytic input parameters and Calculate the respective metrics // if (AnalyticsModel != null) { AnalyticResults = AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters, new[] { RateMetrics.DiscountFactorAtMaturity }); } return(AnalyticResults.DiscountFactorAtMaturity); }
/// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; CalculationResults = null; UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); // 1. First derive the analytics to be evaluated via the stream controller model // NOTE: These take precedence of the child model metrics if (AnalyticsModel == null) { AnalyticsModel = new FxSwapAnalytic(); } var swapControllerMetrics = ResolveModelMetrics(AnalyticsModel.Metrics); AssetValuation swapValuation; //Sets the evolution type for calculations. foreach (var leg in Legs) { leg.PricingStructureEvolutionType = PricingStructureEvolutionType; leg.BucketedDates = BucketedDates; leg.Multiplier = Multiplier; } var legControllers = new List <InstrumentControllerBase>(GetLegs()); //The assetValuation list. var childValuations = new List <AssetValuation>(); // 2. Now evaluate only the child specific metrics (if any) if (modelData.MarketEnvironment.GetType() == typeof(MarketEnvironment)) { childValuations.AddRange(legControllers.Select(leg => leg.Calculate(modelData))); } else { childValuations = EvaluateChildMetrics(legControllers, modelData, Metrics); } var childControllerValuations = AssetValuationHelper.AggregateMetrics(childValuations, new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); childControllerValuations.id = Id + ".FxLeg"; // Child metrics have now been calculated so we can now evaluate the stream model metrics if (swapControllerMetrics.Count > 0) { IFxSwapParameters analyticModelParameters = new FxSwapParameters { Multiplier = Multiplier, //AccrualFactor = AggregateCouponMetric(InstrumentMetrics.AccrualFactor), //FloatingNPV = AggregateCouponMetric(InstrumentMetrics.FloatingNPV), //NPV = AggregateCouponMetric(InstrumentMetrics.NPV) }; CalculationResults = AnalyticsModel.Calculate <IFxSwapInstrumentResults, FxSwapInstrumentResults>(analyticModelParameters, swapControllerMetrics.ToArray()); // Now merge back into the overall stream valuation var swapControllerValuation = GetValue(CalculationResults, modelData.ValuationDate); swapValuation = AssetValuationHelper.UpdateValuation(swapControllerValuation, childControllerValuations, ConvertMetrics(swapControllerMetrics), new List <string>(Metrics)); } else { swapValuation = childControllerValuations; } CalculationPerformedIndicator = true; swapValuation.id = Id; return(swapValuation); }
/// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; CalculationResults = null; UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); // 1. First derive the analytics to be evaluated via the stream controller model // NOTE: These take precendence of the child model metrics if (AnalyticsModel == null) { AnalyticsModel = new CapFloorInstrumentAnalytic(); } var swapControllerMetrics = ResolveModelMetrics(AnalyticsModel.Metrics); AssetValuation swapValuation; //Sets the evolution type for calculations. CapFloorLeg.PricingStructureEvolutionType = PricingStructureEvolutionType; CapFloorLeg.BucketedDates = BucketedDates; CapFloorLeg.Multiplier = Multiplier; if (AdditionalPayments != null) { foreach (var payment in AdditionalPayments) { payment.PricingStructureEvolutionType = PricingStructureEvolutionType; payment.BucketedDates = BucketedDates; payment.Multiplier = Multiplier; } } //The assetValuation list. var childValuations = new List <AssetValuation> { CapFloorLeg.Calculate(modelData) }; // 2. Now evaluate only the child specific metrics (if any) if (GetAdditionalPayments() != null) { var paymentControllers = new List <InstrumentControllerBase>(GetAdditionalPayments()); childValuations.AddRange(paymentControllers.Select(payment => payment.Calculate(modelData))); } var childControllerValuations = AssetValuationHelper.AggregateMetrics(childValuations, new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); childControllerValuations.id = Id + ".CapFloorStreams"; // Child metrics have now been calculated so we can now evaluate the stream model metrics if (swapControllerMetrics.Count > 0) { //Generate the vectors var streamAccrualFactor = AssetValuationHelper.GetQuotationByMeasureType(childValuations[0], InstrumentMetrics.AccrualFactor.ToString()); var streamFloatingNPV = AssetValuationHelper.GetQuotationByMeasureType(childValuations[0], InstrumentMetrics.FloatingNPV.ToString()); var streamNPV = AssetValuationHelper.GetQuotationByMeasureType(childValuations[0], InstrumentMetrics.NPV.ToString()); IIRSwapInstrumentParameters analyticModelParameters = new SwapInstrumentParameters { AccrualFactor = streamAccrualFactor.value, FloatingNPV = streamFloatingNPV.value, NPV = streamNPV.value //, MarketQuote = MarketQuote. }; AnalyticModelParameters = analyticModelParameters; CalculationResults = AnalyticsModel.Calculate <IIRSwapInstrumentResults, SwapInstrumentResults>(analyticModelParameters, swapControllerMetrics.ToArray()); // Now merge back into the overall stream valuation var swapControllerValuation = GetValue(CalculationResults, modelData.ValuationDate); swapValuation = AssetValuationHelper.UpdateValuation(swapControllerValuation, childControllerValuations, ConvertMetrics(swapControllerMetrics), new List <string>(Metrics)); } else { swapValuation = childControllerValuations; } CalculationPerfomedIndicator = true; swapValuation.id = Id; return(swapValuation); }
/// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> public override BasicAssetValuation Calculate(IAssetControllerData modelData) { ModelData = modelData; if (AnalyticsModel == null) { AnalyticsModel = new RateAssetAnalytic(); //DependencyCreator.Resolve<IModelAnalytic<ISimpleAssetParameters, RateMetrics>>(_modelIdentifier); } var metrics = MetricsHelper.GetMetricsToEvaluate(Metrics, AnalyticsModel.Metrics); // Determine if DFAM has been requested - if so thats all we evaluate - every other metric is ignored // var bEvalDiscountFactorAtMaturity = false; if (metrics.Contains(RateMetrics.DiscountFactorAtMaturity)) { bEvalDiscountFactorAtMaturity = true; // Remove all metrics except DFAM // metrics.RemoveAll(metricItem => metricItem != RateMetrics.DiscountFactorAtMaturity); } ISimpleRateAssetParameters analyticModelParameters = new RateAssetParameters { YearFraction = YearFraction }; CalculationResults = new RateAssetResults(); var metricsToEvaluate = metrics.ToArray(); var marketEnvironment = modelData.MarketEnvironment; IRateCurve curve = null; //1. instantiate curve if (marketEnvironment.GetType() == typeof(SimpleMarketEnvironment)) { curve = (IRateCurve)((ISimpleMarketEnvironment)marketEnvironment).GetPricingStructure(); CurveName = curve.GetPricingStructureId().UniqueIdentifier; } if (marketEnvironment.GetType() == typeof(SimpleRateMarketEnvironment)) { curve = ((ISimpleRateMarketEnvironment)marketEnvironment).GetRateCurve(); CurveName = curve.GetPricingStructureId().UniqueIdentifier; } if (marketEnvironment.GetType() == typeof(SwapLegEnvironment)) { curve = ((ISwapLegEnvironment)marketEnvironment).GetDiscountRateCurve(); CurveName = curve.GetPricingStructureId().UniqueIdentifier; } if (marketEnvironment.GetType() == typeof(MarketEnvironment)) { curve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(CurveName); } //2. get start df = curve.getvalue(this._adjustedStartDate); // analyticModelParameters.StartDiscountFactor = GetDiscountFactor(curve, AdjustedStartDate, modelData.ValuationDate); //3. Get the Rate // if (FixedRate != null) { analyticModelParameters.Rate = MarketQuoteHelper.NormalisePriceUnits(FixedRate, "DecimalRate").value; } if (bEvalDiscountFactorAtMaturity) { //4. Set the anaytic input parameters and Calculate the respective metrics // CalculationResults = AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters, metricsToEvaluate); EndDiscountFactor = CalculationResults.DiscountFactorAtMaturity; } else { analyticModelParameters.NotionalAmount = Notional; //3. Get the end discount factor // EndDiscountFactor = GetDiscountFactor(curve, GetRiskMaturityDate(), modelData.ValuationDate); analyticModelParameters.EndDiscountFactor = EndDiscountFactor; analyticModelParameters.PaymentDiscountFactor = analyticModelParameters.EndDiscountFactor; //4. Set the anaytic input parameters and Calculate the respective metrics // CalculationResults = AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters, metricsToEvaluate); } return(GetValue(CalculationResults)); }
public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; CalculationResults = null; UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); // 1. First derive the analytics to be evaluated via the stream controller model // NOTE: These take precendence of the child model metrics if (AnalyticsModel == null) { AnalyticsModel = new FxOptionLegAnalytic(); } var marketEnvironment = modelData.MarketEnvironment as IFxLegEnvironment; AssetValuation streamValuation; //Check if risk calc are required. bool delta0PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta0PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta0PDH.ToString()) != null; bool delta1PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta1PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta1PDH.ToString()) != null; var streamControllerMetrics = ResolveModelMetrics(AnalyticsModel.Metrics); var childValuations = new List <AssetValuation>(); // 2. Now evaluate only the child specific metrics (if any) foreach (var payment in FxLeg.Payments) { payment.Multiplier = Multiplier; payment.PricingStructureEvolutionType = PricingStructureEvolutionType; payment.BucketedDates = BucketedDates; } foreach (var premium in Premia) { premium.Multiplier = 1.0m; premium.PricingStructureEvolutionType = PricingStructureEvolutionType; premium.BucketedDates = BucketedDates; } if (marketEnvironment != null) { //Modify the second market. var modelData1 = new InstrumentControllerData(modelData.AssetValuation, marketEnvironment.GetExchangeCurrencyPaymentEnvironment1(), modelData.ValuationDate, modelData.ReportingCurrency); var modelData2 = new InstrumentControllerData(modelData.AssetValuation, marketEnvironment.GetExchangeCurrencyPaymentEnvironment2(), modelData.ValuationDate, modelData.ReportingCurrency); childValuations.Add(Currency1Payment.Calculate(modelData1)); childValuations.Add(Currency2Payment.Calculate(modelData2)); childValuations.AddRange(Premia.Select(premium => premium.Calculate(modelData2))); } else if (modelData.MarketEnvironment.GetType() == typeof(MarketEnvironment)) { var market = (MarketEnvironment)modelData.MarketEnvironment; if (delta0PDH) { // //Force building of the risk curves. // market.SearchForPerturbedPricingStructures(FxIndexCurveName, "delta0PDH");//TODO Need to add this perturbation to fxCurve. } if (delta1PDH) { //Force building of the risk curves. market.SearchForPerturbedPricingStructures(FxLeg.Currency1DiscountCurveName, "delta1PDH"); market.SearchForPerturbedPricingStructures(FxLeg.Currency2DiscountCurveName, "delta1PDH"); } childValuations = EvaluateChildMetrics(GetChildren().ToList(), modelData, Metrics); //childValuations.Add(Currency1Payment.Calculate(modelData)); } var paymentValuation = AssetValuationHelper.AggregateMetrics(childValuations, new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); var childControllerValuations = new List <AssetValuation> { paymentValuation }; TimeToExpiry = GetPaymentYearFraction(ModelData.ValuationDate, ExpiryDate); var volatilityCurveNodeTime = GetPaymentYearFraction(ModelData.ValuationDate, ValueDate); // Child metrics have now been calculated so we can now evaluate the stream model metrics if (streamControllerMetrics.Count > 0) { if (modelData.MarketEnvironment is MarketEnvironment market) { var fxCurve = (IFxCurve)market.SearchForPricingStructureType(FxLeg.FxIndexCurveName); var indexSurface = (IVolatilitySurface)market.SearchForPricingStructureType(VolatilitySurfaceName); if (HybridValuation) { var curve1 = (IRateCurve)market.SearchForPricingStructureType(FxLeg.Currency1DiscountCurveName); var curve2 = (IRateCurve)market.SearchForPricingStructureType(FxLeg.Currency2DiscountCurveName); var flag = FxLeg.ExchangeRate.quotedCurrencyPair.quoteBasis == QuoteBasisEnum.Currency2PerCurrency1; AnalyticsModel = new FxOptionLegAnalytic(modelData.ValuationDate, RiskMaturityDate, fxCurve, curve1, curve2, flag, FxStrike, TimeToExpiry, volatilityCurveNodeTime, indexSurface, FxOptionType); } else { AnalyticsModel = new FxOptionLegAnalytic(modelData.ValuationDate, RiskMaturityDate, fxCurve, FxStrike, TimeToExpiry, volatilityCurveNodeTime, indexSurface, FxOptionType); } } decimal?premium = null; if (Premia.Count > 1) { premium = Premia[0].PaymentAmount.amount; // We assume only a single premium in the basic case. } IFxOptionLegParameters analyticModelParameters = new FxOptionLegParameters { Premium = premium, }; CalculationResults = AnalyticsModel.Calculate <IFxOptionLegInstrumentResults, FxOptionLegInstrumentResults>( analyticModelParameters, streamControllerMetrics.ToArray()); // Now merge back into the overall stream valuation var streamControllerValuation = GetValue(CalculationResults, modelData.ValuationDate); streamValuation = AssetValuationHelper.UpdateValuation(streamControllerValuation, childControllerValuations, ConvertMetrics(streamControllerMetrics), new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); } else { streamValuation = paymentValuation; } CalculationPerformedIndicator = true; streamValuation.id = Id; return(streamValuation); }
/// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; AnalyticsModel = new FxOptionAnalytic(); CalculationResults = null; YearFractionToCashFlowPayment = Convert.ToDecimal(CDefaultDayCounter.YearFraction(ModelData.ValuationDate, PaymentDate)); //Make sure there are some bucket dates even if not set previously. if (BucketedDates.Length < 1) { UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); } IsRealised = HasBeenRealised(ModelData.ValuationDate); //Add the extra metrics required var quotes = ModelData.AssetValuation.quote.ToList(); if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.NPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyNPV.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.LocalCurrencyNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyNPV.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.RiskNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.NPV.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.LocalCurrencyExpectedValue.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyExpectedValue.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } //Check if risk calc are required. bool delta1PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta1PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta1PDH.ToString()) != null; //Check if risk calc are required. bool delta0PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta0PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta0PDH.ToString()) != null; ModelData.AssetValuation.quote = quotes.ToArray(); //Set the cash flowdetails. HasReset = modelData.ValuationDate > ResetDate; IsRealised = HasBeenRealised(ModelData.ValuationDate); TimeToExpiry = GetPaymentYearFraction(ModelData.ValuationDate, AdjustedFixingDate); var volatilityCurveNodeTime = GetPaymentYearFraction(ModelData.ValuationDate, PaymentDate); IFxCurve fxCurve = null; IRateCurve discountCurve = null; IFxCurve currencyCurve = null; IVolatilitySurface volSurface = null; var metrics = ResolveModelMetrics(AnalyticsModel.Metrics); //var metricsToEvaluate = metrics.ToArray(); //if (metricsToEvaluate.Length > 0) //{ YearFractionToCashFlowPayment = GetPaymentYearFraction(ModelData.ValuationDate, PaymentDate); var reportingCurrency = ModelData.ReportingCurrency == null ? PaymentCurrency.Value : ModelData.ReportingCurrency.Value; decimal?premium = null; if (Premium != null) { premium = Premium; } IFxRateCashflowParameters analyticModelParameters = new FxRateCashflowParameters { ValuationDate = modelData.ValuationDate, PaymentDate = PaymentDate, Currency = PaymentCurrency.Value, ReportingCurrency = reportingCurrency, IsRealised = IsRealised, IsReset = HasReset, NotionalAmount = NotionalAmount.amount, CurveYearFraction = YearFractionToCashFlowPayment, ExpiryYearFraction = TimeToExpiry, Premium = premium }; // Curve Related if (modelData.MarketEnvironment.GetType() == typeof(MarketEnvironment)) { var market = (MarketEnvironment)modelData.MarketEnvironment; discountCurve = (IRateCurve)market.SearchForPricingStructureType(DiscountCurveName); discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; volSurface = (IVolatilitySurface)market.SearchForPricingStructureType(VolatilitySurfaceName); volSurface.PricingStructureEvolutionType = PricingStructureEvolutionType; var currencyCurveName = MarketEnvironmentHelper.ResolveFxCurveNames(StartFxRate.quotedCurrencyPair.currency1.Value, StartFxRate.quotedCurrencyPair.currency2.Value); currencyCurve = (IFxCurve)market.SearchForPricingStructureType(currencyCurveName); currencyCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; analyticModelParameters.DiscountCurve = discountCurve; if (delta1PDH) { var riskMarket = market.SearchForPerturbedPricingStructures(DiscountCurveName, "delta1PDH"); analyticModelParameters.Delta1PDHCurves = riskMarket; analyticModelParameters.Delta1PDHPerturbation = 10; } if (delta0PDH)//TODO Do this for the fxrate { //var riskMarket = market.SearchForPerturbedPricingStructures(DiscountCurveName, "delta0PDH"); // //TODO The fx deltas //analyticModelParameters.Delta1PDHCurves = riskMarket; //analyticModelParameters.Delta1PDHPerturbation = 10; } if (modelData.ReportingCurrency.Value != PaymentCurrency.Value) { string curveName = MarketEnvironmentHelper.ResolveFxCurveNames(PaymentCurrency.Value, modelData.ReportingCurrency.Value); fxCurve = (IFxCurve)market.SearchForPricingStructureType(curveName); fxCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; analyticModelParameters.ReportingCurrencyFxCurve = fxCurve; } if (HybridValuation) { var currency1RateCurve = (IRateCurve)market.SearchForPricingStructureType(Currency1DiscountCurveName); currency1RateCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; var currency2RateCurve = (IRateCurve)market.SearchForPricingStructureType(Currency2DiscountCurveName); currency2RateCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; AnalyticsModel = new FxOptionAnalytic(ModelData.ValuationDate, PaymentDate, currencyCurve, currency1RateCurve, currency2RateCurve, IsSettlementInCurrency1, !InvertFxRate, Strike, TimeToExpiry, volatilityCurveNodeTime, volSurface, FxOptionType, fxCurve); } } // store inputs and results from this run AnalyticModelParameters = analyticModelParameters; if (!HybridValuation) { AnalyticsModel = new FxOptionAnalytic(ModelData.ValuationDate, PaymentDate, Strike, TimeToExpiry, volatilityCurveNodeTime, fxCurve, currencyCurve, discountCurve, volSurface, FxOptionType); } //TODO Fix this with a generic index curve. //AnalyticsModel = analyticsModel; CalculationResults = AnalyticsModel.Calculate <IFloatingCashflowResults, FloatingCashflowResults>( AnalyticModelParameters, metrics.ToArray()); CalculationPerfomedIndicator = true; PaymentDiscountFactor = ((FxRateCashflowAnalytic)AnalyticsModel).PaymentDiscountFactor; ForecastAmount = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyExpectedValue, PaymentAmount.currency); NPV = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyNPV, PaymentAmount.currency); AssetValuation valuation = GetValue(CalculationResults, modelData.ValuationDate); valuation.id = Id; return(valuation); }
/// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; AnalyticsModel = new FloatingRateCouponAnalytic(); RequiresReset = modelData.ValuationDate > ResetDate; IsRealised = HasBeenRealised(ModelData.ValuationDate); //Make sure there are some bucket dates even if not set previously. if (BucketedDates.Length < 1) { UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); } //Add the extra metrics required var quotes = ModelData.AssetValuation.quote.ToList(); if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.BreakEvenRate.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.BreakEvenRate.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.AccrualFactor.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.AccrualFactor.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.FloatingNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.FloatingNPV.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.NPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.NPV.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.RiskNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.RiskNPV.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.LocalCurrencyNPV.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyExpectedValue.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.LocalCurrencyExpectedValue.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } //Check if risk calc are required. bool delta1PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta1PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta1PDH.ToString()) != null; //Check if risk calc are required. bool delta0PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta0PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta0PDH.ToString()) != null; ModelData.AssetValuation.quote = quotes.ToArray(); var metrics = ResolveModelMetrics(AnalyticsModel.Metrics); IFxCurve fxCurve = null; IRateCurve discountCurve = null; IRateCurve forecastCurve = null; //// Determine if DFAM has been requested - if so thats all we evaluate - every other metric is ignored //if (metrics.Contains(InstrumentMetrics.DiscountFactorAtMaturity)) //{ // metrics.RemoveAll(metricItem => metricItem != InstrumentMetrics.DiscountFactorAtMaturity); //} //Set the forrecast rate dates. The ForecastRateInterpolation shhould have been set. ForwardStartDate = AccrualStartDate; ForwardEndDate = ForecastRateInterpolation ? AccrualEndDate : AdjustedDateHelper.ToAdjustedDate(FixingCalendar, ForecastRateIndex.indexTenor.Add(ForwardStartDate), AccrualBusinessDayAdjustments); //var metricsToEvaluate = metrics.ToArray(); if (metrics.Count > 0) { YearFractionToCashFlowPayment = GetPaymentYearFraction(ModelData.ValuationDate, PaymentDate); var reportingCurrency = ModelData.ReportingCurrency == null ? PaymentCurrency.Value : ModelData.ReportingCurrency.Value; var amount = NotionalAmount.amount; IRateCouponParameters analyticModelParameters = new RateCouponParameters { Multiplier = Multiplier, ValuationDate = modelData.ValuationDate, PaymentDate = PaymentDate, Currency = PaymentCurrency.Value, ReportingCurrency = reportingCurrency, DiscountType = DiscountType, IsRealised = IsRealised, HasReset = RequiresReset, NotionalAmount = amount, Spread = Margin, YearFraction = CouponYearFraction, CurveYearFraction = YearFractionToCashFlowPayment }; decimal?discountRate = null; // Curve Related if (modelData.MarketEnvironment is ISwapLegEnvironment environment) { var streamMarket = environment; discountCurve = streamMarket.GetDiscountRateCurve(); discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; forecastCurve = streamMarket.GetForecastRateCurve(); forecastCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; DiscountCurveName = discountCurve.GetPricingStructureId().UniqueIdentifier; analyticModelParameters.DiscountCurve = discountCurve; ForecastCurveName = forecastCurve.GetPricingStructureId().UniqueIdentifier; analyticModelParameters.ForecastCurve = forecastCurve; // Bucketed Delta if (BucketedDates.Length > 1) { analyticModelParameters.PeriodAsTimesPerYear = GetPaymentYearFraction(BucketedDates[0], BucketedDates[1]); analyticModelParameters.BucketedDiscountFactors = GetBucketedDiscountFactors(discountCurve, ModelData. ValuationDate, BucketedDates); } //Check for currency. if (ModelData.ReportingCurrency != null) { if (ModelData.ReportingCurrency.Value != PaymentCurrency.Value) { fxCurve = streamMarket.GetReportingCurrencyFxCurve(); fxCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; analyticModelParameters.ReportingCurrencyFxCurve = fxCurve; } } AnalyticModelParameters = analyticModelParameters; } else if (modelData.MarketEnvironment.GetType() == typeof(MarketEnvironment)) { var market = (MarketEnvironment)modelData.MarketEnvironment; discountCurve = (IRateCurve)market.SearchForPricingStructureType(DiscountCurveName); discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; forecastCurve = (IRateCurve)market.SearchForPricingStructureType(ForecastCurveName); forecastCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; analyticModelParameters.DiscountCurve = discountCurve; analyticModelParameters.ForecastCurve = forecastCurve; // Bucketed Delta if (BucketedDates.Length > 1) { analyticModelParameters.PeriodAsTimesPerYear = GetPaymentYearFraction(BucketedDates[0], BucketedDates[1]); analyticModelParameters.BucketedDiscountFactors = GetBucketedDiscountFactors(discountCurve, ModelData. ValuationDate, BucketedDates); } if (delta1PDH) { var riskMarket = market.SearchForPerturbedPricingStructures(DiscountCurveName, "delta1PDH"); analyticModelParameters.Delta1PDHCurves = riskMarket; analyticModelParameters.Delta1PDHPerturbation = 10; } if (delta0PDH) { var riskMarket = market.SearchForPerturbedPricingStructures(ForecastCurveName, "delta0PDH"); analyticModelParameters.Delta0PDHCurves = riskMarket; analyticModelParameters.Delta0PDHPerturbation = 10; } //Check for currency. if (ModelData.ReportingCurrency != null) { if (ModelData.ReportingCurrency.Value != PaymentCurrency.Value) { string curveName = MarketEnvironmentHelper.ResolveFxCurveNames(PaymentCurrency.Value, modelData.ReportingCurrency.Value); fxCurve = (IFxCurve)market.SearchForPricingStructureType(curveName); fxCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; analyticModelParameters.ReportingCurrencyFxCurve = fxCurve; } } AnalyticModelParameters = analyticModelParameters; } //Set the base rate. Default is zero if (AnalyticModelParameters != null) { AnalyticModelParameters.BaseRate = BaseRate; } if (UseObservedRate) { AnalyticsModel = new FixedRateCouponAnalytic(ModelData.ValuationDate, AccrualStartDate, AccrualEndDate, PaymentDate, Rate, analyticModelParameters.YearFraction, DiscountType, fxCurve, discountCurve, forecastCurve); if (Rate != null) { analyticModelParameters.Rate = (decimal)Rate; } } else { if (Rate != null) { discountRate = Rate; } if (DiscountRate != null) { discountRate = DiscountRate; } AnalyticsModel = new FloatingRateCouponAnalytic(ModelData.ValuationDate, AccrualStartDate, AccrualEndDate, PaymentDate, discountRate, analyticModelParameters.YearFraction, DiscountType, fxCurve, discountCurve, forecastCurve); } CalculationResults = AnalyticsModel.Calculate <IRateInstrumentResults, RateInstrumentResults>(AnalyticModelParameters, metrics.ToArray()); CalculationPerfomedIndicator = true; PaymentDiscountFactor = ((FixedRateCouponAnalytic)AnalyticsModel).PaymentDiscountFactor; if (!UseObservedRate) { Rate = CalculationResults.BreakEvenRate; } ForecastAmount = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyExpectedValue, PaymentAmount.currency); NPV = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyNPV, PaymentAmount.currency); } AssetValuation valuation = GetValue(CalculationResults, modelData.ValuationDate); valuation.id = Id; return(valuation); }
/// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> public override BasicAssetValuation Calculate(IAssetControllerData modelData) { ModelData = modelData; if (AnalyticsModel == null) { //AnalyticsModel = // DependencyCreator.Resolve<IModelAnalytic<ISimpleOptionAssetParameters, RateOptionMetrics>>( // ModelIdentifier); AnalyticsModel = new SimpleRateOptionAssetAnalytic(); } var metrics = MetricsHelper.GetMetricsToEvaluate(Metrics, AnalyticsModel.Metrics); // Determine if DFAM has been requested - if so that all we evaluate - every other metric is ignored // var bEvalVolatilityAtRiskMaturity = false; if (metrics.Contains(RateOptionMetrics.VolatilityAtExpiry)) { bEvalVolatilityAtRiskMaturity = true; // Remove all metrics except DFAM // metrics.RemoveAll(metricItem => metricItem != RateOptionMetrics.VolatilityAtExpiry); } ISimpleOptionAssetParameters analyticModelParameters = new SimpleRateOptionAssetParameters { YearFraction = YearFraction }; AnalyticResults = new SimpleRateOptionAssetResults(); var metricsToEvaluate = metrics.ToArray(); if (IsVolatilityQuote) { analyticModelParameters.IsVolatilityQuote = true; analyticModelParameters.Volatility = Volatility; } if (bEvalVolatilityAtRiskMaturity && IsVolatilityQuote) { analyticModelParameters.IsVolatilityQuote = true; AnalyticResults = AnalyticsModel.Calculate <ISimpleRateOptionAssetResults, SimpleRateOptionAssetResults>(analyticModelParameters, metricsToEvaluate); return(GetValue(AnalyticResults)); } var marketEnvironment = modelData.MarketEnvironment; IRateCurve curve = null; //1. instantiate curve if (marketEnvironment.GetType() == typeof(SimpleMarketEnvironment)) { curve = (IRateCurve)((ISimpleMarketEnvironment)marketEnvironment).GetPricingStructure(); CurveName = curve.GetPricingStructureId().UniqueIdentifier; } if (marketEnvironment.GetType() == typeof(SimpleRateMarketEnvironment)) { curve = ((ISimpleRateMarketEnvironment)marketEnvironment).GetRateCurve(); CurveName = curve.GetPricingStructureId().UniqueIdentifier; } if (marketEnvironment.GetType() == typeof(SwapLegEnvironment)) { curve = ((ISwapLegEnvironment)marketEnvironment).GetDiscountRateCurve(); CurveName = curve.GetPricingStructureId().UniqueIdentifier; } if (marketEnvironment.GetType() == typeof(MarketEnvironment)) { curve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(CurveName); } analyticModelParameters.IsPut = !IsCap; //A cap is a call option on the rate. This rate should reflect the underlying Xibor analyticModelParameters.Rate = GetRate(curve, modelData.ValuationDate, AdjustedEffectiveDate, MaturityDate, YearFraction); analyticModelParameters.Premium = Premium; //2. get start df = curve.getvalue(this._adjustedStartDate); // analyticModelParameters.StartDiscountFactor = GetDiscountFactor(curve, AdjustedEffectiveDate, modelData.ValuationDate); analyticModelParameters.PremiumPaymentDiscountFactor = GetDiscountFactor(curve, PaymentDate, modelData.ValuationDate); analyticModelParameters.NotionalAmount = Notional; analyticModelParameters.IsDiscounted = IsDiscounted; //3. Get the end discount factor // analyticModelParameters.EndDiscountFactor = GetDiscountFactor(curve, MaturityDate, modelData.ValuationDate); analyticModelParameters.Strike = Strike; analyticModelParameters.TimeToExpiry = TimeToExpiry; if (bEvalVolatilityAtRiskMaturity && !IsVolatilityQuote) { AnalyticResults = AnalyticsModel.Calculate <ISimpleRateOptionAssetResults, SimpleRateOptionAssetResults>( analyticModelParameters, metricsToEvaluate); return(GetValue(AnalyticResults)); } if (!IsVolatilityQuote) { IVolatilitySurface volCurve; if (marketEnvironment.GetType() == typeof(SwapLegEnvironment)) { var me = (ISwapLegEnvironment)marketEnvironment; volCurve = me.GetVolatilitySurface(); VolCurveName = volCurve.GetPricingStructureId().UniqueIdentifier; } else { volCurve = (IVolatilitySurface)modelData.MarketEnvironment.GetPricingStructure(VolCurveName); } analyticModelParameters.Volatility = Convert.ToDecimal(volCurve.GetValue((double)TimeToExpiry, (double)Strike)); } //4. Set the analytic input parameters and Calculate the respective metrics // AnalyticResults = AnalyticsModel.Calculate <ISimpleRateOptionAssetResults, SimpleRateOptionAssetResults>(analyticModelParameters, metricsToEvaluate); return(GetValue(AnalyticResults)); }
// <summary> // Initializes a new instance of the <see cref="PriceableRateCoupon"/> class. // </summary> // <param name="cashlfowId">The stream id.</param> // <param name="accrualStartDate">The accrual start date. If adjusted, the adjustCalculationDatesIndicator should be false.</param> // <param name="accrualEndDate">The accrual end date. If adjusted, the adjustCalculationDatesIndicator should be false.</param> // <param name="adjustCalculationDatesIndicator">if set to <c>true</c> [adjust calculation dates indicator].</param> // <param name="accrualBusinessCenters">The accrual business centers.</param> // <param name="margin">The margin.</param> // <param name="observedRate">The observed Rate.</param> // <param name="notionalAmount">The notional amount.</param> // <param name="dayCountfraction">Type of day Countfraction.</param> // <param name="paymentDate">The payment date.</param> // <param name="accrualRollConvention">The accrual roll convention.</param> // <param name="resetRelativeTo">reset relative to?</param> // <param name="fixingDateRelativeOffset">The fixing date offset.</param> // <param name="forecastRateIndex">The forecastrateindex.</param> // <param name="discountingType">The swap discounting type.</param> // <param name="discountRate">The discount rate.</param> // <param name="fraDiscounting">Determines whether the coupon is discounted or not. If this parameter is null, // then it is assumed that there is no fradiscounting</param> //public PriceableComplexRateCoupon // ( // string cashlfowId // , DateTime accrualStartDate // , DateTime accrualEndDate // , Boolean adjustCalculationDatesIndicator // , BusinessCenters accrualBusinessCenters // , BusinessDayConventionEnum accrualRollConvention // , DayCountFraction dayCountfraction // , ResetRelativeToEnum resetRelativeTo // , RelativeDateOffset fixingDateRelativeOffset // , Decimal margin // , Decimal? observedRate // , Money notionalAmount // , AdjustableDate paymentDate // , ForecastRateIndex forecastRateIndex // , DiscountingTypeEnum? discountingType // , Decimal? discountRate // , FraDiscountingEnum? fraDiscounting) // : base( // cashlfowId // , CouponType.FloatingRate // , accrualStartDate // , accrualEndDate // , adjustCalculationDatesIndicator // , accrualBusinessCenters // , accrualRollConvention // , dayCountfraction // , observedRate // , notionalAmount // , paymentDate // , discountingType // , discountRate // , fraDiscounting // ) //{ //} //public PriceableComplexRateCoupon // (string uniqueId // , DateTime accrualStartDate // , DateTime accrualEndDate // , Boolean adjustCalculationDatesIndicator // , AdjustableDate paymentDate // , Money notionalAmount // , ResetRelativeToEnum resetRelativeTo // , RelativeDateOffset fixingDateRelativeOffset // , Decimal margin // , Calculation calculation // , ForecastRateIndex forecastRateIndex // ) // : base // (uniqueId // , CouponType.FloatingRate // , accrualStartDate // , accrualEndDate // , adjustCalculationDatesIndicator // , BusinessDayAdjustmentsHelper.Create(fixingDateRelativeOffset.businessDayConvention, fixingDateRelativeOffset.businessCenters) // , calculation // , notionalAmount // , paymentDate // ) //{ //} #endregion #region Metrics for Valuation /// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> override public AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; RequiresReset = modelData.ValuationDate > ResetDate; IsRealised = HasBeenRealised(ModelData.ValuationDate); if (AnalyticsModel == null) { AnalyticsModel = new FloatingRateCouponAnalytic(); } var metrics = ResolveModelMetrics(AnalyticsModel.Metrics); // Determine if DFAM has been requested - if so thats all we evaluate - every other metric is ignored if (metrics.Contains(RateInstrumentMetrics.DiscountFactorAtMaturity)) { metrics.RemoveAll(metricItem => metricItem != RateInstrumentMetrics.DiscountFactorAtMaturity); } var metricsToEvaluate = metrics.ToArray(); if (metricsToEvaluate.Length > 0) { //May need to adapt for fra discounting. var isDiscounted = (GetDiscountingTypeEnum() == DiscountingTypeEnum.Standard ? true : false); var reportingCurrency = ModelData.ReportingCurrency == null ? PaymentCurrency.Value : ModelData.ReportingCurrency.Value; IRateCouponParameters analyticModelParameters = new RateCouponParameters { Currency = PaymentCurrency.Value, ReportingCurrency = reportingCurrency, IsDiscounted = isDiscounted, IsRealised = IsRealised, HasReset = RequiresReset, NotionalAmount = NotionalAmount.amount, Spread = Margin, Rate = GetRate(), DiscountRate = GetRate(), YearFraction = CouponYearFraction }; // Curve Related var streamMarket = (ISwapLegEnvironment)modelData.MarketEnvironment; var discountCurve = streamMarket.GetDiscountRateCurve(); discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; var fwdCurve = streamMarket.GetForecastRateCurve(); fwdCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; DiscountCurveName = discountCurve.GetPricingStructureId().UniqueIdentifier; ForecastCurveName = fwdCurve.GetPricingStructureId().UniqueIdentifier; //Setting the parameters analyticModelParameters.StartDiscountFactor = (decimal)fwdCurve.GetDiscountFactor(ModelData.ValuationDate, AccrualStartDate); analyticModelParameters.EndDiscountFactor = (decimal)fwdCurve.GetDiscountFactor(ModelData.ValuationDate, AccrualEndDate); analyticModelParameters.PaymentDiscountFactor = (decimal)discountCurve.GetDiscountFactor(ModelData.ValuationDate, PaymentDate); analyticModelParameters.CurveYearFraction = GetPaymentYearFraction(ModelData.ValuationDate, PaymentDate); // Bucketed Delta if (BucketedDates.Count > 1) { analyticModelParameters.PeriodAsTimesPerYear = GetPaymentYearFraction(BucketedDates[0], BucketedDates[1]); analyticModelParameters.BucketedDiscountFactors = GetBucketedDiscountFactors(discountCurve, ModelData.ValuationDate, BucketedDates); } IRateInstrumentResults analyticResults = AnalyticsModel.Calculate <IRateInstrumentResults, RateInstrumentResults>(analyticModelParameters, metricsToEvaluate); UpdateResults(metricsToEvaluate, analyticResults); // store inputs and results from this run AnalyticModelParameters = analyticModelParameters; CalculationPerfomedIndicator = true; } AssetValuation valuation = GetValue(CalculationResults); valuation.id = Id; return(valuation); }
public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; // 1. First derive the analytics to be evaluated via the stream controller model // NOTE: These take precedence of the child model metrics if (AnalyticsModel == null) { AnalyticsModel = new BondTransactionAnalytic(); } var bondControllerMetrics = ResolveModelMetrics(AnalyticsModel.Metrics); AssetValuation bondValuation; var quotes = ModelData.AssetValuation.quote.ToList(); if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.AccrualFactor.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.AccrualFactor.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.FloatingNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.FloatingNPV.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.NPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.NPV.ToString(), "DecimalValue"); quotes.Add(quote); } ModelData.AssetValuation.quote = quotes.ToArray(); var marketEnvironment = modelData.MarketEnvironment; IRateCurve rateDiscountCurve = null; //2. Sets the evolution type for coupon and payment calculations. Coupons.PricingStructureEvolutionType = PricingStructureEvolutionType; Coupons.BucketedDates = BucketedDates; Coupons.Multiplier = Multiplier; if (AdditionalPayments != null) { foreach (var payment in AdditionalPayments) { payment.PricingStructureEvolutionType = PricingStructureEvolutionType; payment.BucketedDates = BucketedDates; payment.Multiplier = Multiplier; } } //3. Aggregate the child metrics. List <AssetValuation> childValuations = new List <AssetValuation> { Coupons?.Calculate(modelData) }; if (GetAdditionalPayments() != null) { var paymentControllers = new List <InstrumentControllerBase>(GetAdditionalPayments()); childValuations.AddRange(paymentControllers.Select(payment => payment.Calculate(modelData))); } var childControllerValuations = AssetValuationHelper.AggregateMetrics(childValuations, new List <string>(Metrics), PaymentCurrencies); childControllerValuations.id = Id + ".BondCouponRateStreams"; //4. Calc the asset as a little extra var metrics = ResolveModelMetrics(AnalyticsModel.Metrics); var metricsAsString = metrics.Select(metric => metric.ToString()).ToList(); var controllerData = PriceableAssetFactory.CreateAssetControllerData(metricsAsString.ToArray(), modelData.ValuationDate, modelData.MarketEnvironment); UnderlyingBond.Multiplier = Multiplier; UnderlyingBond.Calculate(controllerData); //5. Now do the bond calculations. if (bondControllerMetrics.Count > 0) { CalculationResults = new BondTransactionResults(); if (marketEnvironment.GetType() == typeof(MarketEnvironment)) { var bondCurve = (IBondCurve)modelData.MarketEnvironment.GetPricingStructure(BondCurveName); if (bondCurve != null) { var marketDataType = bondCurve.GetPricingStructureId().Properties.GetValue <string>(AssetMeasureEnum.MarketQuote.ToString(), false); if (marketDataType != null && marketDataType == BondPriceEnum.YieldToMaturity.ToString()) { IsYTMQuote = true; } //TODO handle the other cases like: AssetSwapSpread; DirtyPrice and ZSpread. var mq = (decimal)bondCurve.GetYieldToMaturity(modelData.ValuationDate, SettlementDate); Quote = BasicQuotationHelper.Create(mq, AssetMeasureEnum.MarketQuote.ToString(), PriceQuoteUnitsEnum.DecimalRate.ToString()); } rateDiscountCurve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(DiscountCurveName); } //Generate the vectors const bool isBuyerInd = true; var analyticModelParameters = new BondTransactionParameters { IsBuyerInd = isBuyerInd, AccrualYearFractions = GetCouponAccrualFactors(), Multiplier = Multiplier, Quote = QuoteValue, CouponRate = UnderlyingBond.GetCouponRate(), NotionalAmount = UnderlyingBond.Notional, Frequency = UnderlyingBond.Frequency, IsYTMQuote = IsYTMQuote, AccruedFactor = UnderlyingBond.GetAccruedFactor(), RemainingAccruedFactor = UnderlyingBond.GetRemainingAccruedFactor(), PaymentDiscountFactors = GetDiscountFactors(rateDiscountCurve, Coupons.StreamPaymentDates.ToArray(), modelData.ValuationDate), }; //5. Get the Weightings analyticModelParameters.Weightings = CreateWeightings(CDefaultWeightingValue, analyticModelParameters.PaymentDiscountFactors.Length); //6. Set the analytic input parameters and Calculate the respective metrics AnalyticModelParameters = analyticModelParameters; CalculationResults = AnalyticsModel.Calculate <IBondTransactionResults, BondTransactionResults>(analyticModelParameters, metrics.ToArray()); // Now merge back into the overall stream valuation var bondControllerValuation = GetValue(CalculationResults, modelData.ValuationDate); bondValuation = AssetValuationHelper.UpdateValuation(bondControllerValuation, childControllerValuations, ConvertMetrics(bondControllerMetrics), new List <string>(Metrics)); } else { bondValuation = childControllerValuations; } // store inputs and results from this run CalculationPerformedIndicator = true; bondValuation.id = Id; return(bondValuation); }
/// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; CalculationResults = null; UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); // 1. First derive the analytics to be evaluated via the stream controller model // NOTE: These take precendence of the child model metrics if (AnalyticsModel == null) { AnalyticsModel = new SimpleIRSwaptionInstrumentAnalytic(); } var swaptionControllerMetrics = ResolveModelMetrics(AnalyticsModel.Metrics); var quotes = ModelData.AssetValuation.quote.ToList(); if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.BreakEvenRate.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.BreakEvenRate.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.NPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.NPV.ToString(), "DecimalValue"); quotes.Add(quote); } ModelData.AssetValuation.quote = quotes.ToArray(); AssetValuation swaptionValuation; //Sets the evolution type for calculations. Swap.PricingStructureEvolutionType = PricingStructureEvolutionType; Swap.BucketedDates = BucketedDates; if (PremiumPayments != null) { foreach (var payment in PremiumPayments) { payment.PricingStructureEvolutionType = PricingStructureEvolutionType; payment.BucketedDates = BucketedDates; } } //The assetValuation list. var childValuations = new List <AssetValuation>(); // 2. Now evaluate only the child specific metrics (if any) if (PremiumPayments != null) { var paymentControllers = new List <InstrumentControllerBase>(PremiumPayments); childValuations.AddRange(paymentControllers.Select(payment => payment.Calculate(modelData))); } var swapMetrics = Swap.Calculate(modelData); //We assume the fixed leg is always the first leg! var fixedLeg = Swap.GetLegs()[0].Calculate(modelData); var breakEvenRate = AssetValuationHelper.GetQuotationByMeasureType(swapMetrics, InstrumentMetrics.BreakEvenRate.ToString()).value; var timeToIndex = (Swap.EffectiveDate - ModelData.ValuationDate).Days / 365.0; //This is European only. var expiryTime = (ExerciseDates[0] - ModelData.ValuationDate).Days / 365.0; IVolatilitySurface indexVolSurface = null; if (modelData.MarketEnvironment is ISwapLegEnvironment streamMarket1) { indexVolSurface = streamMarket1.GetVolatilitySurface(); indexVolSurface.PricingStructureEvolutionType = PricingStructureEvolutionType; VolatilitySurfaceName = indexVolSurface.GetPricingStructureId().UniqueIdentifier; } else { if (!string.IsNullOrEmpty(VolatilitySurfaceName)) { indexVolSurface = (IVolatilitySurface)modelData.MarketEnvironment.GetPricingStructure(VolatilitySurfaceName); } } //Calculate the delta var delta = SimpleIRSwaptionInstrumentAnalytic.CalculateOptionDelta(IsCall, breakEvenRate, StrikeRate, expiryTime, timeToIndex, indexVolSurface); //Set the multiplier using the delta of the option. //Multiplier = delta;? Swap.Multiplier = System.Math.Abs(delta); //New function that converts the metrics by multiplying be the delta. var swapCalculations = Swap.Calculate(modelData); //childValuations.Add(swapCalculations); var childControllerValuations = AssetValuationHelper.AggregateMetrics(childValuations, new List <string>(Metrics), PaymentCurrencies); // modelData.ValuationDate); var streamAccrualFactor = AssetValuationHelper.GetQuotationByMeasureType(fixedLeg, InstrumentMetrics.AccrualFactor.ToString()); //TODO This is not correct! var npv = AssetValuationHelper.GetQuotationByMeasureType(childControllerValuations, InstrumentMetrics.NPV.ToString()); childValuations.Add(swapCalculations); // Child metrics have now been calculated so we can now evaluate the stream model metrics if (swaptionControllerMetrics.Count > 0) { //Get the market data. IFxCurve fxCurve = null; ISwaptionInstrumentParameters analyticModelParameters = new SwaptionInstrumentParameters { IsBought = IsBasePartyBuyer, IsCall = IsCall, SwapAccrualFactor = System.Math.Abs(streamAccrualFactor.value), Strike = StrikeRate, OtherNPV = npv.value, TimeToExpiry = (decimal)expiryTime, SwapBreakEvenRate = breakEvenRate, //OtherNPV = }; // Curve Related if (modelData.MarketEnvironment is ISwapLegEnvironment streamMarket) { analyticModelParameters.VolatilitySurface = indexVolSurface; //Check for currency. if (ModelData.ReportingCurrency != null) { if (ModelData.ReportingCurrency.Value != PaymentCurrencies[0])//This is an interest rate swap and so only has one currency. { fxCurve = streamMarket.GetReportingCurrencyFxCurve(); fxCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; } } } var analyticsModel = new SimpleIRSwaptionInstrumentAnalytic(ModelData.ValuationDate, (decimal)timeToIndex, StrikeRate, fxCurve, indexVolSurface); AnalyticsModel = analyticsModel; Volatility = analyticsModel.Volatility; AnalyticModelParameters = analyticModelParameters; CalculationResults = AnalyticsModel.Calculate <ISwaptionInstrumentResults, SwaptionInstrumentResults>(analyticModelParameters, swaptionControllerMetrics.ToArray()); // Now merge back into the overall stream valuation var swapControllerValuation = GetValue(CalculationResults, modelData.ValuationDate); //childValuations.Add(swapControllerValuation); childControllerValuations = AssetValuationHelper.AggregateMetrics(childValuations, new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); swaptionValuation = AssetValuationHelper.UpdateValuation(swapControllerValuation, childControllerValuations, ConvertMetrics(swaptionControllerMetrics), new List <string>(Metrics)); //swaptionValuation = AssetValuationHelper.AggregateMetrics(childValuations, new List<string>(Metrics), modelData.ValuationDate); } else { swaptionValuation = childControllerValuations; } CalculationPerfomedIndicator = true; swaptionValuation.id = Id; return(swaptionValuation); }
/// <summary> /// Calculates the specified metric for the fast bootstrapper. /// </summary> /// <param name="discountCurve">The discount curve.</param> /// <param name="forecastCurve">The forecast curve</param> /// <param name="curveToPerturb">The curve to perturb: the discount curve, the forecast curve or both.</param> /// <returns></returns> public IDictionary <string, Decimal> CalculatePDH(CurveBase discountCurve, CurveBase forecastCurve, CurvePerturbation curveToPerturb) { if (AnalyticsModel == null) { switch (ModelIdentifier) { case "SwapAsset": AnalyticsModel = new SwapAssetAnalytic(); break; case "DiscountSwapAsset": AnalyticsModel = new DiscountSwapAssetAnalytic(); break; } } var result = new Dictionary <string, Decimal>(); if (discountCurve != null && forecastCurve != null) { ISwapAssetParameters analyticModelParameters = new IRSwapAssetParameters { NotionalAmount = Notional, //2. Get the discount factors DiscountFactors = GetDiscountFactors(discountCurve, AdjustedPeriodDates.ToArray(), BaseDate), //3. Get the respective year fractions YearFractions = YearFractions, Weightings = Weightings, Rate = MarketQuoteHelper.NormalisePriceUnits( FixedRate, "DecimalRate").value, FloatingLegDiscountFactors = GetDiscountFactors(discountCurve, FloatingLegAdjustedPeriodDates.ToArray(), BaseDate), FloatingLegForecastDiscountFactors = GetDiscountFactors(forecastCurve, FloatingLegAdjustedPeriodDates.ToArray(), BaseDate), FloatingLegYearFractions = FloatingLegYearFractions, FloatingLegWeightings = FloatingLegWeightings, FloatingLegSpread = MarketQuoteHelper.NormalisePriceUnits( FloatingLegSpread, "DecimalRate").value }; if (ForwardRates != null) { analyticModelParameters.FloatingLegForwardRates = ForwardRates; } //4. Set the analytic input parameters and Calculate the respective metrics // if (AnalyticsModel != null) { var analyticResults = AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters, new[] { RateMetrics.NPV }); AnalyticResults = analyticResults; analyticModelParameters.BaseNPV = analyticResults.NPV; //Now loop through the risk curves. if (curveToPerturb == CurvePerturbation.DiscountCurve) { var riskCurves = discountCurve.CreateCurveRiskSet(1); foreach (var curve in riskCurves) { var perturbedAsset = curve.GetPricingStructureId().Properties.GetValue <string>("PerturbedAsset"); analyticResults = RiskCalculationHelper((IRateCurve)curve, analyticModelParameters); result.Add("DiscountCurve:" + perturbedAsset, analyticResults.NPVChange); } } if (curveToPerturb == CurvePerturbation.ForecastCurve) { var riskCurves = forecastCurve.CreateCurveRiskSet(1); foreach (var curve in riskCurves) { var perturbedAsset = curve.GetPricingStructureId().Properties.GetValue <string>("PerturbedAsset"); analyticResults = ForecastRiskCalculationHelper((IRateCurve)curve, analyticModelParameters); result.Add("ForecastCurve:" + perturbedAsset, analyticResults.NPVChange); } } if (curveToPerturb == CurvePerturbation.Both) { var riskCurves1 = discountCurve.CreateCurveRiskSet(1); foreach (var curve in riskCurves1) { var perturbedAsset = curve.GetPricingStructureId().Properties.GetValue <string>("PerturbedAsset"); analyticResults = RiskCalculationHelper((IRateCurve)curve, analyticModelParameters); result.Add("DiscountCurve:" + perturbedAsset, analyticResults.NPVChange); } var riskCurves2 = forecastCurve.CreateCurveRiskSet(1); foreach (var curve in riskCurves2) { var perturbedAsset = curve.GetPricingStructureId().Properties.GetValue <string>("PerturbedAsset"); analyticResults = ForecastRiskCalculationHelper((IRateCurve)curve, analyticModelParameters); result.Add("ForecastCurve:" + perturbedAsset, analyticResults.NPVChange); } } } } return(result); }
public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; CalculationResults = null; UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); // 1. First derive the analytics to be evaluated via the stream controller model // NOTE: These take precendence of the child model metrics if (AnalyticsModel == null) { AnalyticsModel = new FxLegAnalytic(); } AssetValuation streamValuation; //Check if risk calc are required. bool delta0PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta0PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta0PDH.ToString()) != null; bool delta1PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta1PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta1PDH.ToString()) != null; var streamControllerMetrics = ResolveModelMetrics(AnalyticsModel.Metrics); var childValuations = new List <AssetValuation>(); foreach (var payment in Payments) { payment.PricingStructureEvolutionType = PricingStructureEvolutionType; payment.BucketedDates = BucketedDates; payment.Multiplier = Multiplier; } if (modelData.MarketEnvironment is IFxLegEnvironment marketEnvironment)//TODO need to look at PricingStructureEvolutionType. { //Modify the second market. var curveName1 = marketEnvironment.GetExchangeCurrencyPaymentEnvironment1(); var modelData1 = new InstrumentControllerData(modelData.AssetValuation, curveName1, modelData.ValuationDate, modelData.ReportingCurrency); var curveName2 = marketEnvironment.GetExchangeCurrencyPaymentEnvironment2(); var modelData2 = new InstrumentControllerData(modelData.AssetValuation, curveName2, modelData.ValuationDate, modelData.ReportingCurrency); childValuations.Add(Currency1Payment.Calculate(modelData1)); childValuations.Add(Currency2Payment.Calculate(modelData2)); } else if (modelData.MarketEnvironment.GetType() == typeof(MarketEnvironment)) { var market = (MarketEnvironment)modelData.MarketEnvironment; if (delta0PDH) { //Force building of the risk curves. //market.SearchForPerturbedPricingStructures(FxIndexCurveName, "delta0PDH");//TODO Need to add this perturbation to fxCurve. } if (delta1PDH) { //Force building of the risk curves. market.SearchForPerturbedPricingStructures(Currency1DiscountCurveName, "delta1PDH"); market.SearchForPerturbedPricingStructures(Currency2DiscountCurveName, "delta1PDH"); } //This defines the cross cureves from the payment currency to the reporting //currency for each leg of the fx trade. // if (modelData.ReportingCurrency.Value != Currency1.Value) { ReportingCurrencyFxCurveName1 = MarketEnvironmentHelper.ResolveFxCurveNames(Currency1.Value, modelData.ReportingCurrency.Value); } if (modelData.ReportingCurrency.Value != Currency2.Value) { ReportingCurrencyFxCurveName2 = MarketEnvironmentHelper.ResolveFxCurveNames(Currency2.Value, modelData.ReportingCurrency.Value); } childValuations.Add(Currency1Payment.Calculate(modelData)); childValuations.Add(Currency2Payment.Calculate(modelData)); } var paymentValuation = AssetValuationHelper.AggregateMetrics(childValuations, new List <string>(Metrics), PaymentCurrencies); var childControllerValuations = new List <AssetValuation> { paymentValuation }; // Child metrics have now been calculated so we can now evaluate the stream model metrics if (streamControllerMetrics.Count > 0) { var rate = ExchangeRate.rate; if (modelData.MarketEnvironment is MarketEnvironment market) { var fxCurve = (IFxCurve)market.SearchForPricingStructureType(FxIndexCurveName); if (HybridValuation) { var curve1 = (IRateCurve)market.SearchForPricingStructureType(Currency1DiscountCurveName); var curve2 = (IRateCurve)market.SearchForPricingStructureType(Currency2DiscountCurveName); var flag = ExchangeRate.quotedCurrencyPair.quoteBasis == QuoteBasisEnum.Currency2PerCurrency1; AnalyticsModel = new FxLegAnalytic(modelData.ValuationDate, RiskMaturityDate, fxCurve, curve1, curve2, flag); } else { AnalyticsModel = new FxLegAnalytic(modelData.ValuationDate, RiskMaturityDate, fxCurve); } } IFxLegParameters analyticModelParameters = new FxLegParameters { Multiplier = Multiplier, MarketQuote = rate, }; CalculationResults = AnalyticsModel.Calculate <IFxLegInstrumentResults, FxLegInstrumentResults>( analyticModelParameters, streamControllerMetrics.ToArray()); // Now merge back into the overall stream valuation var streamControllerValuation = GetValue(CalculationResults, modelData.ValuationDate); streamValuation = AssetValuationHelper.UpdateValuation(streamControllerValuation, childControllerValuations, ConvertMetrics(streamControllerMetrics), new List <string>(Metrics), PaymentCurrencies); } else { streamValuation = paymentValuation; } CalculationPerfomedIndicator = true; streamValuation.id = Id; return(streamValuation); }
public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; CalculationResults = null; UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); // 1. First derive the analytics to be evaluated via the stream controller model // NOTE: These take precendence of the child model metrics if (AnalyticsModel == null) { AnalyticsModel = new CapFloorStreamAnalytic(); } var streamControllerMetrics = ResolveModelMetrics(AnalyticsModel.Metrics); AssetValuation streamValuation; // 2. Now evaluate only the child specific metrics (if any) foreach (var coupon in Coupons) { coupon.PricingStructureEvolutionType = PricingStructureEvolutionType; coupon.BucketedDates = BucketedDates; coupon.Multiplier = 1.0m;//TODO this will have to be fixed eventually. } var childControllers = new List <InstrumentControllerBase>(Coupons.ToArray()); //Add the extra metrics required var quotes = ModelData.AssetValuation.quote.ToList(); if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.AccrualFactor.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.AccrualFactor.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.FloatingNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.FloatingNPV.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.NPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.NPV.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.LocalCurrencyNPV.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyExpectedValue.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.LocalCurrencyExpectedValue.ToString(), "DecimalValue"); quotes.Add(quote); } ModelData.AssetValuation.quote = quotes.ToArray(); var childValuations = EvaluateChildMetrics(childControllers, modelData, Metrics); var couponValuation = AssetValuationHelper.AggregateMetrics(childValuations, new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); var childControllerValuations = new List <AssetValuation> { couponValuation }; if (Exchanges != null && Exchanges.Count > 0) { foreach (var exchange in Exchanges) { exchange.PricingStructureEvolutionType = PricingStructureEvolutionType; exchange.BucketedDates = BucketedDates; exchange.Multiplier = 1.0m;//TODO this will have to be fixed eventually. } // Roll-Up and merge child valuations into parent Valuation var childPrincipalControllers = new List <InstrumentControllerBase>(Exchanges.ToArray()); var childPrincipalValuations = EvaluateChildMetrics(childPrincipalControllers, modelData, Metrics); var principalValuation = AssetValuationHelper.AggregateMetrics(childPrincipalValuations, new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); childControllerValuations.Add(principalValuation); } // Child metrics have now been calculated so we can now evaluate the stream model metrics if (streamControllerMetrics.Count > 0) { var reportingCurrency = ModelData.ReportingCurrency == null ? Currency.Value : ModelData.ReportingCurrency.Value; ICapFloorStreamParameters analyticModelParameters = new CapFloorStreamParameters { Multiplier = 1.0m, Currency = Currency.Value, ReportingCurrency = reportingCurrency, AccrualFactor = AggregateMetric(InstrumentMetrics.AccrualFactor, childControllerValuations), FloatingNPV = AggregateMetric(InstrumentMetrics.FloatingNPV, childControllerValuations), NPV = AggregateMetric(InstrumentMetrics.NPV, childControllerValuations) //, }; CalculationResults = AnalyticsModel.Calculate <ICapFloorStreamInstrumentResults, CapFloorStreamInstrumentResults>(analyticModelParameters, streamControllerMetrics.ToArray()); // Now merge back into the overall stream valuation var streamControllerValuation = GetValue(CalculationResults, modelData.ValuationDate); streamValuation = AssetValuationHelper.UpdateValuation(streamControllerValuation, childControllerValuations, ConvertMetrics(streamControllerMetrics), new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); } else { streamValuation = AssetValuationHelper.AggregateMetrics(childControllerValuations, new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); } CalculationPerfomedIndicator = true; streamValuation.id = Id; return(streamValuation); }
/// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param>//TODO the floating delta? /// <returns></returns> public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; AnalyticsModel = new FxRateCashflowAnalytic(); CalculationResults = null; YearFractionToCashFlowPayment = Convert.ToDecimal(CDefaultDayCounter.YearFraction(ModelData.ValuationDate, PaymentDate)); //Make sure there are some bucket dates even if not set previously. if (BucketedDates.Length < 1) { UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); } IsRealised = HasBeenRealised(ModelData.ValuationDate); //Add the extra metrics required var quotes = ModelData.AssetValuation.quote.ToList(); if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.NPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyNPV.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.LocalCurrencyNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyNPV.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.RiskNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.NPV.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.LocalCurrencyExpectedValue.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyExpectedValue.ToString(), "DecimalValue", ModelData.ValuationDate); quotes.Add(quote); } //Check if risk calc are required. bool delta1PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta1PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta1PDH.ToString()) != null; //Check if risk calc are required. bool delta0PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta0PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta0PDH.ToString()) != null; ModelData.AssetValuation.quote = quotes.ToArray(); var metrics = ResolveModelMetrics(AnalyticsModel.Metrics); IFxCurve fxCurve = null; IRateCurve discountCurve = null; IFxCurve currencyCurve = null; var reportingCurrency = ModelData.ReportingCurrency == null ? PaymentCurrency.Value : ModelData.ReportingCurrency.Value; //Set the basic model. var analyticModelParameters = new FxRateCashflowParameters { Multiplier = Multiplier, ValuationDate = ModelData.ValuationDate, PaymentDate = PaymentDate, Currency = PaymentCurrency.Value, ReportingCurrency = reportingCurrency, NotionalAmount = PaymentAmount.amount, StartIndex = StartIndex, IsRealised = IsRealised, CurveYearFraction = YearFractionToCashFlowPayment, PeriodAsTimesPerYear = 0.25m, BucketingRate = 0.05m }; if (modelData.MarketEnvironment is ISwapLegEnvironment environment) { var marketEnvironment = environment; //The discount curve. discountCurve = marketEnvironment.GetDiscountRateCurve(); discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; analyticModelParameters.DiscountCurve = discountCurve; //Check if it is our of currency. if (ModelData.ReportingCurrency != null && ModelData.ReportingCurrency.Value != PaymentCurrency.Value) { fxCurve = marketEnvironment.GetReportingCurrencyFxCurve(); fxCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; analyticModelParameters.ReportingCurrencyFxCurve = fxCurve; } } else if (modelData.MarketEnvironment.GetType() == typeof(MarketEnvironment)) { var market = (MarketEnvironment)modelData.MarketEnvironment; discountCurve = (IRateCurve)market.SearchForPricingStructureType(DiscountCurveName); discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; analyticModelParameters.DiscountCurve = discountCurve; var currencyCurveName = MarketEnvironmentHelper.ResolveFxCurveNames(StartFxRate.quotedCurrencyPair.currency1.Value, StartFxRate.quotedCurrencyPair.currency2.Value); currencyCurve = (IFxCurve)market.SearchForPricingStructureType(currencyCurveName); currencyCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; if (delta1PDH) { var riskMarket = market.SearchForPerturbedPricingStructures(DiscountCurveName, "delta1PDH"); analyticModelParameters.Delta1PDHCurves = riskMarket; analyticModelParameters.Delta1PDHPerturbation = 10; } if (delta0PDH) { var riskMarket = market.SearchForPerturbedPricingStructures(DiscountCurveName, "delta0PDH");//TODO The fx deltas analyticModelParameters.Delta1PDHCurves = riskMarket; analyticModelParameters.Delta1PDHPerturbation = 10; } if (modelData.ReportingCurrency.Value != PaymentCurrency.Value) { string curveName = MarketEnvironmentHelper.ResolveFxCurveNames(PaymentCurrency.Value, modelData.ReportingCurrency.Value); fxCurve = (IFxCurve)market.SearchForPricingStructureType(curveName); fxCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; analyticModelParameters.ReportingCurrencyFxCurve = fxCurve; } if (HybridValuation) { var currency1RateCurve = (IRateCurve)market.SearchForPricingStructureType(Currency1DiscountCurveName); currency1RateCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; var currency2RateCurve = (IRateCurve)market.SearchForPricingStructureType(Currency2DiscountCurveName); currency2RateCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; AnalyticsModel = new FxRateCashflowAnalytic(ModelData.ValuationDate, PaymentDate, currencyCurve, currency1RateCurve, currency2RateCurve, !InvertFxRate, IsSettlementInCurrency1, fxCurve); } } // store inputs and results from this run AnalyticModelParameters = analyticModelParameters; if (!HybridValuation) { AnalyticsModel = new FxRateCashflowAnalytic(ModelData.ValuationDate, PaymentDate, fxCurve, currencyCurve, discountCurve); } //TODO Fix this with a generic index curve. //AnalyticsModel = analyticsModel; CalculationResults = AnalyticsModel.Calculate <IFloatingCashflowResults, FloatingCashflowResults>(AnalyticModelParameters, metrics.ToArray()); CalculationPerformedIndicator = true; PaymentDiscountFactor = ((FxRateCashflowAnalytic)AnalyticsModel).PaymentDiscountFactor; ForecastAmount = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyExpectedValue, PaymentAmount.currency); NPV = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyNPV, PaymentAmount.currency); AssetValuation valuation = GetValue(CalculationResults, modelData.ValuationDate); valuation.id = Id; return(valuation); }
/// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; CalculationResults = null; UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); // 1. First derive the analytics to be evaluated via the stream controller model // NOTE: These take precendence of the child model metrics if (AnalyticsModel == null) { AnalyticsModel = new SimpleXccySwapInstrumentAnalytic(); } var swapControllerMetrics = ResolveModelMetrics(AnalyticsModel.Metrics); AssetValuation swapValuation; var quotes = ModelData.AssetValuation.quote.ToList(); if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.AccrualFactor.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.AccrualFactor.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.FloatingNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.FloatingNPV.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.NPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.NPV.ToString(), "DecimalValue"); quotes.Add(quote); } ModelData.AssetValuation.quote = quotes.ToArray(); //Sets the evolution type for calculations. foreach (var leg in Legs) { leg.PricingStructureEvolutionType = PricingStructureEvolutionType; leg.BucketedDates = BucketedDates; leg.Multiplier = Multiplier; } if (AdditionalPayments != null) { foreach (var payment in AdditionalPayments) { payment.PricingStructureEvolutionType = PricingStructureEvolutionType; payment.BucketedDates = BucketedDates; payment.Multiplier = Multiplier; } } var legControllers = new List <InstrumentControllerBase> { PayLeg, ReceiveLeg }; //The assetValuation list. var childValuations = new List <AssetValuation>(); // 2. Now evaluate only the child specific metrics (if any) if (modelData.MarketEnvironment is ISwapLegEnvironment) { var market = (SwapLegEnvironment)modelData.MarketEnvironment; IRateCurve discountCurve = null; IRateCurve forecastCurve = null; IFxCurve currencyCurve = null; foreach (var leg in legControllers) { var stream = (PriceableInterestRateStream)leg; if (modelData.ReportingCurrency == null) { modelData.ReportingCurrency = stream.Currency; } if (stream.DiscountCurveName != null) { discountCurve = market.GetDiscountRateCurve(); } if (stream.ForecastCurveName != null) { forecastCurve = market.GetForecastRateCurve(); } if (modelData.ReportingCurrency.Value != stream.Currency.Value) { //stream.ReportingCurrencyFxCurveName = // MarketEnvironmentHelper.ResolveFxCurveNames(stream.Currency.Value, modelData.ReportingCurrency.Value); currencyCurve = market.GetReportingCurrencyFxCurve(); } modelData.MarketEnvironment = MarketEnvironmentHelper.CreateInterestRateStreamEnvironment(modelData.ValuationDate, discountCurve, forecastCurve, currencyCurve); childValuations.Add(leg.Calculate(modelData)); } if (GetAdditionalPayments() != null) { var paymentControllers = new List <InstrumentControllerBase>(GetAdditionalPayments()); childValuations.AddRange(paymentControllers.Select(payment => payment.Calculate(modelData))); } } else { childValuations = EvaluateChildMetrics(legControllers, modelData, Metrics); } var childControllerValuations = AssetValuationHelper.AggregateMetrics(childValuations, new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); childControllerValuations.id = Id + ".InterestRateStreams"; // Child metrics have now been calculated so we can now evaluate the stream model metrics if (swapControllerMetrics.Count > 0) { //TODO need to fix this calculation. var payStreamAccrualFactor = AssetValuationHelper.GetQuotationByMeasureType(childValuations[0], InstrumentMetrics.AccrualFactor.ToString()); //AggregateMetric(InstrumentMetrics.AccrualFactor, childValuations); var payStreamNPV = AssetValuationHelper.GetQuotationByMeasureType(childValuations[0], InstrumentMetrics.NPV.ToString()); //AggregateMetric(InstrumentMetrics.NPV, childValuations); var payStreamFloatingNPV = AssetValuationHelper.GetQuotationByMeasureType(childValuations[0], InstrumentMetrics.FloatingNPV.ToString()); //AggregateMetric(InstrumentMetrics.FloatingNPV, childValuations); var receiveStreamAccrualFactor = AssetValuationHelper.GetQuotationByMeasureType(childValuations[1], InstrumentMetrics.AccrualFactor.ToString()); //AggregateMetric(InstrumentMetrics.AccrualFactor, childValuations); var receiveStreamNPV = AssetValuationHelper.GetQuotationByMeasureType(childValuations[1], InstrumentMetrics.NPV.ToString()); //AggregateMetric(InstrumentMetrics.NPV, childValuations); var receiveStreamFloatingNPV = AssetValuationHelper.GetQuotationByMeasureType(childValuations[1], InstrumentMetrics.FloatingNPV.ToString()); IIRSwapInstrumentParameters analyticModelParameters = new SwapInstrumentParameters { IsPayFixedInd = true, PayStreamAccrualFactor = payStreamAccrualFactor.value, PayStreamFloatingNPV = payStreamFloatingNPV.value, PayStreamNPV = payStreamNPV.value, ReceiveStreamFloatingNPV = receiveStreamFloatingNPV.value, ReceiveStreamNPV = receiveStreamNPV.value, ReceiveStreamAccrualFactor = receiveStreamAccrualFactor.value, NPV = payStreamNPV.value + receiveStreamNPV.value }; CalculationResults = AnalyticsModel.Calculate <IIRSwapInstrumentResults, SwapInstrumentResults>(analyticModelParameters, swapControllerMetrics.ToArray()); // Now merge back into the overall stream valuation var swapControllerValuation = GetValue(CalculationResults, modelData.ValuationDate); swapValuation = AssetValuationHelper.UpdateValuation(swapControllerValuation, childControllerValuations, ConvertMetrics(swapControllerMetrics), new List <string>(Metrics)); } else { swapValuation = childControllerValuations; } CalculationPerfomedIndicator = true; swapValuation.id = Id; return(swapValuation); }
public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; CalculationResults = null; UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); // 1. First derive the analytics to be evaluated via the stream controller model // NOTE: These take precedence of the child model metrics if (AnalyticsModel == null) { AnalyticsModel = new BondStreamAnalytic(); } var streamControllerMetrics = ResolveModelMetrics(AnalyticsModel.Metrics); AssetValuation streamValuation; // 2. Now evaluate only the child specific metrics (if any) foreach (var coupon in Coupons) { coupon.PricingStructureEvolutionType = PricingStructureEvolutionType; coupon.BucketedDates = BucketedDates; coupon.Multiplier = Multiplier; } var childControllers = new List <InstrumentControllerBase>(Coupons.ToArray()); //Now the stream analytics can be completed. var childValuations = EvaluateChildMetrics(childControllers, modelData, Metrics); var couponValuation = AssetValuationHelper.AggregateMetrics(childValuations, new List <string>(Metrics), PaymentCurrencies); var childControllerValuations = new List <AssetValuation> { couponValuation }; // Child metrics have now been calculated so we can now evaluate the stream model metrics if (streamControllerMetrics.Count > 0) { var reportingCurrency = ModelData.ReportingCurrency == null ? Currency : ModelData.ReportingCurrency.Value; var notionals = GetCouponNotionals(); var accrualFactors = GetCouponAccrualFactors(); var discountFactors = GetPaymentDiscountFactors(); var floatingNPV = AggregateMetric(InstrumentMetrics.FloatingNPV, childControllerValuations); var accrualFactor = AggregateMetric(InstrumentMetrics.AccrualFactor, childControllerValuations); //TODO need to set the notional amount and the weighting. Also amortisation?? IBondStreamParameters analyticModelParameters = new BondStreamParameters { Multiplier = Multiplier, CouponNotionals = notionals, Currency = Currency, ReportingCurrency = reportingCurrency, AccrualFactor = accrualFactor, FloatingNPV = floatingNPV, NPV = AggregateMetric(InstrumentMetrics.NPV, childControllerValuations), CouponYearFractions = accrualFactors, PaymentDiscountFactors = discountFactors, TargetNPV = floatingNPV }; CalculationResults = AnalyticsModel.Calculate <IBondStreamInstrumentResults, BondStreamInstrumentResults>(analyticModelParameters, streamControllerMetrics.ToArray()); // Now merge back into the overall stream valuation var streamControllerValuation = GetValue(CalculationResults, modelData.ValuationDate); streamValuation = AssetValuationHelper.UpdateValuation(streamControllerValuation, childControllerValuations, ConvertMetrics(streamControllerMetrics), new List <string>(Metrics), PaymentCurrencies); AnalyticModelParameters = analyticModelParameters; } else { streamValuation = AssetValuationHelper.AggregateMetrics(childControllerValuations, new List <string>(Metrics), PaymentCurrencies); } CalculationPerformedIndicator = true; streamValuation.id = Id; return(streamValuation); }
/// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; CalculationResults = null; UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval)); // 1. First derive the analytics to be evaluated via the stream controller model // NOTE: These take precedence of the child model metrics if (AnalyticsModel == null) { AnalyticsModel = new TermDepositInstrumentAnalytic(); } var termDepositControllerMetrics = ResolveModelMetrics(AnalyticsModel.Metrics); //Allows the evolution type to be modified pre-calculation. //Set the children foreach (var cashflow in GetChildren()) { if (cashflow is PriceableCashflow priceableCashflow) { priceableCashflow.BucketedDates = BucketedDates; priceableCashflow.PricingStructureEvolutionType = PricingStructureEvolutionType; priceableCashflow.Multiplier = Multiplier; } } var childControllers = new List <InstrumentControllerBase>(GetChildren()); //The assetValuation list. ChildValuations = new List <AssetValuation>(); // 2. Now evaluate only the child specific metrics (if any) ChildValuations = EvaluateChildMetrics(childControllers, modelData, Metrics); var childControllerValuations = AssetValuationHelper.AggregateMetrics(ChildValuations, new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); childControllerValuations.id = Id + ".Cashflows"; AssetValuation depositValuation; // Child metrics have now been calculated so we can now evaluate the stream model metrics if (termDepositControllerMetrics.Count > 0) { var reportingCurrency = ModelData.ReportingCurrency == null ? Currency.Value : ModelData.ReportingCurrency.Value; var marketQuote = FixedRate; ITermDepositInstrumentParameters analyticModelParameters = new TermDepositInstrumentParameters { Multiplier = Multiplier, Currency = Currency.Value, ReportingCurrency = reportingCurrency, BreakEvenRate = InterestAmount.CalculationResults.ImpliedQuote, MarketQuote = marketQuote }; CalculationResults = AnalyticsModel.Calculate <ITermDepositInstrumentResults, TermDepositInstrumentResults>(analyticModelParameters, termDepositControllerMetrics.ToArray()); // Now merge back into the overall stream valuation var streamControllerValuation = GetValue(CalculationResults, modelData.ValuationDate); depositValuation = AssetValuationHelper.UpdateValuation(streamControllerValuation, ChildValuations, ConvertMetrics(termDepositControllerMetrics), new List <string>(Metrics), PaymentCurrencies);// modelData.ValuationDate); } else { depositValuation = childControllerValuations; } CalculationPerformedIndicator = true; depositValuation.id = Id; return(depositValuation); }