/// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>
        /// <returns></returns>
        public override BasicAssetValuation Calculate(IAssetControllerData modelData)
        {
            ModelData      = modelData;
            AnalyticsModel = new LeaseAssetAnalytic();
            var metrics = MetricsHelper.GetMetricsToEvaluate(Metrics, AnalyticsModel.Metrics);
            // Determine if DFAM has been requested - if so that's all we evaluate - every other metric is ignored
            var metricsToEvaluate       = metrics.ToArray();
            var analyticModelParameters = new LeaseAssetParameters();

            CalculationResults = new LeaseAssetAnalytic();
            var marketEnvironment = modelData.MarketEnvironment;
            //IRateCurve rate forecast curve = null;
            IRateCurve leaseCurve = null;

            //0. Set the valuation date and recalculate the settlement date. This could mean regenerating all the coupon dates as well
            //Alternatively the lease can be recreated with a different base date = valuation date.
            //1. instantiate curve
            if (marketEnvironment.GetType() == typeof(SimpleMarketEnvironment))
            {
                leaseCurve             = (IRateCurve)((ISimpleMarketEnvironment)marketEnvironment).GetPricingStructure();
                LeaseDiscountCurveName = leaseCurve.GetPricingStructureId().UniqueIdentifier;
            }
            if (marketEnvironment.GetType() == typeof(SimpleRateMarketEnvironment))
            {
                leaseCurve             = ((ISimpleRateMarketEnvironment)marketEnvironment).GetRateCurve();
                LeaseDiscountCurveName = leaseCurve.GetPricingStructureId().UniqueIdentifier;
            }
            if (marketEnvironment.GetType() == typeof(SwapLegEnvironment))
            {
                leaseCurve             = ((ISwapLegEnvironment)marketEnvironment).GetDiscountRateCurve();
                LeaseDiscountCurveName = leaseCurve.GetPricingStructureId().UniqueIdentifier;
            }
            if (marketEnvironment.GetType() == typeof(MarketEnvironment))
            {
                leaseCurve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(LeaseDiscountCurveName);
            }
            //2. Set the rate and the Multiplier
            analyticModelParameters.Multiplier = Multiplier;
            //analyticModelParameters.Quote = QuoteValue;
            analyticModelParameters.GrossAmount = StartAmount;
            analyticModelParameters.StepUp      = LeaseRate;
            //3. Get the discount factors
            analyticModelParameters.PaymentDiscountFactors =
                GetDiscountFactors(leaseCurve, AdjustedPeriodDates, modelData.ValuationDate);
            //4. Get the Weightings
            analyticModelParameters.Weightings = Weightings;
            //5. Set the analytic input parameters and Calculate the respective metrics
            AnalyticModelParameters = analyticModelParameters;
            CalculationResults      =
                AnalyticsModel.Calculate <ILeaseAssetResults, LeaseAssetResults>(analyticModelParameters,
                                                                                 metricsToEvaluate);
            //ExpectedCashflows =
            //CashflowPVs =
            return(GetValue(CalculationResults));
        }
Beispiel #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RateBasisCurve"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        ///  <param name="nameSpace">The client namespace</param>
        /// <param name="baseDiscountingCurve">The reference curve.</param>
        /// <param name="clearedRateAssets">The cleared rate asset.</param>
        /// <param name="properties">The properties of the new spread curve.</param>
        /// <param name="fixingCalendar">The fixingCalendar.</param>
        /// <param name="rollCalendar">The rollCalendar.</param>
        public ClearedRateCurve(ILogger logger, ICoreCache cache, string nameSpace,
                                IRateCurve baseDiscountingCurve, QuotedAssetSet clearedRateAssets, NamedValueSet properties,
                                IBusinessCalendar fixingCalendar, IBusinessCalendar rollCalendar)
            : base(logger, cache, nameSpace, new RateCurveIdentifier(properties), fixingCalendar, rollCalendar)
        {
            PricingStructureData        = new PricingStructureData(CurveType.Child, AssetClass.Rates, properties);
            BaseDiscountingCurve        = baseDiscountingCurve;
            ReferenceDiscountingCurveId = BaseDiscountingCurve.GetPricingStructureId();
            if (PricingStructureIdentifier.PricingStructureType != PricingStructureTypeEnum.ClearedRateCurve)
            {
                return;
            }
            var termCurve  = SetConfigurationData();
            var curveId    = GetRateCurveId();
            var indexTenor = curveId.ForecastRateIndex?.indexTenor;

            //Set the priceable assets.
            PriceableClearedRateAssets = PriceableAssetFactory.CreatePriceableClearedRateAssetsWithBasisSwaps(logger, cache, nameSpace, indexTenor, clearedRateAssets, PricingStructureIdentifier.BaseDate, fixingCalendar, rollCalendar);
            termCurve.point            = ClearedRateBootstrapper.Bootstrap(PriceableClearedRateAssets, BaseDiscountingCurve, curveId.BaseDate, termCurve.extrapolationPermitted,
                                                                           termCurve.interpolationMethod, Tolerance);
            CreatePricingStructure(curveId, termCurve, clearedRateAssets);
            // CreatePricingStructure(curveId, termCurve, PriceableAssetFactory.Parse(PriceableClearedRateAssets));
            // Interpolate the DiscountFactor curve based on the respective curve interpolation
            SetInterpolator(termCurve);
        }
Beispiel #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RateSpreadCurve"/> class.
 /// </summary>
 /// <param name="logger">The logger.</param>
 /// <param name="cache">The cache.</param>
 ///  <param name="nameSpace">The client namespace</param>
 /// <param name="referenceCurve">The reference parent curve id.</param>
 /// <param name="spreadAssets">The spreads by asset.</param>
 /// <param name="properties">The properties of the new spread curve.</param>
 /// <param name="fixingCalendar">The fixingCalendar.</param>
 /// <param name="rollCalendar">The rollCalendar.</param>
 public RateSpreadCurve(ILogger logger, ICoreCache cache, string nameSpace,
                        IRateCurve referenceCurve, QuotedAssetSet spreadAssets, NamedValueSet properties,
                        IBusinessCalendar fixingCalendar, IBusinessCalendar rollCalendar)
     : base(logger, cache, nameSpace, ProcessQuotedAssetSet(logger, cache, nameSpace, referenceCurve, spreadAssets, properties, fixingCalendar, rollCalendar), properties, fixingCalendar, rollCalendar)
 {
     PricingStructureData = new PricingStructureData(CurveType.Child, AssetClass.Rates, properties);
     BaseCurve            = referenceCurve;
     ReferenceCurveId     = BaseCurve.GetPricingStructureId();
 }
Beispiel #4
0
        public override AssetValuation Calculate(IInstrumentControllerData modelData)
        {
            ModelData = modelData;
            AnalyticModelParameters = new FuturesAssetParameters();
            AnalyticsModel          = new FuturesTransactionAnalytic();
            var marketEnvironment              = modelData.MarketEnvironment;
            var metrics                        = ResolveModelMetrics(AnalyticsModel.Metrics);
            var metricsAsArray                 = metrics.Select(metric => metric).ToArray();
            IExchangeTradedCurve futuresCurve  = null;
            IRateCurve           discountCurve = null;

            //1. instantiate curve
            if (marketEnvironment.GetType() == typeof(SimpleMarketEnvironment))
            {
                discountCurve     = (IRateCurve)((ISimpleMarketEnvironment)marketEnvironment).GetPricingStructure();
                DiscountCurveName = discountCurve.GetPricingStructureId().UniqueIdentifier;
                futuresCurve      = (IExchangeTradedCurve)((ISimpleMarketEnvironment)marketEnvironment).GetPricingStructure();
                FuturesCurveName  = futuresCurve.GetPricingStructureId().UniqueIdentifier;
            }
            if (marketEnvironment.GetType() == typeof(MarketEnvironment))
            {
                futuresCurve  = (IExchangeTradedCurve)modelData.MarketEnvironment.GetPricingStructure(FuturesCurveName);
                discountCurve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(DiscountCurveName);
            }
            var settlementDF = 1.0;

            if (discountCurve != null)
            {
                settlementDF = discountCurve.GetDiscountFactor(SettlementDate);
            }
            //var interval = FuturesTypeInfo.;
            AnalyticModelParameters.SettlementDiscountFactor = Convert.ToDecimal(settlementDF);
            AnalyticModelParameters.Multiplier        = Multiplier;
            AnalyticModelParameters.AccrualPeriod     = 0.25m;
            AnalyticModelParameters.NumberOfContracts = NumberOfContracts;
            AnalyticModelParameters.TradePrice        = PurchasePrice.amount;
            AnalyticModelParameters.ContractNotional  = Convert.ToDecimal(FuturesTypeInfo.Future.multiplier);
            //Get the discountfactor to the settlemetn date
            if (futuresCurve != null)
            {
                AnalyticModelParameters.Quote = Convert.ToDecimal(futuresCurve.GetForward(LastTradeDate));
            }
            AnalyticResults =
                AnalyticsModel.Calculate <IFuturesAssetResults, FuturesAssetResults>(AnalyticModelParameters,
                                                                                     metricsAsArray);
            // store inputs and results from this run
            CalculationPerfomedIndicator = true;
            return(GetValue(CalculationResults, modelData.ValuationDate));
        }
Beispiel #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RateBasisCurve"/> class.
 /// </summary>
 /// <param name="logger">The logger.</param>
 /// <param name="cache">The cache.</param>
 ///  <param name="nameSpace">The client namespace</param>
 /// <param name="referenceCurve">The reference parent curve id.</param>
 /// <param name="spreadAssets">The spreads by asset.</param>
 /// <param name="properties">The properties of the new spread curve.</param>
 /// <param name="fixingCalendar">The fixingCalendar.</param>
 /// <param name="rollCalendar">The rollCalendar.</param>
 public RateBasisCurve(ILogger logger, ICoreCache cache, string nameSpace,
                       IRateCurve referenceCurve, QuotedAssetSet spreadAssets, NamedValueSet properties,
                       IBusinessCalendar fixingCalendar, IBusinessCalendar rollCalendar)
     : base(logger, cache, nameSpace, ProcessQuotedAssetSet(logger, cache, nameSpace, referenceCurve, spreadAssets, properties, fixingCalendar, rollCalendar), properties, fixingCalendar, rollCalendar)
 {
     PricingStructureData = new PricingStructureData(CurveType.Child, AssetClass.Rates, properties);
     BaseCurve            = referenceCurve;
     ReferenceCurveId     = BaseCurve.GetPricingStructureId();
     if (PricingStructureIdentifier.PricingStructureType != PricingStructureTypeEnum.RateBasisCurve)
     {
         return;
     }
     //Set the spread sets.
     PriceableRateSpreadAssets = PriceableAssetFactory.CreatePriceableRateSpreadAssets(logger, cache, nameSpace, PricingStructureIdentifier.BaseDate, spreadAssets, fixingCalendar, rollCalendar);
     Build(logger, cache, nameSpace, fixingCalendar, rollCalendar);
 }
Beispiel #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RateBasisCurve"/> class.
        /// </summary>
        /// <param name="referenceCurve">The reference curve.</param>
        /// <param name="spreadAssets">The spreads by asset.</param>
        /// <param name="properties">The properties of the new spread curve.</param>
        /// <param name="algorithm">The algorithm holder. </param>
        public RateBasisCurve(NamedValueSet properties, IRateCurve referenceCurve,
                              List <IPriceableRateSpreadAssetController> spreadAssets, PricingStructureAlgorithmsHolder algorithm)
            : base(properties, algorithm)
        {
            PricingStructureData = new PricingStructureData(CurveType.Child, AssetClass.Rates, properties);
            //Set the identifier.
            var pricingStructureId = GetRateCurveId();

            if (pricingStructureId.PricingStructureType != PricingStructureTypeEnum.RateBasisCurve)
            {
                return;
            }
            //Set the reference curve
            BaseCurve                 = referenceCurve;
            ReferenceCurveId          = BaseCurve.GetPricingStructureId();
            PriceableRateSpreadAssets = spreadAssets;
            //Order the assets.
            PriceableRateSpreadAssets = PriceableRateSpreadAssets.OrderBy(a => a.GetRiskMaturityDate()).ToList();
            var termCurve = SetConfigurationData();

            //Get the reference interpolated curve.
            termCurve.point = RateSpreadBootstrapper.Bootstrap(PriceableRateSpreadAssets,
                                                               BaseCurve,
                                                               pricingStructureId.BaseDate,
                                                               termCurve.extrapolationPermitted,
                                                               Tolerance);
            CreatePricingStructure(pricingStructureId, termCurve, PriceableAssetFactory.Parse(PriceableRateSpreadAssets));
            SetInterpolator(BaseCurve, pricingStructureId.PricingStructureType);
            // Set the Zero curve, just for reference
            YieldCurveValuation yieldCurveValuation = GetYieldCurveValuation();

            if (yieldCurveValuation.zeroCurve?.rateCurve == null)
            {
                //var curveId = (RateCurveIdentifier)PricingStructureIdentifier;
                //var psType = PricingStructureIdentifier.PricingStructureType;
                TermCurve curve = YieldCurveAnalytics.ToZeroCurve(termCurve, GetBaseDate(), CompoundingFrequency, DayCounter);
                curve.interpolationMethod = InterpolationMethodHelper.Parse(Holder.GetValue("CurveInterpolation"));
                var zeroCurve = new ZeroRateCurve
                {
                    rateCurve            = curve,
                    compoundingFrequency = FpML.V5r3.Reporting.CompoundingFrequency.Create(CompoundingFrequency)
                };
                yieldCurveValuation.zeroCurve = zeroCurve;
            }
        }
        public NewtonRaphsonSolverFunctions(IPriceableAssetController asset, IPriceableAssetController previousAsset, PricingStructureAlgorithmsHolder algorithmHolder,
                                            IRateCurve baseCurve, DateTime baseDate, SortedDictionary <DateTime, Pair <string, decimal> > items,
                                            double compoundingPeriod, IDictionary <DateTime, double> zeroRateSpreads, IDayCounter dayCounter,
                                            List <DateTime> assetDates)
        {
            _asset           = asset;
            _baseCurve       = baseCurve;
            _zeroRateSpreads = zeroRateSpreads;
            string currency = PropertyHelper.ExtractCurrency(baseCurve.GetPricingStructureId().Properties);

            _algorithm  = algorithmHolder;
            _properties = new NamedValueSet(new Dictionary <string, object>
            {
                { CurveProp.PricingStructureType, "RateCurve" },
                { CurveProp.Market, "DiscountCurveConstruction" },
                { CurveProp.IndexTenor, "0M" },
                { CurveProp.Currency1, currency },
                { "Index", "XXX-XXX" },
                { "Algorithm", "FastLinearZero" },
                { "BaseDate", baseDate },
            });
            _items             = items;
            _compoundingPeriod = compoundingPeriod;
            _dayCounter        = dayCounter;
            _assetDates        = assetDates;
            if (previousAsset != null)
            {
                DateTime previousAssetMaturity = previousAsset.GetRiskMaturityDate();
                DateTime assetMaturity         = asset.GetRiskMaturityDate();
                IEnumerable <KeyValuePair <DateTime, string> > points
                    = from b in baseCurve.GetTermCurve().point
                      where (DateTime)b.term.Items[0] > previousAssetMaturity &&
                      (DateTime)b.term.Items[0] < assetMaturity
                      select new KeyValuePair <DateTime, string>((DateTime)b.term.Items[0], b.id);
                foreach (KeyValuePair <DateTime, string> point in points)
                {
                    _extraPoints.Add(point.Key, point.Value);
                    Pair <string, decimal> pair = new Pair <string, decimal>(point.Value, 0);
                    items.Add(point.Key, pair);
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="valuationDate">The valuation date.</param>
        /// <param name="discountCurve">The discount curve.</param>
        /// <param name="forecastCurve">The forward curve.</param>
        /// <param name="volCurve">The volatility surface.
        /// and discount curves when called with ForecastRateCurve.</param>
        /// <param name="curveToPerturb">The curve to perturb: the discount curve, the forecast curve or both.</param>
        /// <returns></returns>
        public IDictionary <string, double> CalculateRatePDH(DateTime valuationDate,
                                                             IRateCurve discountCurve, IRateCurve forecastCurve, IVolatilitySurface volCurve, CurvePerturbation curveToPerturb)
        {
            var result = new Dictionary <string, double>();

            AnalyticResults = new RateOptionAssetResults();
            switch (ModelIdentifier)
            {
            case "CapAsset":
                AnalyticsModel = new RateOptionAssetAnalytic();
                break;

            case "DiscountCapAsset":
                AnalyticsModel = new RateOptionAssetAnalytic();
                break;
            }
            ForecastCurveName   = forecastCurve.GetPricingStructureId().UniqueIdentifier;
            DiscountCurveName   = discountCurve.GetPricingStructureId().UniqueIdentifier;
            VolatilityCurveName = volCurve.GetPricingStructureId().UniqueIdentifier;
            var analyticModelParameters = new RateOptionAssetParameters {
                IsPut = !IsCap, Notionals = Notionals
            };

            //and the rest rates
            if (ResetRates != null)
            {
                analyticModelParameters.ForwardRates = ResetRates;
            }
            //2. Get the discount factors
            analyticModelParameters.ForecastDiscountFactors =
                GetDiscountFactors(forecastCurve, AdjustedPeriodDates.ToArray(), valuationDate);
            analyticModelParameters.PaymentDiscountFactors =
                GetDiscountFactors(discountCurve, AdjustedPeriodDates.ToArray(), valuationDate);
            //3. Get the respective year fractions
            analyticModelParameters.YearFractions = YearFractions;
            //4. set the expiry times.
            TimesToExpiry =
                GetTimesToExpiry(ExpiryDates, valuationDate);
            analyticModelParameters.TimesToExpiry = TimesToExpiry;
            //5. Get the vols
            analyticModelParameters.Volatilities =
                GetVolatilties(volCurve, TimesToExpiry, Strikes);
            //8. Get the Strikes
            analyticModelParameters.Strikes = Strikes;
            //9. Set the analytic input parameters and Calculate the respective metrics
            var analyticResults =
                AnalyticsModel.Calculate <IRateOptionAssetResults, RateOptionAssetResults>(analyticModelParameters,
                                                                                           new[] { RateOptionMetrics.NPV });

            AnalyticResults = analyticResults;
            var baseNPV = SumDoubleList(AnalyticResults.NPV, 0);

            //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, baseNPV - SumDoubleList(analyticResults.NPV, 0));
                }
            }
            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, baseNPV - SumDoubleList(analyticResults.NPV, 0));
                }
            }
            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, baseNPV - SumDoubleList(analyticResults.NPV, 0));
                }
                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, baseNPV - SumDoubleList(analyticResults.NPV, 0));
                }
            }
            return(result);
        }
Beispiel #9
0
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>
        /// <returns></returns>
        public override BasicAssetValuation Calculate(IAssetControllerData modelData)
        {
            ModelData = modelData;
            switch (ModelIdentifier)
            {
            case "CapAsset":
                AnalyticsModel = new RateOptionAssetAnalytic();
                break;

            case "DiscountCapAsset":
                AnalyticsModel = new RateOptionAssetAnalytic();
                break;
            }
            var metrics                 = MetricsHelper.GetMetricsToEvaluate(Metrics, AnalyticsModel.Metrics);
            var metricsToEvaluate       = metrics.ToArray();
            var analyticModelParameters = new RateOptionAssetParameters();

            AnalyticResults = new RateOptionAssetResults();
            var                marketEnvironment = modelData.MarketEnvironment;
            IRateCurve         rateCurve         = null;
            IRateCurve         discountCurve     = null;
            IVolatilitySurface volCurve          = null;

            //1. instantiate curve
            if (marketEnvironment.GetType() == typeof(SwapLegEnvironment))
            {
                rateCurve           = ((ISwapLegEnvironment)marketEnvironment).GetForecastRateCurve();
                ForecastCurveName   = rateCurve.GetPricingStructureId().UniqueIdentifier;
                discountCurve       = ((ISwapLegEnvironment)marketEnvironment).GetDiscountRateCurve();
                DiscountCurveName   = discountCurve.GetPricingStructureId().UniqueIdentifier;
                volCurve            = ((ISwapLegEnvironment)marketEnvironment).GetVolatilitySurface();
                VolatilityCurveName = volCurve.GetPricingStructureId().UniqueIdentifier;
            }
            //Cap logic.
            analyticModelParameters.IsPut = !IsCap;
            //1. Notionals
            analyticModelParameters.Notionals = Notionals;
            //and the rest rates
            if (ResetRates != null)
            {
                analyticModelParameters.ForwardRates = ResetRates;
            }
            //2. Get the discount factors
            analyticModelParameters.ForecastDiscountFactors =
                GetDiscountFactors(rateCurve, AdjustedPeriodDates.ToArray(), modelData.ValuationDate);
            analyticModelParameters.PaymentDiscountFactors =
                GetDiscountFactors(discountCurve, AdjustedPeriodDates.ToArray(), modelData.ValuationDate);
            //3. Get the respective year fractions
            analyticModelParameters.YearFractions = YearFractions;
            //4. set the expiry times.
            TimesToExpiry =
                GetTimesToExpiry(ExpiryDates, modelData.ValuationDate);
            analyticModelParameters.TimesToExpiry = TimesToExpiry;
            //5. Get the vols
            analyticModelParameters.Volatilities =
                GetVolatilties(volCurve, TimesToExpiry, Strikes);
            //8. Get the Strikes
            analyticModelParameters.Strikes = Strikes;
            ParRate = CalculateImpliedParRate(modelData.ValuationDate);
            analyticModelParameters.Rate = (double)ParRate;
            //9. Set the analytic input parameters and Calculate the respective metrics
            AnalyticResults =
                AnalyticsModel.Calculate <IRateOptionAssetResults, RateOptionAssetResults>(analyticModelParameters,
                                                                                           metricsToEvaluate);
            //TODO change this method and return a table report of all greeks.
            return(GetValue(AnalyticResults));
        }
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>
        /// <returns></returns>
        public override BasicAssetValuation Calculate(IAssetControllerData modelData)
        {
            ModelData      = modelData;
            AnalyticsModel = new InflationAssetAnalytic();
            //DependencyCreator.Resolve<IModelAnalytic<ISimpleDualAssetParameters, RateMetrics>>("InflationAsset");
            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;
                metrics.RemoveAll(
                    metricItem => metricItem != RateMetrics.DiscountFactorAtMaturity);
            }

            ISimpleDualAssetParameters analyticModelParameters = new DualRateAssetParameters
            {
                YearFraction = YearFraction
            };

            AnalyticResults = 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
            analyticModelParameters.Rate = MarketQuoteHelper.NormalisePriceUnits(FixedRate, "DecimalRate").value;
            if (bEvalDiscountFactorAtMaturity)
            {
                //4. Set the anaytic input parameters and Calculate the respective metrics
                AnalyticResults =
                    AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters,
                                                                                   metricsToEvaluate);
                EndDiscountFactor = DiscountFactorAtMaturity;
            }
            else
            {
                analyticModelParameters.NotionalAmount = Notional;
                //3. Get the end index discount factor
                analyticModelParameters.EndDiscountFactor =
                    GetDiscountFactor(curve, GetRiskMaturityDate(), modelData.ValuationDate);
                //4. Get the payment discount factor
                analyticModelParameters.PaymentDiscountFactor =
                    GetDiscountFactor(curve, GetRiskMaturityDate(), modelData.ValuationDate);
                //5. Set the anaytic input parameters and Calculate the respective metrics
                AnalyticResults =
                    AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters,
                                                                                   metricsToEvaluate);
            }
            return(GetValue(AnalyticResults));
        }
        /// <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);
        }
Beispiel #12
0
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>
        /// <returns></returns>
        public override BasicAssetValuation Calculate(IAssetControllerData modelData)
        {
            ModelData      = modelData;
            AnalyticsModel = new ZeroCouponRateAssetAnalytic();
            //DependencyCreator.Resolve<IModelAnalytic<IZeroRateAssetParameters, 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);
            }
            IZeroRateAssetParameters analyticModelParameters = new ZeroRateAssetParameters {
                YearFraction = YearFraction
            };

            CalculationResults = new RateAssetResults();
            var metricsToEvaluate = metrics.ToArray();

            analyticModelParameters.PeriodAsTimesPerYear =
                CompoundingHelper.PeriodFractionFromCompoundingFrequency(BaseDate, CompoundingFrequency, DayCountFraction);
            var        marketEnvironment = modelData.MarketEnvironment;
            IRateCurve curve             = null;

            //1. instantiate curve
            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.StartDiscountFactor = GetDiscountFactor(curve, BaseDate, 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
                //
                analyticModelParameters.EndDiscountFactor = GetDiscountFactor(curve, GetRiskMaturityDate(), modelData.ValuationDate);
                //4. Set the anaytic input parameters and Calculate the respective metrics
                //
                CalculationResults = AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters, metricsToEvaluate);
            }

            return(GetValue(CalculationResults));
        }
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>
        /// <returns></returns>
        public override BasicAssetValuation Calculate(IAssetControllerData modelData)
        {
            ModelData      = modelData;
            AnalyticsModel = new BondAssetAnalytic();
            var metrics = MetricsHelper.GetMetricsToEvaluate(Metrics, AnalyticsModel.Metrics);
            // Determine if DFAM has been requested - if so that's all we evaluate - every other metric is ignored
            var metricsToEvaluate       = metrics.ToArray();
            var analyticModelParameters = new BondAssetParameters();

            CalculationResults = new BondAssetResults();
            var marketEnvironment = modelData.MarketEnvironment;
            //IRateCurve rate forecast curve = null;
            IRateCurve rateDiscountCurve = null;

            //0. Set the valuation date and recalculate the settlement date. This could mean regenerating all the coupon dates as well
            //Alternatively the bond can be recreated with a different base date = valuation date.
            //TODO Check that the dates are correct and that the last coupon date is used.
            //Set the purchase price.
            analyticModelParameters.PurchasePrice = PurchasePrice;
            //1. instantiate curve
            if (marketEnvironment.GetType() == typeof(SimpleMarketEnvironment))
            {
                rateDiscountCurve     = (IRateCurve)((ISimpleMarketEnvironment)marketEnvironment).GetPricingStructure();
                SwapDiscountCurveName = rateDiscountCurve.GetPricingStructureId().UniqueIdentifier;
            }
            if (marketEnvironment.GetType() == typeof(SimpleRateMarketEnvironment))
            {
                rateDiscountCurve     = ((ISimpleRateMarketEnvironment)marketEnvironment).GetRateCurve();
                SwapDiscountCurveName = rateDiscountCurve.GetPricingStructureId().UniqueIdentifier;
            }
            if (marketEnvironment.GetType() == typeof(SwapLegEnvironment))
            {
                rateDiscountCurve     = ((ISwapLegEnvironment)marketEnvironment).GetDiscountRateCurve();
                SwapDiscountCurveName = rateDiscountCurve.GetPricingStructureId().UniqueIdentifier;
            }
            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());
                }
                //The forecast rate curve will need to be set if it is a floating rate note.
                rateDiscountCurve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(SwapDiscountCurveName);
            }
            //2. Set the rate and the Multiplier
            analyticModelParameters.Multiplier             = Multiplier;
            analyticModelParameters.Quote                  = QuoteValue;
            analyticModelParameters.CouponRate             = GetCouponRate();
            analyticModelParameters.NotionalAmount         = Notional;
            analyticModelParameters.Frequency              = Frequency;
            analyticModelParameters.IsYTMQuote             = IsYTMQuote;
            analyticModelParameters.AccruedFactor          = GetAccruedFactor();
            analyticModelParameters.RemainingAccruedFactor = GetRemainingAccruedFactor();
            //3. Get the discount factors
            analyticModelParameters.PaymentDiscountFactors =
                GetDiscountFactors(rateDiscountCurve, AdjustedPeriodDates, modelData.ValuationDate);
            //4. Get the respective year fractions
            analyticModelParameters.AccrualYearFractions = GetYearFractions();
            //5. Get the Weightings
            Weightings =
                CreateWeightings(CDefaultWeightingValue, analyticModelParameters.PaymentDiscountFactors.Length);
            analyticModelParameters.Weightings = Weightings;
            //6. Set the analytic input parameters and Calculate the respective metrics
            AnalyticModelParameters = analyticModelParameters;
            CalculationResults      =
                AnalyticsModel.Calculate <IBondAssetResults, BondAssetResults>(analyticModelParameters,
                                                                               metricsToEvaluate);
            return(GetValue(CalculationResults));
        }
Beispiel #14
0
        /// <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));
        }
Beispiel #15
0
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>
        /// <returns></returns>
        public override BasicAssetValuation Calculate(IAssetControllerData modelData)
        {
            ModelData = modelData;
            switch (ModelIdentifier)
            {
            case "SwapAsset":
                AnalyticsModel = new SwapAssetAnalytic();
                break;

            case "DiscountSwapAsset":
                AnalyticsModel = new DiscountSwapAssetAnalytic();
                break;
            }
            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;
                metrics.RemoveAll(
                    metricItem => metricItem != RateMetrics.DiscountFactorAtMaturity);
            }
            var metricsToEvaluate = metrics.ToArray();
            ISwapAssetParameters analyticModelParameters = new IRSwapAssetParameters();

            AnalyticResults = new RateAssetResults();
            var        marketEnvironment = modelData.MarketEnvironment;
            IRateCurve curve             = null;
            IRateCurve forecastCurve     = null;

            //1. instantiate curve
            if (marketEnvironment.GetType() == typeof(SimpleMarketEnvironment))
            {
                curve             = (IRateCurve)((ISimpleMarketEnvironment)marketEnvironment).GetPricingStructure();
                CurveName         = curve.GetPricingStructureId().UniqueIdentifier;
                ForecastCurveName = CurveName;
            }
            if (marketEnvironment.GetType() == typeof(SimpleRateMarketEnvironment))
            {
                curve             = ((ISimpleRateMarketEnvironment)marketEnvironment).GetRateCurve();
                CurveName         = curve.GetPricingStructureId().UniqueIdentifier;
                ForecastCurveName = CurveName;
            }
            if (marketEnvironment.GetType() == typeof(SwapLegEnvironment))
            {
                curve             = ((ISwapLegEnvironment)marketEnvironment).GetDiscountRateCurve();
                CurveName         = curve.GetPricingStructureId().UniqueIdentifier;
                forecastCurve     = ((ISwapLegEnvironment)marketEnvironment).GetForecastRateCurve();
                ForecastCurveName = forecastCurve.GetPricingStructureId().UniqueIdentifier;
            }
            if (marketEnvironment.GetType() == typeof(MarketEnvironment))
            {
                curve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(CurveName);
                if (ForecastCurveName != null)
                {
                    forecastCurve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(ForecastCurveName);
                }
            }
            if (forecastCurve == null)
            {
                forecastCurve = curve;
            }
            //2. Set the rate
            analyticModelParameters.Rate = MarketQuoteHelper.NormalisePriceUnits(FixedRate, "DecimalRate").value;
            if (bEvalDiscountFactorAtMaturity)
            {
                //3. Set the start diccount factor
                analyticModelParameters.StartDiscountFactor =
                    GetDiscountFactor(curve, AdjustedStartDate, modelData.ValuationDate);
                //4. Get the respective year fractions
                analyticModelParameters.YearFractions = YearFractions;
                //5. Set the anaytic input parameters and Calculate the respective metrics
                AnalyticResults =
                    AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters,
                                                                                   metricsToEvaluate);
            }
            else
            {
                analyticModelParameters.NotionalAmount = Notional;
                //1. Get any rates that have reset.
                if (ForwardRates != null)
                {
                    analyticModelParameters.FloatingLegForwardRates = ForwardRates;
                }
                //2. Get the discount factors
                analyticModelParameters.DiscountFactors =
                    GetDiscountFactors(curve, AdjustedPeriodDates.ToArray(), modelData.ValuationDate);
                //3. Get the respective year fractions
                analyticModelParameters.YearFractions = YearFractions;
                //4. Get the Weightings
                analyticModelParameters.Weightings = Weightings;
                //5. Get the respective year fractions
                analyticModelParameters.FloatingLegYearFractions = FloatingLegYearFractions;
                //6. Get the Weightings
                analyticModelParameters.FloatingLegWeightings = FloatingLegWeightings;
                //7. Get the floating discount factors
                analyticModelParameters.FloatingLegDiscountFactors =
                    GetDiscountFactors(curve, FloatingLegAdjustedPeriodDates.ToArray(), modelData.ValuationDate);
                //8. Get the forecast curve discount factors.
                analyticModelParameters.FloatingLegForecastDiscountFactors =
                    GetDiscountFactors(forecastCurve, FloatingLegAdjustedPeriodDates.ToArray(), modelData.ValuationDate);
                //9. Get the Spread
                analyticModelParameters.FloatingLegSpread = FloatingLegSpread?.value ?? 0.0m;
                //10. Set the anaytic input parameters and Calculate the respective metrics
                AnalyticResults =
                    AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters,
                                                                                   metricsToEvaluate);
            }
            return(GetValue(AnalyticResults));
        }
Beispiel #16
0
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>
        /// <returns></returns>
        public override BasicAssetValuation Calculate(IAssetControllerData modelData)
        {
            ModelData      = modelData;
            AnalyticsModel = new SwapAssetAnalytic();
            //DependencyCreator.Resolve<IModelAnalytic<ISwapAssetParameters, RateMetrics>>("InflationSwapAsset");
            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;
                metrics.RemoveAll(
                    metricItem => metricItem != RateMetrics.DiscountFactorAtMaturity);
            }
            var metricsToEvaluate = metrics.ToArray();
            ISwapAssetParameters analyticModelParameters = new IRSwapAssetParameters();

            AnalyticResults = new RateAssetResults();
            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. Set the rate
            analyticModelParameters.Rate = MarketQuoteHelper.NormalisePriceUnits(FixedRate, "DecimalRate").value;
            if (bEvalDiscountFactorAtMaturity)
            {
                //3. Set the start diccount factor
                analyticModelParameters.StartDiscountFactor =
                    GetDiscountFactor(curve, AdjustedStartDate, modelData.ValuationDate);
                //4. Get the respective year fractions
                analyticModelParameters.YearFractions = GetYearFractions();
                //5. Set the anaytic input parameters and Calculate the respective metrics
                AnalyticResults =
                    AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters,
                                                                                   metricsToEvaluate);
            }
            else
            {
                //2. Get the discount factors
                analyticModelParameters.DiscountFactors =
                    GetDiscountFactors(curve, AdjustedPeriodDates.ToArray(), modelData.ValuationDate);
                //3. Get the respective year fractions
                analyticModelParameters.YearFractions = GetYearFractions();
                //4. Get the Weightings
                analyticModelParameters.Weightings =
                    CreateWeightings(CDefaultWeightingValue, analyticModelParameters.DiscountFactors.Length);
                //5. Set the anaytic input parameters and Calculate the respective metrics
                AnalyticResults =
                    AnalyticsModel.Calculate <IRateAssetResults, RateAssetResults>(analyticModelParameters,
                                                                                   metricsToEvaluate);
            }
            return(GetValue(AnalyticResults));
        }