Exemplo n.º 1
0
        /// <summary>
        /// Gets and sets the required pricing structures to value this leg.
        /// </summary>
        public List <String> GetRequiredPricingStructures()
        {
            var result = new List <String>();

            if (calculationPeriodAmount.Item is Calculation amount)
            {
                var currency = XsdClassesFieldResolver.CalculationGetNotionalSchedule(amount);
                if (currency?.notionalStepSchedule != null)
                {
                    var discountCurve = CurveNameHelpers.GetDiscountCurveName(currency.notionalStepSchedule.currency, true);
                    result.Add(discountCurve);
                }
                if (amount.Items[0] is FloatingRateCalculation floatingRateCalculation)
                {
                    result.Add(CurveNameHelpers.GetForecastCurveName(floatingRateCalculation.floatingRateIndex, floatingRateCalculation.indexTenor));
                }
            }
            //TODO
            if (stubCalculationPeriodAmount != null)
            {
                if (stubCalculationPeriodAmount.initialStub?.Items != null)
                {
                    result.AddRange(from value in stubCalculationPeriodAmount.initialStub.Items
                                    where value is Money
                                    select CurveNameHelpers.GetDiscountCurveName(((Money)value).currency, true));
                }
                if (stubCalculationPeriodAmount.finalStub?.Items != null)
                {
                    result.AddRange(from value in stubCalculationPeriodAmount.finalStub.Items
                                    where value is Money
                                    select CurveNameHelpers.GetDiscountCurveName(((Money)value).currency, true));
                }
            }
            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Updates forecastRate, forecastPaymentAmount, discountFactor and presentValueAmount of each paymentCalculation period.
        /// </summary>
        /// <param name="interestRateStream">The interest rate stream.</param>
        /// <param name="forecastCurve">The forecast curve.</param>
        /// <param name="discountCurve">The discount curve.</param>
        /// <param name="valuationDate">The valuation date.</param>
        public static void UpdateCashflowsAmounts(InterestRateStream interestRateStream,
                                                  IRateCurve forecastCurve, IRateCurve discountCurve,
                                                  DateTime valuationDate)
        {
            //FixAfterManualUpdate(interestRateStream);//should it be removed, since it might produce subtle errors which will be effectively hidden.
            Calculation calculation = XsdClassesFieldResolver.CalculationPeriodAmountGetCalculation(interestRateStream.calculationPeriodAmount);

            UpdateNumberOfDaysAndYearFraction(new List <PaymentCalculationPeriod>(interestRateStream.cashflows.paymentCalculationPeriod), calculation);
            FloatingRateCalculation floatingRateCalculation =
                XsdClassesFieldResolver.CalculationHasFloatingRateCalculation(calculation)
                    ? XsdClassesFieldResolver.CalculationGetFloatingRateCalculation(calculation) : null;

            // calculate forecast payment amount for each payment calculation period
            //
            foreach (PaymentCalculationPeriod period in interestRateStream.cashflows.paymentCalculationPeriod)
            {
                CalculateForecastPaymentAmount(calculation, floatingRateCalculation, period, forecastCurve, discountCurve, valuationDate);
            }
            //  principle exchanges
            //
            if (interestRateStream.cashflows.principalExchange != null)
            {
                foreach (PrincipalExchange principalExchange in interestRateStream.cashflows.principalExchange)
                {
                    CalculateForecastPaymentAmount(principalExchange, discountCurve, valuationDate);
                }
            }
        }
        public static ValuationReport Generate(string valuationId, string baseParty, Fra fra, Market market, AssetValuation assetValuation)
        {
            var valuationReport = new ValuationReport
            {
                header = new NotificationMessageHeader
                {
                    messageId = new MessageId
                    {
                        Value
                            =
                                valuationId
                    }
                },
                market = market
            };
            //  Associate id with the valuation
            //
            var tradeValuationItem = new TradeValuationItem();

            valuationReport.tradeValuationItem = new[] { tradeValuationItem };
            var trade = new Trade();

            XsdClassesFieldResolver.TradeSetFra(trade, fra);
            tradeValuationItem.Items        = new object[] { trade };
            tradeValuationItem.valuationSet = new ValuationSet
            {
                baseParty      = PartyReferenceFactory.Create(baseParty),
                assetValuation = new[] { assetValuation }
            };
            return(valuationReport);
        }
Exemplo n.º 4
0
        private static void UpdateCashflowsWithDetailedCashflows(Cashflows cashflows, IEnumerable <DetailedCashflowRangeItem> listDetailedCashflows /*, bool fixedLeg*/)
        {
            var paymentCalculationPeriods = new List <PaymentCalculationPeriod>();

            foreach (DetailedCashflowRangeItem detailedCashflowRangeItem in listDetailedCashflows)
            {
                var paymentCalculationPeriod = new PaymentCalculationPeriod();
                var calculationPeriod        = new CalculationPeriod();
                paymentCalculationPeriod.Items = new object[] { calculationPeriod };
                paymentCalculationPeriod.adjustedPaymentDate          = detailedCashflowRangeItem.PaymentDate;
                paymentCalculationPeriod.adjustedPaymentDateSpecified = true;
                PaymentCalculationPeriodHelper.SetCalculationPeriodStartDate(paymentCalculationPeriod, detailedCashflowRangeItem.StartDate);
                PaymentCalculationPeriodHelper.SetCalculationPeriodEndDate(paymentCalculationPeriod, detailedCashflowRangeItem.EndDate);
                // Update notional amount
                //
                PaymentCalculationPeriodHelper.SetNotionalAmount(paymentCalculationPeriod, (decimal)detailedCashflowRangeItem.NotionalAmount);
                if (detailedCashflowRangeItem.CouponType == "Fixed")
                {
                    //CalculationPeriod calculationPeriod = PaymentCalculationPeriodHelper.GetCalculationPeriods(paymentCalculationPeriod)[0];

                    //if (XsdClassesFieldResolver.CalculationPeriod_HasFixedRate(calculationPeriod))
                    //{
                    //  Fixed->Fixed
                    //
                    //PaymentCalculationPeriodHelper.SetRate(paymentCalculationPeriod, (decimal)detailedCashflowRangeItem.Rate);

                    XsdClassesFieldResolver.SetCalculationPeriodFixedRate(calculationPeriod, (decimal)detailedCashflowRangeItem.Rate);
                    //}
                    //else if (XsdClassesFieldResolver.CalculationPeriod_HasFloatingRateDefinition(calculationPeriod))
//                    {
//                        //  Float->Fixed
//                        //
//                        PaymentCalculationPeriodHelper.ReplaceFloatingRateWithFixedRate(paymentCalculationPeriod, (decimal)detailedCashflowRangeItem.Rate);
//                    }
//                    else
//                    {
//                        throw new NotImplementedException();
//                    }
                }
                else if (detailedCashflowRangeItem.CouponType == "Float")
                {
                    //  Create floating rate definiton...
                    //
                    var floatingRateDefinition = new FloatingRateDefinition();
                    //XsdClassesFieldResolver.CalculationPeriod_SetFloatingRateDefinition(calculationPeriod, floatingRateDefinition);
                    calculationPeriod.Item1 = floatingRateDefinition;
                    // After the spread is reset - we need to update calculated rate.
                    //
                    PaymentCalculationPeriodHelper.SetSpread(paymentCalculationPeriod, (decimal)detailedCashflowRangeItem.Spread);
                }
                else
                {
                    string message = $"Unsupported coupon type '{detailedCashflowRangeItem.CouponType}";
                    throw new System.Exception(message);
                }
                paymentCalculationPeriods.Add(paymentCalculationPeriod);
            }
            cashflows.cashflowsMatchParameters = false;
            cashflows.paymentCalculationPeriod = paymentCalculationPeriods.ToArray();
        }
Exemplo n.º 5
0
        public static void SetFloorRateSchedule(InterestRateStream stream, Schedule floorRateShedule, bool isReceiverBuyer)
        {
            Calculation             calculation             = XsdClassesFieldResolver.CalculationPeriodAmountGetCalculation(stream.calculationPeriodAmount);
            FloatingRateCalculation floatingRateCalculation = XsdClassesFieldResolver.CalculationGetFloatingRateCalculation(calculation);
            var schedule = new StrikeSchedule
            {
                initialValue = floorRateShedule.initialValue,
                step         = floorRateShedule.step
            };

            floatingRateCalculation.floorRateSchedule = new[] { schedule };
            if (isReceiverBuyer)
            {
                floatingRateCalculation.floorRateSchedule[0].buyer = new IdentifiedPayerReceiver {
                    Value = PayerReceiverEnum.Receiver
                };
                floatingRateCalculation.floorRateSchedule[0].seller = new IdentifiedPayerReceiver {
                    Value = PayerReceiverEnum.Payer
                };
            }
            else
            {
                floatingRateCalculation.floorRateSchedule[0].buyer = new IdentifiedPayerReceiver {
                    Value = PayerReceiverEnum.Payer
                };
                floatingRateCalculation.floorRateSchedule[0].seller = new IdentifiedPayerReceiver {
                    Value = PayerReceiverEnum.Receiver
                };
            }
        }
Exemplo n.º 6
0
        internal static void AddOtherPartyPayments(ValuationReport valuationReport, List <OtherPartyPaymentRangeItem> otherPartyPaymentList)
        {
            var otherPartyPayments = new List <Payment>();

            //  other party payments
            //
            if (null != otherPartyPaymentList)
            {
                foreach (OtherPartyPaymentRangeItem item in otherPartyPaymentList)
                {
                    var otherPartyPayment = new Payment
                    {
                        payerPartyReference =
                            PartyReferenceFactory.Create(item.Payer),
                        receiverPartyReference =
                            PartyReferenceFactory.Create(item.Receiver),
                        paymentAmount = MoneyHelper.GetNonNegativeAmount(item.Amount),
                        paymentDate   = AdjustableOrAdjustedDateHelper.CreateAdjustedDate(item.PaymentDate),
                        paymentType   = PaymentTypeHelper.Create(item.PaymentType)
                    };
                    otherPartyPayments.Add(otherPartyPayment);
                }
            }
            TradeValuationItem valuationItem = valuationReport.tradeValuationItem[0];

            Trade[] tradeArray = XsdClassesFieldResolver.TradeValuationItemGetTradeArray(valuationItem);
            Trade   trade      = tradeArray[0];

            trade.otherPartyPayment = otherPartyPayments.ToArray();
        }
Exemplo n.º 7
0
        public string CacheFraTrade(ILogger logger, ICoreCache cache, string fraId, FraInputRange fraInputRange)
        {
            var fra   = ProductFactory.GetFpMLFra(fraInputRange);
            var trade = new Trade();

            XsdClassesFieldResolver.TradeSetFra(trade, fra);
            cache.SaveObject(trade, fraId, null);
            return(fraId);
        }
        public static ValuationReport Generate(string valuationId, string baseParty,
                                               string tradeId, DateTime tradeDate,
                                               Swap swap, Market market,
                                               AssetValuation assetValuation)
        {
            var valuationReport = new ValuationReport
            {
                header = new NotificationMessageHeader
                {
                    messageId = new MessageId
                    {
                        Value
                            =
                                valuationId
                    }
                },
                market = market
            };
            //  Associate id with the valuation
            //
            var tradeValuationItem = new TradeValuationItem();

            valuationReport.tradeValuationItem = new[] { tradeValuationItem };

            //Party nabParty = PartyFactory.Create("Party1");
            //Party counterParty = PartyFactory.Create(_counterpartyName);
//
//            valuationReport.party = new Party[] { nabParty, counterParty };

//            PartyOrAccountReference nabPartyReference = PartyOrAccountReferenceFactory.Create(nabParty.id);
//            PartyOrAccountReference counterPartyReference = PartyOrAccountReferenceFactory.Create(counterParty.id);

//            // NAB is the payer of pay paystream and receiver of receive stream
//            //
//            SwapHelper.GetPayerStream(swap).payerPartyReference = nabPartyReference;
//            SwapHelper.GetReceiverStream(swap).receiverPartyReference = nabPartyReference;
//
//            // CounterParty is the receiver of paystream and payer of receivestream
//            //
//            SwapHelper.GetPayStream(swap).receiverPartyReference = counterPartyReference;
//            SwapHelper.GetReceiveStream(swap).payerPartyReference = counterPartyReference;

            var trade = new Trade();
            //  Generate trade header
            //
            TradeHeader tradeHeader = CreateTradeHeader(tradeDate, tradeId);

            trade.tradeHeader = tradeHeader;
            XsdClassesFieldResolver.TradeSetSwap(trade, swap);
            tradeValuationItem.Items        = new object[] { trade };
            tradeValuationItem.valuationSet = new ValuationSet
            {
                baseParty      = PartyReferenceFactory.Create(baseParty),
                assetValuation = new[] { assetValuation }
            };
            return(valuationReport);
        }
Exemplo n.º 9
0
 private static void SetFirstPeriodStartDate(InterestRateStream stream,
                                             AdjustableDate firstPeriodStartDate)
 {
     if (firstPeriodStartDate != null)
     {
         XsdClassesFieldResolver.CalculationPeriodDatesSetFirstPeriodStartDate(
             stream.calculationPeriodDates, firstPeriodStartDate);
     }
 }
Exemplo n.º 10
0
 private static void SetLastRegularPeriodEndDate(InterestRateStream stream,
                                                 DateTime lastRegularPeriodEndDate)
 {
     if (lastRegularPeriodEndDate != new DateTime())
     {
         XsdClassesFieldResolver.CalculationPeriodDatesSetLastRegularPeriodEndDate(
             stream.calculationPeriodDates, lastRegularPeriodEndDate);
     }
 }
Exemplo n.º 11
0
 private static void SetFirstRegularPeriodStartDate(InterestRateStream stream,
                                                    DateTime firstRegularPeriodStartDate)
 {
     if (firstRegularPeriodStartDate != new DateTime())
     {
         XsdClassesFieldResolver.CalculationPeriodDatesSetFirstRegularPeriodStartDate(
             stream.calculationPeriodDates, firstRegularPeriodStartDate);
     }
 }
Exemplo n.º 12
0
        //private static void ProcessStubs(InterestRateStream stream, SwapLegParametersRange_Old swapTermParametersRange, IBusinessCalendar paymentCalendar)
        //{
        //    //bool isFullFirstCoupon = swapTermParametersRange.FirstCouponType == FirstCouponType.Full?true:false;
        //    DateTime adjustedEffectiveDate = AdjustedDateHelper.ToAdjustedDate(paymentCalendar, XsdClassesFieldResolver.CalculationPeriodDates_GetEffectiveDate(stream.calculationPeriodDates));
        //    DateTime adjustedTerminationDate = AdjustedDateHelper.ToAdjustedDate(paymentCalendar, XsdClassesFieldResolver.CalculationPeriodDates_GetTerminationDate(stream.calculationPeriodDates));
        //    StubPeriodTypeEnum? initialStubType = null;
        //    if (!string.IsNullOrEmpty(swapTermParametersRange.InitialStubType))
        //    {
        //        initialStubType = EnumHelper.Parse<StubPeriodTypeEnum>(swapTermParametersRange.InitialStubType);
        //    }
        //    StubPeriodTypeEnum? finalStubType = null;
        //    if (!string.IsNullOrEmpty(swapTermParametersRange.FinalStubType))
        //    {
        //        finalStubType = EnumHelper.Parse<StubPeriodTypeEnum>(swapTermParametersRange.FinalStubType);
        //    }
        //    //Only calculate a stub if required i.e.
        //    //If a FirsteRegularPeriod is specified -> Roll forward
        //    //If a lastRegularePeriod is specified --> Roll Backwards
        //    //If intialstub is not null
        //    //if finalStubType is not null
        //    //Otherwise, check if the maturity - effective date is modulo the frequency.
        //    //If yes, there is no stub.
        //    var periods = CalculationPeriodGenerator.GenerateAdjustedCalculationPeriods(adjustedEffectiveDate,
        //                                                                                adjustedTerminationDate,
        //                                                                                swapTermParametersRange.FirstRegularPeriodStartDate,
        //                                                                                stream.calculationPeriodDates.calculationPeriodFrequency,
        //                                                                                stream.calculationPeriodDates.calculationPeriodDatesAdjustments,
        //                                                                                initialStubType,
        //                                                                                finalStubType,
        //                                                                                paymentCalendar);
        //    //var periods = CalculationPeriodGenerator.GenerateAdjustedCalculationPeriods(adjustedEffectiveDate,
        //    //                                                                            adjustedTerminationDate,
        //    //                                                                            stream.calculationPeriodDates.firstRegularPeriodStartDate,
        //    //                                                                            stream.calculationPeriodDates.lastRegularPeriodEndDate,
        //    //                                                                            stream.calculationPeriodDates.calculationPeriodFrequency,
        //    //                                                                            stream.calculationPeriodDates.calculationPeriodDatesAdjustments,
        //    //                                                                            paymentCalendar);
        //    if (!stream.calculationPeriodDates.firstRegularPeriodStartDateSpecified && periods.HasInitialStub)
        //    {
        //        stream.calculationPeriodDates.firstRegularPeriodStartDate = periods.FirstRegularPeriodUnadjustedStartDate;
        //        stream.calculationPeriodDates.firstRegularPeriodStartDateSpecified = true;
        //    }
        //    if (!stream.calculationPeriodDates.lastRegularPeriodEndDateSpecified && periods.HasFinalStub)
        //    {
        //        stream.calculationPeriodDates.lastRegularPeriodEndDate = periods.LastRegularPeriodUnadjustedEndDate;
        //        stream.calculationPeriodDates.lastRegularPeriodEndDateSpecified = true;
        //    }
        //}

        private static void SetNotional(Calculation calculation,
                                        decimal amount,
                                        string currencyAsString)
        {
            Money    notionalAsMoney  = MoneyHelper.GetAmount(amount, currencyAsString);
            Notional notionalSchedule = NotionalFactory.Create(notionalAsMoney);

            XsdClassesFieldResolver.CalculationSetNotionalSchedule(calculation, notionalSchedule);
        }
Exemplo n.º 13
0
        //public static void SetNotionalSchedule(InterestRateStream stream, AmountSchedule amountSchedule)
        //{
        //    Calculation calculation = XsdClassesFieldResolver.CalculationPeriodAmount_GetCalculation(stream.calculationPeriodAmount);
        //    var notional = new Notional { notionalStepSchedule = amountSchedule };
        //    XsdClassesFieldResolver.Calculation_SetNotionalSchedule(calculation, notional);
        //}
        public static void SetNotionalSchedule(InterestRateStream stream, NonNegativeAmountSchedule amountSchedule)
        {
            Calculation calculation = XsdClassesFieldResolver.CalculationPeriodAmountGetCalculation(stream.calculationPeriodAmount);
            var         notional    = new Notional {
                notionalStepSchedule = amountSchedule
            };

            XsdClassesFieldResolver.CalculationSetNotionalSchedule(calculation, notional);
        }
        private static void UpdateStubCalculationPeriodData(InterestRateStream interestRateStream, CalculationPeriod stubCalculationPeriod, StubValue stubValue, Notional notinalSchedule)
        {
            StubCalculationPeriodAmountHelper.UpdateStubCalculationPeriod(interestRateStream, stubCalculationPeriod, stubValue);
            decimal notional = NotionalHelper.GetNotionalValue(notinalSchedule, stubCalculationPeriod.adjustedStartDate);

            // Notinal amount
            //
            XsdClassesFieldResolver.CalculationPeriodSetNotionalAmount(stubCalculationPeriod, notional);
        }
Exemplo n.º 15
0
        public static void SetSpreadSchedule(InterestRateStream stream, Schedule spreadShedule)
        {
            Calculation             calculation             = XsdClassesFieldResolver.CalculationPeriodAmountGetCalculation(stream.calculationPeriodAmount);
            FloatingRateCalculation floatingRateCalculation = XsdClassesFieldResolver.CalculationGetFloatingRateCalculation(calculation);
            var schedule = new SpreadSchedule {
                initialValue = spreadShedule.initialValue, step = spreadShedule.step
            };

            floatingRateCalculation.spreadSchedule = new[] { schedule };
        }
Exemplo n.º 16
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public List <string> GetRequiredCurrencies()
        {
            var result = new List <string>();
            var item   = XsdClassesFieldResolver.CalculationGetNotionalSchedule((Calculation)calculationPeriodAmount.Item);

            if (item?.notionalStepSchedule?.currency != null)
            {
                result.Add(item.notionalStepSchedule.currency.Value);
            }
            return(result);
        }
Exemplo n.º 17
0
        ///<summary>
        /// Gets all the Forecast curve name.
        ///</summary>
        ///<returns></returns>
        public static string GetRateVolatilityMatrixName(Swap swap)
        {
            AdjustableDate adjustableEffectiveDate   = XsdClassesFieldResolver.CalculationPeriodDatesGetEffectiveDate(swap.swapStream[0].calculationPeriodDates);
            AdjustableDate adjustableTerminationDate = XsdClassesFieldResolver.CalculationPeriodDatesGetTerminationDate(swap.swapStream[0].calculationPeriodDates);
            var            years       = adjustableTerminationDate.unadjustedDate.Value.Year - adjustableEffectiveDate.unadjustedDate.Value.Year;
            var            calculation = (Calculation)swap.swapStream[0].calculationPeriodAmount.Item;
            var            notional    = XsdClassesFieldResolver.CalculationGetNotionalSchedule(calculation);
            var            currency    = notional.notionalStepSchedule.currency.Value;

            return(PricingStructureTypeEnum.RateVolatilityMatrix + "." + currency + "-IRSwap-" + years + "Y");
        }
Exemplo n.º 18
0
        public static Trade CreateFraTrade(FraInputRange2 fraInputRange)
        {
            var trade = new Trade();
            var fra   = new Fra
            {
                adjustedEffectiveDate =
                    DateTypesHelper.ToRequiredIdentifierDate(fraInputRange.AdjustedEffectiveDate),
                adjustedTerminationDate          = fraInputRange.AdjustedTerminationDate,
                adjustedTerminationDateSpecified = true,
                paymentDate =
                    DateTypesHelper.ToAdjustableDate(fraInputRange.UnadjustedPaymentDate,
                                                     fraInputRange.PaymentDateBusinessDayConvention,
                                                     fraInputRange.PaymentDateBusinessCenters),
                Items = new object[] { new ProductType {
                                           Value = ProductTypeSimpleEnum.FRA.ToString()
                                       } },
                ItemsElementName = new[] { ItemsChoiceType2.productType }
            };

            if ("resetDate" != fraInputRange.FixingDayOffsetDateRelativeTo)
            {
                throw new ArgumentException("The fixing date must be specified as 'resetDate'-relative!", nameof(fraInputRange));
            }
            var fixingDayType = EnumHelper.Parse <DayTypeEnum>(fraInputRange.FixingDayOffsetDayType);

            fra.fixingDateOffset = RelativeDateOffsetHelper.Create(fraInputRange.FixingDayOffsetPeriod, fixingDayType,
                                                                   fraInputRange.FixingDayOffsetBusinessDayConvention,
                                                                   fraInputRange.FixingDayOffsetBusinessCenters,
                                                                   fraInputRange.FixingDayOffsetDateRelativeTo);
            fra.dayCountFraction = DayCountFractionHelper.Parse(fraInputRange.DayCountFraction);
            IDayCounter dayCounter = DayCounterHelper.Parse(fra.dayCountFraction.Value);

            fra.calculationPeriodNumberOfDays = dayCounter.DayCount(fra.adjustedEffectiveDate.Value, fra.adjustedTerminationDate).ToString(CultureInfo.InvariantCulture);
            fra.notional                = MoneyHelper.GetAmount(fraInputRange.NotionalAmount, fraInputRange.NotionalCurrency);
            fra.fixedRate               = (decimal)fraInputRange.FixedRate;
            fra.fixedRateSpecified      = true;
            fra.floatingRateIndex       = FloatingRateIndexHelper.Parse(fraInputRange.FloatingRateIndex);
            fra.indexTenor              = new[] { PeriodHelper.Parse(fraInputRange.IndexTenor) };
            fra.fraDiscounting          = fraInputRange.FraDiscounting;
            fra.fraDiscountingSpecified = true;
            PartyReference party1 = PartyReferenceFactory.Create("party1");
            PartyReference party2 = PartyReferenceFactory.Create("party2");

            fra.sellerPartyReference = party1;
            fra.buyerPartyReference  = party2;
            if (bool.Parse(fraInputRange.IsParty1Buyer))
            {
                fra.sellerPartyReference = party2;
                fra.buyerPartyReference  = party1;
            }
            XsdClassesFieldResolver.TradeSetFra(trade, fra);
            trade.id = fraInputRange.TradeId;
            return(trade);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CommoditySpreadCurve2"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        /// <param name="nameSpace">The client namespace</param>
        /// <param name="referenceCurveData">The market data. This must contain both the underlying base curve and the spread curve.
        /// Otherwise the RateBasisInterpolator can not instantiate.</param>
        /// <param name="spreadCurveData">The spread Curve Data</param>
        /// <param name="rollCalendar">The rollCalendar.</param>
        public CommoditySpreadCurve2(ILogger logger, ICoreCache cache, String nameSpace,
                                     Triplet <PricingStructure, PricingStructureValuation, NamedValueSet> referenceCurveData,
                                     Triplet <PricingStructure, PricingStructureValuation, NamedValueSet> spreadCurveData, IBusinessCalendar rollCalendar)
            : base(spreadCurveData.Third, GenerateHolder(logger, cache, nameSpace, spreadCurveData.Third))
        {
            PricingStructureData = new PricingStructureData(CurveType.Child, AssetClass.Rates, spreadCurveData.Third);
            //Set the identifier.
            var nvs = spreadCurveData.Third;
            var pricingStructureId = GetCommodityCurveId();
            var refCurveId         = PropertyHelper.ExtractReferenceCurveUniqueId(nvs);

            ReferenceCurveId = refCurveId != null ? new Identifier(refCurveId) : ReferenceCurveId = null;
            if (pricingStructureId.PricingStructureType != PricingStructureTypeEnum.CommoditySpreadCurve)
            {
                return;
            }
            //Set the reference curve
            var baseCurveFpml  = new Pair <PricingStructure, PricingStructureValuation>(referenceCurveData.First, referenceCurveData.Second);
            var baseCurveProps = referenceCurveData.Third;

            BaseCurve = (ICommodityCurve)PricingStructureFactory.Create(logger, cache, nameSpace, rollCalendar, rollCalendar, baseCurveFpml, baseCurveProps);
            //Get the spread Data
            var spreadCurveFpml = new Pair <PricingStructure, PricingStructureValuation>(spreadCurveData.First, spreadCurveData.Second);
            //Override properties.
            //var optimize = PropertyHelper.ExtractOptimizeBuildFlag(properties);
            var bootstrap    = PropertyHelper.ExtractBootStrapOverrideFlag(nvs);
            var tempFpml     = (FxCurveValuation)spreadCurveFpml.Second;
            var spreadAssets = tempFpml.spotRate;
            //This is to catch it when there are no discount factor points.
            var discountsAbsent = tempFpml.fxForwardCurve == null ||
                                  tempFpml.fxForwardCurve.point == null ||
                                  tempFpml.fxForwardCurve.point.Length == 0;

            if (bootstrap || discountsAbsent)
            {
                //There must be a valid quotedassetset in order to bootstrap.
                if (!XsdClassesFieldResolver.QuotedAssetSetIsValid(spreadAssets))
                {
                    return;
                }
                PriceableCommoditySpreadAssets =
                    PriceableAssetFactory.CreatePriceableCommoditySpreadAssets(logger, cache, nameSpace, pricingStructureId.BaseDate, spreadAssets, rollCalendar);
                Build(logger, cache, nameSpace, rollCalendar, rollCalendar);
            }
            else
            {
                // the discount curve is already built, so don't rebuild
                PriceableCommoditySpreadAssets = PriceableAssetFactory.CreatePriceableCommoditySpreadAssets(logger, cache, nameSpace, pricingStructureId.BaseDate, spreadAssets, rollCalendar);
                //Order the assets.
                PriceableCommoditySpreadAssets = PriceableCommoditySpreadAssets.OrderBy(a => a.GetRiskMaturityDate()).ToList();
                CreatePricingStructure(pricingStructureId, tempFpml.fxForwardCurve, PriceableAssetFactory.Parse(PriceableCommoditySpreadAssets));
                //SetInterpolator(BaseCurve, pricingStructureId.PricingStructureType);
            }
        }
Exemplo n.º 20
0
        private static void SetEffectiveAndTerminationDates(InterestRateStream stream,
                                                            DateTime rawEffectiveDate,
                                                            DateTime rawTerminationDate,
                                                            string terminationDateBusinessDayAdjustements,
                                                            string terminationDateBusinessDayCalendar)
        {
            AdjustableDate effectiveDate = DateTypesHelper.ToAdjustableDate(rawEffectiveDate);

            XsdClassesFieldResolver.CalculationPeriodDatesSetEffectiveDate(stream.calculationPeriodDates, effectiveDate);
            AdjustableDate terminationDate = DateTypesHelper.ToAdjustableDate(rawTerminationDate, terminationDateBusinessDayAdjustements, terminationDateBusinessDayCalendar);

            XsdClassesFieldResolver.CalculationPeriodDatesSetTerminationDate(stream.calculationPeriodDates, terminationDate);
        }
Exemplo n.º 21
0
        private static Cashflows GetCashfows(
            InterestRateStream interestRateStream, CalculationPeriodsPrincipalExchangesAndStubs calculationPeriodsPrincipalExchangesAndStubs,
            IBusinessCalendar paymentCalendar)
        {
            // Assign notionals, rates, cap/floor rate, etc
            //
            StreamCashflowsGenerator.UpdateCalculationPeriodsData(interestRateStream, calculationPeriodsPrincipalExchangesAndStubs);
            List <PaymentCalculationPeriod> paymentCalculationPeriods = StreamCashflowsGenerator.GetPaymentCalculationPeriods(interestRateStream, calculationPeriodsPrincipalExchangesAndStubs, paymentCalendar);
            Calculation calculation = XsdClassesFieldResolver.CalculationPeriodAmountGetCalculation(interestRateStream.calculationPeriodAmount);

            UpdateNumberOfDaysAndYearFraction(paymentCalculationPeriods, calculation);
            return(CashflowsFactory.Create(paymentCalculationPeriods, calculationPeriodsPrincipalExchangesAndStubs.GetAllPrincipalExchanges(), true));//TODO THe cashflowsmatch paraqmeter at the end could be a problem!
        }
Exemplo n.º 22
0
        public string CacheFraTradeWithProperties(ILogger logger, ICoreCache cache, FraInputRange fraInputRange, NamedValueSet properties)
        {
            var fra   = ProductFactory.GetFpMLFra(fraInputRange);
            var trade = new Trade();

            XsdClassesFieldResolver.TradeSetFra(trade, fra);
            //Get the id.
            ProductIdentifier = new FpML.V5r10.Reporting.Identifiers.TradeIdentifier(properties);
            var fraId = ProductIdentifier.UniqueIdentifier;

            //Cache the trade.
            cache.SaveObject(trade, fraId, properties);
            return(fraId);
        }
        private static TradeHeader CreateTradeHeader(DateTime tradeDate, string tradeId)
        {
            var tradeHeader = new TradeHeader
            {
                tradeDate            = IdentifiedDateHelper.Create(TradeProp.TradeDate, tradeDate),
                partyTradeIdentifier = new[] { new PartyTradeIdentifier() }
            };
            var tradeIdAsObject = new TradeId {
                tradeIdScheme = "FpML", Value = tradeId
            };

            XsdClassesFieldResolver.TradeIdentifierSetTradeId(tradeHeader.partyTradeIdentifier[0], tradeIdAsObject);
            return(tradeHeader);
        }
Exemplo n.º 24
0
 private static void UpdateNumberOfDaysAndYearFraction(IEnumerable <PaymentCalculationPeriod> paymentCalculationPeriods, Calculation calculation)
 {
     foreach (PaymentCalculationPeriod pcp in paymentCalculationPeriods)
     {
         //  set the calculationPeriodNumberOfDays and dayCountYearFraction fields
         //
         foreach (CalculationPeriod calculationPeriod in XsdClassesFieldResolver.GetPaymentCalculationPeriodCalculationPeriodArray(pcp))
         {
             IDayCounter dayCounter = DayCounterHelper.Parse(calculation.dayCountFraction.Value);
             calculationPeriod.calculationPeriodNumberOfDays = dayCounter.DayCount(calculationPeriod.adjustedStartDate, calculationPeriod.adjustedEndDate).ToString(CultureInfo.InvariantCulture);
             calculationPeriod.dayCountYearFraction          = (decimal)dayCounter.YearFraction(calculationPeriod.adjustedStartDate, calculationPeriod.adjustedEndDate);
             calculationPeriod.dayCountYearFractionSpecified = true;
         }
     }
 }
Exemplo n.º 25
0
        private static string GetCouponType(PaymentCalculationPeriod pcalculationPeriod)
        {
            CalculationPeriod      calculationPeriod      = PaymentCalculationPeriodHelper.GetCalculationPeriods(pcalculationPeriod)[0];
            FloatingRateDefinition floatingRateDefinition = XsdClassesFieldResolver.CalculationPeriodGetFloatingRateDefinition(calculationPeriod);

            //  If has a Cap rate, finalRate = MAX(0, FinalRate - CapRate)
            //
            if (null != floatingRateDefinition.capRate)
            {
                return("Cap");
            }
            //  If has a Floor rate, finalRate = MAX(0, FloorRate - FinalRate)
            //
            if (null != floatingRateDefinition.floorRate)
            {
                return("Floor");
            }
            throw new System.Exception("Invalid coupond type. Only Cap & Floor coupons are expected here.");
        }
Exemplo n.º 26
0
        public static Trade CreateFraTrade(string tradeId, RequiredIdentifierDate adjustedEffectiveDate, DateTime adjustedTerminationDate,
                                           AdjustableDate paymentDate, RelativeDateOffset fixingDayOffset, DayCountFraction dayCountFraction, decimal notionalAmount,
                                           string notionalCurrency, decimal fixedRate, string floatingRateIndex, string indexTenor, FraDiscountingEnum fraDiscounting)
        {
            var trade = new Trade();
            var fra   = new Fra
            {
                adjustedEffectiveDate            = adjustedEffectiveDate,
                adjustedTerminationDate          = adjustedTerminationDate,
                adjustedTerminationDateSpecified = true,
                paymentDate = paymentDate,
                Items       = new object[] { new ProductType {
                                                 Value = ProductTypeSimpleEnum.FRA.ToString()
                                             } },
                ItemsElementName = new[] { ItemsChoiceType2.productType }
            };

            if ("resetDate" != fixingDayOffset.dateRelativeTo.href)
            {
                throw new ArgumentException("The fixing date must be specified as 'resetDate'-relative!", nameof(fixingDayOffset));
            }
            fra.fixingDateOffset = fixingDayOffset;
            fra.dayCountFraction = dayCountFraction;
            IDayCounter dayCounter = DayCounterHelper.Parse(fra.dayCountFraction.Value);

            fra.calculationPeriodNumberOfDays = dayCounter.DayCount(fra.adjustedEffectiveDate.Value, fra.adjustedTerminationDate).ToString(CultureInfo.InvariantCulture);
            fra.notional                = MoneyHelper.GetAmount(notionalAmount, notionalCurrency);
            fra.fixedRate               = fixedRate;
            fra.fixedRateSpecified      = true;
            fra.floatingRateIndex       = FloatingRateIndexHelper.Parse(floatingRateIndex);
            fra.indexTenor              = new[] { PeriodHelper.Parse(indexTenor) };
            fra.fraDiscounting          = fraDiscounting;
            fra.fraDiscountingSpecified = true;
            PartyReference party1 = PartyReferenceFactory.Create("party1");
            PartyReference party2 = PartyReferenceFactory.Create("party2");

            fra.sellerPartyReference = party2;
            fra.buyerPartyReference  = party1;
            XsdClassesFieldResolver.TradeSetFra(trade, fra);
            trade.id = tradeId;
            return(trade);
        }
Exemplo n.º 27
0
        public static Trade CreateSwaptionTrade(SwaptionParametersRange swaptionParametersRange, IBusinessCalendar paymentCalendar, Swap underlyingSwap)
        {
            var                      premium        = MoneyHelper.GetNonNegativeAmount(swaptionParametersRange.Premium, swaptionParametersRange.PremiumCurrency);
            AdjustableDate           expirationDate = DateTypesHelper.ToAdjustableDate(swaptionParametersRange.ExpirationDate, swaptionParametersRange.ExpirationDateBusinessDayAdjustments, swaptionParametersRange.ExpirationDateCalendar);
            AdjustableOrAdjustedDate paymentDate    = DateTypesHelper.ToAdjustableOrAdjustedDate(swaptionParametersRange.PaymentDate, swaptionParametersRange.PaymentDateBusinessDayAdjustments, swaptionParametersRange.PaymentDateCalendar);
            TimeSpan                 earliestExerciseTimeAsTimeSpan = TimeSpan.FromDays(swaptionParametersRange.EarliestExerciseTime);
            DateTime                 earliestExerciseTime           = DateTime.MinValue.Add(earliestExerciseTimeAsTimeSpan);
            TimeSpan                 expirationTimeAsTimeSpan       = TimeSpan.FromDays(swaptionParametersRange.ExpirationTime);
            DateTime                 expirationTime = DateTime.MinValue.Add(expirationTimeAsTimeSpan);
            var                      swaption       = SwaptionFactory.Create(underlyingSwap, premium, swaptionParametersRange.PremiumPayer, swaptionParametersRange.PremiumReceiver,
                                                                             paymentDate, expirationDate,
                                                                             earliestExerciseTime, expirationTime, swaptionParametersRange.AutomaticExcercise);

            swaption.Items = new object[] { new ProductType {
                                                Value = ProductTypeSimpleEnum.InterestRateSwaption.ToString()
                                            } };
            swaption.ItemsElementName = new[] { ItemsChoiceType2.productType };
            var trade = new Trade();

            XsdClassesFieldResolver.TradeSetSwaption(trade, swaption);
            return(trade);
        }
Exemplo n.º 28
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="leg1Parameters"></param>
        /// <param name="leg1PaymentCalendar"> </param>
        /// <param name="capStrikeSchedule"></param>
        /// <param name="floorStrikeSchedule"> </param>
        /// <param name="spreadSchedule"></param>
        /// <param name="notionalSchedule"></param>
        /// <param name="leg1FixingCalendar"> </param>
        /// <returns></returns>
        public static Trade CreateTrade(CapFloorLegParametersRange leg1Parameters,
                                        IBusinessCalendar leg1FixingCalendar,
                                        IBusinessCalendar leg1PaymentCalendar,
                                        Schedule capStrikeSchedule,
                                        Schedule floorStrikeSchedule,
                                        Schedule spreadSchedule,
                                        NonNegativeAmountSchedule notionalSchedule)
        {
            var stream1 = GetCashflowsSchedule(leg1FixingCalendar, leg1PaymentCalendar, leg1Parameters);

            if (null != capStrikeSchedule && null != floorStrikeSchedule)
            {
                InterestRateStreamParametricDefinitionGenerator.SetCapRateSchedule(stream1, capStrikeSchedule, true);
                InterestRateStreamParametricDefinitionGenerator.SetFloorRateSchedule(stream1, floorStrikeSchedule, false);
            }
            if (null != capStrikeSchedule && null == floorStrikeSchedule)
            {
                InterestRateStreamParametricDefinitionGenerator.SetCapRateSchedule(stream1, capStrikeSchedule, true);
            }
            if (null == capStrikeSchedule && null != floorStrikeSchedule)
            {
                InterestRateStreamParametricDefinitionGenerator.SetFloorRateSchedule(stream1, floorStrikeSchedule, true);
            }
            if (null != spreadSchedule) //for float legs only
            {
                InterestRateStreamParametricDefinitionGenerator.SetSpreadSchedule(stream1, spreadSchedule);
            }
            if (null != notionalSchedule)
            {
                //  Set notional schedule
                //
                InterestRateStreamParametricDefinitionGenerator.SetNotionalSchedule(stream1, notionalSchedule);
            }
            var capFloor = CapFloorFactory.Create(stream1);
            var trade    = new Trade();

            XsdClassesFieldResolver.TradeSetCapFloor(trade, capFloor);
            return(trade);
        }
        public static ValuationReport Generate(string valuationId, string baseParty,
                                               string tradeId, DateTime tradeDate,
                                               Swaption swaption, Market market, AssetValuation assetValuation)
        {
            var valuationReport = new ValuationReport
            {
                header = new NotificationMessageHeader
                {
                    messageId = new MessageId
                    {
                        Value
                            =
                                valuationId
                    }
                },
                market = market
            };
            //  Associate id with the valuation
            //
            var tradeValuationItem = new TradeValuationItem();

            valuationReport.tradeValuationItem = new[] { tradeValuationItem };
            //  Generate trade header
            //
            var         trade       = new Trade();
            TradeHeader tradeHeader = CreateTradeHeader(tradeDate, tradeId);

            trade.tradeHeader = tradeHeader;
            XsdClassesFieldResolver.TradeSetSwaption(trade, swaption);
            tradeValuationItem.Items        = new object[] { trade };
            tradeValuationItem.valuationSet = new ValuationSet
            {
                baseParty      = PartyReferenceFactory.Create(baseParty),
                assetValuation = new[] { assetValuation }
            };
            return(valuationReport);
        }
Exemplo n.º 30
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public List <DateTime> GetListTermDates()
 {
     return(point.Select(eachPoint => XsdClassesFieldResolver.TimeDimensionGetDate(eachPoint.term)).ToList());
 }