private static void LoadHolidays(ILogger logger, ICoreCache client, Assembly assembly)
        {
            const string FileName    = "Holidays.xml";
            string       holidaysXml = ResourceHelper.GetResourceWithPartialName(assembly, FileName);
            // load daterules from file
            LocationCalendarYears calendarYears = XmlSerializerHelper.DeserializeFromString <LocationCalendarYears>(holidaysXml);

            foreach (LocationCalendarYear locationCalendarYear in calendarYears.LocationCalendarYear)
            {
                string        name;
                NamedValueSet itemProps = CreateProperties(locationCalendarYear, out name);
                client.SaveObject <LocationCalendarYear>(locationCalendarYear, name, itemProps, TimeSpan.MaxValue);
            }
            logger.LogDebug("Loaded holidays.");
        }
Exemple #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CapVolatilityCurve"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        /// <param name="nameSpace">The nameSpace</param>
        /// <param name="curveIdentifier">The curveIdentifier.</param>
        protected CapVolatilityCurve(ILogger logger, ICoreCache cache, String nameSpace, PricingStructureIdentifier curveIdentifier)
            : base(logger, cache, nameSpace, curveIdentifier)
        {
            BootstrapperName            = "CapFloorBootstrapper";
            UnderlyingInterpolatedCurve = "CapVolatilityCurve";
            var properties = curveIdentifier.GetProperties();

            PricingStructureData = new PricingStructureData(CurveType.Parent, AssetClass.Rates, properties);
            Tolerance            = PropertyHelper.ExtractDoubleProperty("Tolerance", properties) ?? GetDefaultTolerance(Holder);
            var compoundingFrequency = properties.GetString("CompoundingFrequency", null);

            CompoundingFrequency = compoundingFrequency != null
                                       ? EnumHelper.Parse <CompoundingFrequencyEnum>(compoundingFrequency)
                                       : GetDefaultCompounding(Holder);
        }
Exemple #3
0
        /// <summary>
        /// Derives the adjusted date if not already provided.
        /// </summary>
        /// <param name="baseDate">The base date is settlement is relative.</param>
        /// <param name="adjustableOrAdjustedDate">this may contain the adjustedDate, an unadjustedDate and business Centre</param>
        /// <param name="cache">THe cache if the business calendar has not already been calculated.</param>
        /// <param name="nameSpace">The client nameSpace</param>
        /// <param name="businessCalendar">THe business calendar must be provided, no namespace is required and can be null</param>
        /// <returns></returns>
        public static DateTime?GetAdjustedDate(ICoreCache cache, string nameSpace, IBusinessCalendar businessCalendar,
                                               DateTime?baseDate, AdjustableOrRelativeDate adjustableOrAdjustedDate)
        {
            if (adjustableOrAdjustedDate.Item is AdjustableDate date)
            {
                return(GetAdjustedDate(cache, nameSpace, businessCalendar, date));
            }

            if (adjustableOrAdjustedDate.Item is RelativeDateOffset relativeDate && baseDate != null)
            {
                return(GetAdjustedDate(cache, nameSpace, businessCalendar, baseDate,
                                       relativeDate));
            }
            return(null);
        }
Exemple #4
0
        private void AddCashFlows(ILogger logger, ICoreCache cache,
                                  IBusinessCalendar fixingCalendar,
                                  IBusinessCalendar paymentCalendar,
                                  Fra fraFpML, bool isBuyer, String nameSpace)
        {
            EffectiveDate   = fraFpML.adjustedEffectiveDate.Value;
            TerminationDate = fraFpML.adjustedTerminationDate;
            if (paymentCalendar == null)
            {
                paymentCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, fraFpML.paymentDate.dateAdjustments.businessCenters, nameSpace);
            }
            if (fixingCalendar == null)
            {
                fixingCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, fraFpML.fixingDateOffset.businessCenters, nameSpace);
            }
            DateTime unadjustedPaymentDate = fraFpML.paymentDate.unadjustedDate.Value;
            var      notional = MoneyHelper.GetAmount(fraFpML.notional.amount, fraFpML.notional.currency);

            PaymentDate = paymentCalendar.Roll(unadjustedPaymentDate, BusinessDayConventionHelper.Parse(fraFpML.paymentDate.dateAdjustments.businessDayConvention.ToString()));
            DateTime adjustedFixingDate = GetResetDate(logger, cache, fixingCalendar, fraFpML, nameSpace);
            var      interval           = fraFpML.indexTenor[0];
            var      floatingInterest   = new PriceableFloatingRateCoupon(fraFpML.id + "FloatingCoupon_1"
                                                                          , isBuyer
                                                                          , EffectiveDate
                                                                          , TerminationDate
                                                                          , adjustedFixingDate
                                                                          , fraFpML.dayCountFraction
                                                                          , 0.0m
                                                                          , FixedRate
                                                                          , null
                                                                          , isBuyer ? MoneyHelper.Neg(notional) : notional
                                                                          , PaymentDate
                                                                          , new ForecastRateIndex {
                floatingRateIndex = fraFpML.floatingRateIndex, indexTenor = interval
            }
                                                                          , null
                                                                          , null
                                                                          , fraFpML.fraDiscounting
                                                                          , paymentCalendar
                                                                          , fixingCalendar)
            {
                ForecastRateInterpolation = ForecastRateInterpolation
            };

            // Combine two cashflows into one leg
            //
            FloatingCoupon = floatingInterest;//fraFpML.fraDiscounting,
        }
Exemple #5
0
        /// <summary>
        /// Create a series of Volatility engines from a raw volatility grid and a DF curve
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        /// <param name="nameSpace">The client namespace</param>
        /// <param name="properties">The properties of the engine, including the reference handle to access this engine collection</param>
        /// <param name="instruments">An array of instrument types.</param>
        /// <param name="rawVolatilityGrid">The raw grid used to build the engines. Assume that all volatility and strike values are 100x true</param>
        /// <returns>The engine handle or an error message</returns>
        public string CreateVolatilityCurve(ILogger logger, ICoreCache cache, string nameSpace, NamedValueSet properties,
                                            String[] instruments, Decimal[,] rawVolatilityGrid)
        {
            var id            = properties.GetString(CurveProp.EngineHandle, null);
            var baseDate      = properties.GetValue <DateTime>(CurveProp.BaseDate, true);
            var valuationDate = properties.GetValue(CurveProp.ValuationDate, DateTime.MinValue);

            if (valuationDate == DateTime.MinValue)
            {
                properties.Set(CurveProp.ValuationDate, baseDate);
            }
            var strikeQuoteUnits = properties.GetString(CurveProp.StrikeQuoteUnits, null);

            if (strikeQuoteUnits == null)
            {
                properties.Set(CurveProp.StrikeQuoteUnits, StrikeQuoteUnitsEnum.ATMFlatMoneyness.ToString());
            }
            var measureType = properties.GetString(CurveProp.MeasureType, null);

            if (measureType == null)
            {
                properties.Set(CurveProp.MeasureType, MeasureTypesEnum.Volatility.ToString());
            }
            var quoteUnits = properties.GetString(CurveProp.QuoteUnits, null);

            if (quoteUnits == null)
            {
                properties.Set(CurveProp.QuoteUnits, QuoteUnitsEnum.LogNormalVolatility.ToString());
            }
            var algorithm = properties.GetString(CurveProp.Algorithm, null);

            if (algorithm == null)
            {
                properties.Set(CurveProp.Algorithm, "Default");
            }
            var volatilities = GenerateVolatilityMatrix(instruments, 0, rawVolatilityGrid);

            // Create the engines and either add to, or overwrite the existing, collection
            if (_volCurveEngines.ContainsKey(id))
            {
                _volCurveEngines[id] = VolatilityCurveCreate(logger, cache, nameSpace, properties, instruments, volatilities);
            }
            else
            {
                _volCurveEngines.Add(id, VolatilityCurveCreate(logger, cache, nameSpace, properties, instruments, volatilities));
            }
            return(id);
        }
Exemple #6
0
        public static void BuildTrade(ILogger logger, ICoreCache targetClient, Trade tradeVersion, Party[] party)
        {
            var extraProps = new NamedValueSet();
            var party1     = party[0].partyId[0].Value;
            var party2     = party[1].partyId[0].Value;

            extraProps.Set(TradeProp.Party1, party1);
            extraProps.Set(TradeProp.Party2, party2);
            //extraProps.Set(TradeProp.CounterPartyId, party2);//Redundant
            //extraProps.Set(TradeProp.OriginatingPartyId, party1);//Redundant
            extraProps.Set(TradeProp.TradeDate, tradeVersion.tradeHeader.tradeDate.Value);
            extraProps.Set(TradeProp.TradingBookName, "Test");
            TradeId tradeId;
            var     tempId = tradeVersion.tradeHeader.partyTradeIdentifier[0].Items[0];

            if (tempId as VersionedTradeId == null)
            {
                tradeId = (TradeId)tradeVersion.tradeHeader.partyTradeIdentifier[0].Items[0];
            }
            else
            {
                var id = (VersionedTradeId)tradeVersion.tradeHeader.partyTradeIdentifier[0].Items[0];
                tradeId = id.tradeId;
            }
            //tradeId = (TradeId)tradeVersion.tradeHeader.partyTradeIdentifier[0].Items[0];
            extraProps.Set(TradeProp.TradeState, "Pricing");
            //extraProps.Set("TradeType", "Deposit");
            extraProps.Set(TradeProp.TradeSource, "FPMLSamples");
            extraProps.Set(TradeProp.TradeId, tradeId.Value);
            extraProps.Set(TradeProp.BaseParty, TradeProp.Party1);        //party1
            extraProps.Set(TradeProp.CounterPartyName, TradeProp.Party2); //party2
            extraProps.Set(TradeProp.AsAtDate, DateTime.Today);
            var tradeType  = ProductTypeHelper.TradeTypeHelper(tradeVersion.Item);
            var currencies = tradeVersion.Item.GetRequiredCurrencies().ToArray();
            var curves     = tradeVersion.Item.GetRequiredPricingStructures().ToArray();

            extraProps.Set(TradeProp.RequiredPricingStructures, curves);
            extraProps.Set(TradeProp.RequiredCurrencies, currencies);
            extraProps.Set(TradeProp.TradeType, tradeType.ToString());
            //extraProps.Set(TradeProp.ProductType, tradeType.ToString());
            string idSuffix = String.Format("{0}.{1}",
                                            tradeType,
                                            tradeId.Value);
            ItemInfo itemInfo = MakeTradeProps("Trade", idSuffix, extraProps);

            logger.LogDebug("  {0} ...", idSuffix);
            targetClient.SaveObject(tradeVersion, itemInfo.ItemName, itemInfo.ItemProps, false, TimeSpan.MaxValue);
        }
Exemple #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <param name="swaptionFpML"> </param>
        /// <param name="basePartyReference"></param>
        protected SwaptionPricer(ILogger logger, ICoreCache cache,
                                 String nameSpace, Swaption swaptionFpML, string basePartyReference)
        {
            ProductType = ProductTypeSimpleEnum.InterestRateSwaption;
            if (swaptionFpML == null)
            {
                return;
            }
            BuyerPartyReference  = swaptionFpML.buyerPartyReference.href;
            SellerPartyReference = swaptionFpML.sellerPartyReference.href;
            IsBasePartyBuyer     = basePartyReference == BuyerPartyReference;
            PaymentCurrencies    = new List <string>();
            if (swaptionFpML.Item is EuropeanExercise exercise)
            {
                ExerciseType = ExerciseType.European;
                Exercise     = exercise;
                var exerciseDate = AdjustedDateHelper.ToAdjustedDate(cache, null, exercise.expirationDate, nameSpace);
                ExerciseDates = new[] { exerciseDate };//TODO Only does adjustable date exercise.
            }

            if (swaptionFpML.exerciseProcedure?.Item is AutomaticExercise)
            {
                AutomaticExcercise = true;
            }
            if (swaptionFpML.premium != null)
            {
                PremiumPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, swaptionFpML.premium, null);
                var paymentAmounts = new List <Decimal>();
                var paymentDates   = new List <DateTime>();
                foreach (var premium in PremiumPayments)
                {
                    paymentAmounts.Add(premium.PaymentAmount.amount);
                    paymentDates.Add(premium.PaymentDate);
                    //Add the currencies for the trade pricer.
                    if (!PaymentCurrencies.Contains(premium.PaymentAmount.currency.Value))
                    {
                        PaymentCurrencies.Add(premium.PaymentAmount.currency.Value);
                    }
                }
                PremiumPaymentAmounts = paymentAmounts.ToArray();
                PremiumPaymentDates   = paymentDates.ToArray();
            }

            if (swaptionFpML.Item1 is CashSettlement)
            {
                IsCashSettled = true;//TODO extend to the type of calculation.
            }
        }
Exemple #8
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);
 }
        /// <summary>
        /// Create a surface from an FpML
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <param name="fpmlData"></param>
        /// <param name="properties"></param>
        public ExpiryTermTenorStrikeVolatilityCube(ILogger logger, ICoreCache cache, String nameSpace, Pair <PricingStructure, PricingStructureValuation> fpmlData, NamedValueSet properties)
        {
            var surfaceId = new VolatilitySurfaceIdentifier(properties);

            Algorithm = surfaceId.Algorithm;
            PricingStructureIdentifier = surfaceId;
            var holder = new PricingStructureAlgorithmsHolder(logger, cache, nameSpace, surfaceId.PricingStructureType, surfaceId.Algorithm);

            Algorithm = "Linear"; //Add as a propert in the id.
            var      curveInterpolationMethod = InterpolationMethodHelper.Parse(holder.GetValue("CurveInterpolation"));
            var      data     = (VolatilityMatrix)fpmlData.Second;
            DateTime baseDate = data.baseDate.Value;

            Interpolator = new VolSurfaceInterpolator(data.dataPoints, curveInterpolationMethod, true, baseDate);
            SetFpMLData(fpmlData);
        }
Exemple #10
0
        /// <summary>
        /// Perturbed curve
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        /// <param name="nameSpace">The client namespace</param>
        /// <param name="properties">The properties of the new curve.</param>
        /// <param name="baseCurve">The XCcySpreadCurve that the new curve is based on</param>
        /// <param name="perturbations">The pertubations to the values of the base curve</param>
        /// <param name="fixingCalendar">The fixingCalendar.</param>
        /// <param name="rollCalendar">The rollCalendar.</param>
        public XccySpreadCurve(ILogger logger, ICoreCache cache,
                               String nameSpace, NamedValueSet properties,
                               XccySpreadCurve baseCurve, decimal[] perturbations,
                               IBusinessCalendar fixingCalendar, IBusinessCalendar rollCalendar)
            : base(logger, cache, nameSpace, new RateCurveIdentifier(properties))
        {
            var assetQuote = ((YieldCurveValuation)baseCurve.PricingStructureValuation).inputs.assetQuote;

            string[]  instruments = assetQuote.Where(a => a.definitionRef == null).Select(a => a.objectReference.href).ToArray();
            decimal[] values      = assetQuote.Where(a => a.definitionRef == null).Select(a => a.quote[0].value).ToArray();
            for (int i = 0; i < values.Length; i++)
            {
                values[i] += perturbations[i];
            }
            Initialize(logger, cache, nameSpace, properties, baseCurve.BaseCurve, baseCurve.QuoteCurve, instruments, values, null, fixingCalendar, rollCalendar);
        }
Exemple #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <param name="swaptionFpML"> </param>
        /// <param name="basePartyReference"></param>
        /// <param name="forecastRateInterpolation"></param>
        protected SwaptionPricer(ILogger logger, ICoreCache cache,
                                 String nameSpace, Swaption swaptionFpML, string basePartyReference, Boolean forecastRateInterpolation)
        {
            ProductType = ProductTypeSimpleEnum.InterestRateSwaption;
            if (swaptionFpML == null)
            {
                return;
            }
            BuyerPartyReference  = swaptionFpML.buyerPartyReference.href;
            SellerPartyReference = swaptionFpML.sellerPartyReference.href;
            IsBasePartyBuyer     = basePartyReference == BuyerPartyReference;
            var exercise = swaptionFpML.Item as EuropeanExercise;

            if (exercise != null)
            {
                ExerciseType = ExerciseType.European;
                Exercise     = exercise;
                var exerciseDate = AdjustedDateHelper.ToAdjustedDate(cache, null, exercise.expirationDate, nameSpace);
                ExerciseDates = new[] { exerciseDate };//TODO Only does adjustabledate exercise
            }
            var item = swaptionFpML.exerciseProcedure?.Item as AutomaticExercise;

            if (item != null)
            {
                AutomaticExcercise = true;
            }
            if (swaptionFpML.premium != null)
            {
                PremiumPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, swaptionFpML.premium, null);
            }
            var paymentAmounts = new List <Decimal>();
            var paymentDates   = new List <DateTime>();

            foreach (var premium in PremiumPayments)
            {
                paymentAmounts.Add(premium.PaymentAmount.amount);
                paymentDates.Add(premium.PaymentDate);
            }
            PremiumPaymentAmounts = paymentAmounts.ToArray();
            PremiumPaymentDates   = paymentDates.ToArray();
            var isCashSettled = swaptionFpML.Item1 as CashSettlement;

            if (isCashSettled != null)
            {
                IsCashSettled = true;
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CommodityCurve"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        /// <param name="nameSpace">The client namespace</param>
        /// <param name="fpmlData">The FPML data.</param>
        /// <param name="properties">The properties.</param>
        /// <param name="fixingCalendar">The fixingCalendar.</param>
        /// <param name="rollCalendar">The rollCalendar.</param>
        public CommodityCurve(ILogger logger, ICoreCache cache, string nameSpace,
                              Pair <PricingStructure, PricingStructureValuation> fpmlData, NamedValueSet properties,
                              IBusinessCalendar fixingCalendar, IBusinessCalendar rollCalendar)
            : base(logger, cache, nameSpace, fpmlData, new CommodityCurveIdentifier(properties))
        {
            PricingStructureData = new PricingStructureData(CurveType.Parent, AssetClass.Commodity, properties);
            if (fpmlData == null)
            {
                return;
            }
            FixingCalendar  = fixingCalendar;
            PaymentCalendar = rollCalendar;
            var tempFpML = (FxCurveValuation)fpmlData.Second;

            //  Use default algorithm name
            //
            Algorithm = DefaultAlgorithName;
            var termCurve = SetConfigurationData();

            //SetFpMLData(fpmlData);
            BootstrapperName = Holder.GetValue("Bootstrapper");
            var bootstrap = PropertyHelper.ExtractBootStrapOverrideFlag(properties);
            //  If there's no forward points - do build the curve.
            //
            //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 (cache == null)
            {
                //optimize = true;
                bootstrap = false;
            }
            bool doBuild = (tempFpML.spotRate != null) && discountsAbsent;

            if (bootstrap || doBuild)
            {
                var qas = tempFpML.spotRate;
                PriceableCommodityAssets = PriceableAssetFactory.CreatePriceableCommodityAssets(logger, cache, nameSpace, tempFpML.baseDate.Value, qas, fixingCalendar, rollCalendar);
                var point = CommodityBootstrapper.Bootstrap(PriceableCommodityAssets, tempFpML.baseDate.Value, termCurve.extrapolationPermitted,
                                                            termCurve.interpolationMethod);
                ((FxCurveValuation)fpmlData.Second).fxForwardCurve.point = point;
            }
            SetInterpolator(PricingStructureValuation.baseDate.Value, Holder);
        }
 public void TestSaveLoadPrivateCacheItems()
 {
     using (Reference <ILogger> loggerRef = Reference <ILogger> .Create(new TraceLogger(true)))
         using (CoreServer server = new CoreServer(loggerRef, "UTT", NodeType.Router))
         {
             server.Start();
             using (ICoreClient client = new CoreClientFactory(loggerRef).SetEnv("UTT").Create())
                 using (ICoreCache cacheA = client.CreateCache())
                 {
                     Guid id = cacheA.SavePrivateObject("data", "name1", null);
                     //ICoreItem item = cacheA.LoadPrivateItem<string>("name1");
                     ICoreItem item = cacheA.LoadItem <string>("name1");
                     string    data = (string)item.Data;
                     Assert.AreEqual <string>("data", data);
                 }
         }
 }
        /// <summary>
        /// Tries to get the algorithm.
        /// </summary>
        /// <param name="nameSpace"></param>
        /// <param name="pricingStructureType"></param>
        /// <param name="algorithmName"></param>
        /// <param name="logger"></param>
        /// <param name="cache">The value</param>
        /// <returns>Whether the property existed or not</returns>
        public Algorithm GetAlgorithm(ILogger logger, ICoreCache cache, String nameSpace, PricingStructureTypeEnum pricingStructureType, string algorithmName)
        {
            Algorithm algorithm = null;

            if (cache != null)
            {
                try
                {
                    algorithm = cache.LoadObject <Algorithm>(nameSpace + "." + AlgorithmsProp.GenericName + "." + pricingStructureType + "." + algorithmName);
                }
                catch (Exception ex)
                {
                    logger.Log(ex);
                }
            }
            return(algorithm);
        }
Exemple #15
0
        /// <summary>
        /// Compute a Volatility Smile given an engine, a date and a list of strikes
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        /// <param name="nameSpace">The clients namespace</param>
        /// <param name="engineHandle">The SABR engine to use</param>
        /// <param name="date">The date to compute for</param>
        /// <param name="strikes">The strikes that make up the smile. This can be a single strike (ATM)</param>
        /// <returns></returns>
        public List <Decimal> SABRComputeVolatility(ILogger logger, ICoreCache cache, string nameSpace, string engineHandle, DateTime date, decimal[] strikes)
        {
            SmileCalibrationEngine engine;

            if (_sabrEngines.ContainsKey(engineHandle))
            {
                engine = _sabrEngines[engineHandle];
            }
            else
            {
                throw new ArgumentException("SABR Caplet Smile Calibration engine not found.");
            }
            var strikesList    = new List <decimal>(strikes);
            var computedValues = engine.ComputeVolatilitySmile(logger, cache, nameSpace, date, strikesList);

            return(computedValues);
        }
Exemple #16
0
 /// <summary>
 /// Derives the adjusted date if not already provided.
 /// </summary>
 /// <param name="baseDate">The base date is settlement is relative.</param>
 /// <param name="relativeDateOffset">this may contain the adjustedDate, an unadjustedDate and business Centre</param>
 /// <param name="cache">THe cache if the business calendar has not already been calculated.</param>
 /// <param name="nameSpace">The client nameSpace</param>
 /// <param name="businessCalendar">THe business calendar must be provided, no namespace is required and can be null</param>
 /// <returns></returns>
 public static DateTime?GetAdjustedDate(ICoreCache cache, string nameSpace, IBusinessCalendar businessCalendar,
                                        DateTime?baseDate, RelativeDateOffset relativeDateOffset)
 {
     if (relativeDateOffset.adjustedDate != null)
     {
         return(relativeDateOffset.adjustedDate.Value);
     }
     if (baseDate == null)
     {
         return(null);
     }
     if (businessCalendar == null)
     {
         businessCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, relativeDateOffset.businessCenters, nameSpace);
     }
     return(ToAdjustedDate(businessCalendar, (DateTime)baseDate, relativeDateOffset));
 }
Exemple #17
0
        public ClearedRateCurve(ILogger logger, ICoreCache cache, string nameSpace, NamedValueSet properties,
                                QuotedAssetSet instrumentData, IRateCurve baseDiscountingCurve, IBusinessCalendar fixingCalendar, IBusinessCalendar rollCalendar)
            : base(logger, cache, nameSpace, new RateCurveIdentifier(properties), fixingCalendar, rollCalendar)
        {
            PricingStructureData = new PricingStructureData(CurveType.Child, AssetClass.Rates, properties);
            BaseDiscountingCurve = baseDiscountingCurve;
            var curveId    = GetRateCurveId();
            var termCurve  = SetConfigurationData();
            var indexTenor = curveId.ForecastRateIndex?.indexTenor;

            PriceableClearedRateAssets = PriceableAssetFactory.CreatePriceableClearedRateAssetsWithBasisSwaps(logger, cache, nameSpace, indexTenor, instrumentData, GetRateCurveId().BaseDate, fixingCalendar, rollCalendar);
            termCurve.point            = ClearedRateBootstrapper.Bootstrap(PriceableClearedRateAssets, BaseDiscountingCurve, curveId.BaseDate, termCurve.extrapolationPermitted, termCurve.interpolationMethod, Tolerance);
            CreatePricingStructure(curveId, termCurve, instrumentData);
            // CreatePricingStructure(curveId, termCurve, PriceableAssetFactory.Parse(PriceableClearedRateAssets));
            // Interpolate the DiscountFactor curve based on the respective curve interpolation
            SetInterpolator(termCurve);
        }
        /// <summary>
        /// Create a surface from an FpML
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        /// <param name="nameSpace">The nameSpace</param>
        /// <param name="fpmlData">The data.</param>
        /// <param name="properties">The properties.</param>
        protected ExpiryTermStrikeVolatilitySurface(ILogger logger, ICoreCache cache, String nameSpace, Pair <PricingStructure, PricingStructureValuation> fpmlData, NamedValueSet properties)
        {
            var data = (VolatilityMatrix)fpmlData.Second;

            Algorithm = "Linear";//Add as a property in the id.
            //Creates the property collection. This should be backward compatable with V1.
            var surfaceId = new VolatilitySurfaceIdentifier(properties);

            PricingStructureIdentifier = surfaceId;
            var holder = new PricingStructureAlgorithmsHolder(logger, cache, nameSpace, surfaceId.PricingStructureType, surfaceId.Algorithm);
            var curveInterpolationMethod = InterpolationMethodHelper.Parse(holder.GetValue("CurveInterpolation"));

            Interpolator = new VolSurfaceInterpolator(data.dataPoints, curveInterpolationMethod, true, PricingStructureIdentifier.BaseDate);
            SetFpmlData(fpmlData);
            _matrixIndexHelper = new SortedList <ExpiryTenorStrikeKey, int>(new ExpiryTenorStrikeKey());
            ProcessVolatilityRepresentation();
        }
Exemple #19
0
 protected override void OnFirstCallback()
 {
     // subscribe to import rules
     _ruleCache = IntClient.Target.CreateCache(delegate(CacheChangeData update)
     {
         Interlocked.Increment(ref _dispatchedEventCount);
         MainThreadQueue.Dispatch(update, ProcessRuleUpdate);
     }, null);
     _ruleCache.Subscribe <AlertRule>(
         RuleObject.MakeRuleFilter(
             EnvHelper.EnvName(IntClient.Target.ClientInfo.ConfigEnv),
             IntClient.Target.ClientInfo.HostName,
             AppName,
             IntClient.Target.ClientInfo.UserName));
     // start a 30 second timer to periodically check the rules
     _timer = new Timer(RecvTimerEvent, null, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30));
 }
Exemple #20
0
        /// <summary>
        /// Creates the equity curve.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        /// <param name="nameSpace">THe client namespace</param>
        /// <param name="equityId">THe underlying curve asset.</param>
        /// <param name="fixingCalendar"></param>
        /// <param name="rollCalendar"></param>
        /// <param name="baseDate">The base date.</param>
        /// <param name="fxRates">The spot rate.</param>
        /// <param name="curveId">The curve id.</param>
        /// <param name="termCurve">The bootstrapped term curve.</param>
        /// <returns></returns>
        private static FxCurveValuation CreateEquityCurveValuation(ILogger logger, ICoreCache cache, string nameSpace, EquityCurveIdentifier equityId,
                                                                   IBusinessCalendar fixingCalendar, IBusinessCalendar rollCalendar, DateTime baseDate, FxRateSet fxRates, string curveId,
                                                                   TermCurve termCurve)
        {
            DateTime settlementDate   = GetSettlementDate(logger, cache, nameSpace, equityId, fixingCalendar, rollCalendar, baseDate);
            var      fxCurveValuation = new FxCurveValuation
            {
                baseDate               = IdentifiedDateHelper.Create(baseDate),
                buildDateTime          = baseDate,
                buildDateTimeSpecified = true,
                spotRate               = fxRates,
                id             = curveId,
                fxForwardCurve = termCurve,
                spotDate       = IdentifiedDateHelper.Create("SettlementDate", settlementDate)
            };

            return(fxCurveValuation);
        }
        protected override void OnFirstCallback()
        {
            // subscribe to import rules
            _importRuleSet = IntClient.Target.CreateCache(delegate(CacheChangeData update)
            {
                Interlocked.Increment(ref _updateRequestsDispatched);
                MainThreadQueue.Dispatch(update, ProcessRuleUpdate);
            }, null);
            _importRuleSet.Subscribe <FileImportRule>(
                RuleObject.MakeRuleFilter(
                    EnvHelper.EnvName(IntClient.Target.ClientInfo.ConfigEnv),
                    IntClient.Target.ClientInfo.HostName,
                    AppName,
                    IntClient.Target.ClientInfo.UserName));

            // start a 1 minute timer to periodically check the rules
            _timer = new Timer(RecvTimerEvent, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
        }
Exemple #22
0
        /// <summary>
        /// Converts to an adjustable date type.
        /// </summary>
        /// <param name="adjustableDate"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <returns></returns>
        public static DateTime ToAdjustedDate(ICoreCache cache, AdjustableDate adjustableDate, string nameSpace)
        {
            if (null == adjustableDate)
            {
                throw new ArgumentNullException(nameof(adjustableDate));
            }
            // handle  BusinessDatConventionEnum is NONE as a special case, since there might be no business centers provided.
            //
            if ((null == adjustableDate.dateAdjustments) ||
                (BusinessDayConventionEnum.NONE == adjustableDate.dateAdjustments.businessDayConvention))
            {
                return(adjustableDate.unadjustedDate.Value);
            }
            IBusinessCalendar businessCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, adjustableDate.dateAdjustments.businessCenters, nameSpace);
            DateTime          result           = businessCalendar.Roll(adjustableDate.unadjustedDate.Value, adjustableDate.dateAdjustments.businessDayConvention);

            return(result);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <param name="fixingCalendar"></param>
        /// <param name="paymentCalendar"></param>
        /// <param name="capFloorLeg"></param>
        /// <param name="spreadSchedule"></param>
        /// <param name="capOrFloorSchedule"></param>
        /// <param name="notionalSchedule"></param>
        /// <param name="marketEnvironment"></param>
        /// <param name="valuationDate"></param>
        /// <returns></returns>
        public static CapFloor GenerateDefinitionCashflowsAmounts(ILogger logger,
                                                                  ICoreCache cache, String nameSpace,
                                                                  IBusinessCalendar fixingCalendar,
                                                                  IBusinessCalendar paymentCalendar,
                                                                  CapFloorLegParametersRange capFloorLeg,
                                                                  Schedule spreadSchedule,
                                                                  Schedule capOrFloorSchedule,
                                                                  NonNegativeAmountSchedule notionalSchedule,
                                                                  ISwapLegEnvironment marketEnvironment,
                                                                  DateTime valuationDate)
        {
            CapFloor   capFloor = GenerateDefinitionCashflows(logger, cache, nameSpace, fixingCalendar, paymentCalendar, capFloorLeg, spreadSchedule, capOrFloorSchedule, notionalSchedule);
            IRateCurve payStreamDiscountingCurve = marketEnvironment.GetDiscountRateCurve();
            IRateCurve payStreamForecastCurve    = marketEnvironment.GetForecastRateCurve();

            FixedAndFloatingRateStreamCashflowGenerator.UpdateCashflowsAmounts(capFloor.capFloorStream, payStreamForecastCurve, payStreamDiscountingCurve, valuationDate);
            return(capFloor);
        }
        /// <summary>
        /// Gets the adjusted calculation date schedule.
        /// </summary>
        /// <param name="cache">The cache.</param>
        /// <param name="effectiveDate">The effective date.</param>
        /// <param name="intervalToTerminationDate">The interval to termination date.</param>
        /// <param name="periodInterval">The period interval.</param>
        /// <returns></returns>
        /// <param name="businessDayAdjustments">The necessary date adjustment details.</param>
        /// <param name="nameSpace">The clients namespace</param>
        public List <CalculationPeriod> GetAdjustedCalculationDateSchedule(ICoreCache cache, DateTime effectiveDate,
                                                                           Period intervalToTerminationDate, Period periodInterval,
                                                                           BusinessDayAdjustments businessDayAdjustments, string nameSpace)
        {
            List <CalculationPeriod> adjustedDateScheduleList =
                GetUnadjustedCalculationDateSchedule(effectiveDate, intervalToTerminationDate, periodInterval);

            foreach (CalculationPeriod period in adjustedDateScheduleList)
            {
                period.adjustedStartDateSpecified = true;
                period.adjustedStartDate          =
                    AdjustedDateHelper.ToAdjustedDate(cache, period.unadjustedStartDate, businessDayAdjustments, nameSpace);
                period.adjustedEndDateSpecified = true;
                period.adjustedEndDate          =
                    AdjustedDateHelper.ToAdjustedDate(cache, period.unadjustedEndDate, businessDayAdjustments, nameSpace);
            }
            return(adjustedDateScheduleList);
        }
Exemple #25
0
        private static void UpdateCashflowsWithAmounts(ILogger logger, ICoreCache cache,
                                                       String nameSpace, InterestRateStream stream,
                                                       CapFloorLegParametersRange_Old legParametersRange, ValuationRange valuationRange)
        {
            //  Get a forecast curve
            //
            IRateCurve forecastCurve = null;

            if (!String.IsNullOrEmpty(legParametersRange.ForecastCurve) && legParametersRange.ForecastCurve.ToLower() != "none")
            {
                forecastCurve = CurveLoader.LoadInterestRateCurve(logger, cache, nameSpace, legParametersRange.ForecastCurve);
            }
            //  Get a discount curve
            //
            var discountCurve = CurveLoader.LoadInterestRateCurve(logger, cache, nameSpace, legParametersRange.DiscountCurve);

            FixedAndFloatingRateStreamCashflowGenerator.UpdateCashflowsAmounts(stream, forecastCurve, discountCurve, valuationRange.ValuationDate);
        }
        /// <summary>
        /// Moving to the new algorithm name!
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="targetClient"></param>
        /// <param name="nameSpace"></param>
        public static void LoadPricingStructureAlgorithm(ILogger logger, ICoreCache targetClient, string nameSpace)
        {
            string xml = GetXml("FpML.V5r10.ConfigData.Config.PricingStructureAlgorithms.xml");
            var    pricingStructureTypes = XmlSerializerHelper.DeserializeFromString <PricingStructureTypes>(xml);

            //ItemInfo itemInfo = StandardConfigProps("PricingStructureAlgorithms", null);
            //targetClient.SaveObject<PricingStructureTypes>(pricingStructureTypes, itemInfo.ItemName, itemInfo.ItemProps);
            //logger.LogDebug("Loaded pricing structure types.");
            foreach (var pst in pricingStructureTypes.PricingStructureType)
            {
                foreach (var algo in pst.Algorithms)
                {
                    var itemInfo = StandardConfigProps("Algorithm", pst.id + "." + algo.id, nameSpace);
                    targetClient.SaveObject(algo, itemInfo.ItemName, itemInfo.ItemProps);
                    logger.LogDebug("Loaded Algorithm: {0}", itemInfo.ItemName);
                }
            }
        }
        public List <DetailedCashflowRangeItem> GetDetailedCashflowsWithNotionalSchedule(
            ILogger logger,
            ICoreCache cache,
            String nameSpace,
            IBusinessCalendar fixingCalendar,
            IBusinessCalendar paymentCalendar,
            SwapLegParametersRange_Old legParametersRange,
            List <DateTimeDoubleRangeItem> notionalValueItems,
            ValuationRange valuationRange)
        {
            var tempList = notionalValueItems.Select(item => new Pair <DateTime, decimal>(item.DateTime, Convert.ToDecimal(item.Value))).ToList();
            NonNegativeSchedule       notionalScheduleFpML = NonNegativeScheduleHelper.Create(tempList);
            Currency                  currency             = CurrencyHelper.Parse(legParametersRange.Currency);
            NonNegativeAmountSchedule amountSchedule       = NonNegativeAmountScheduleHelper.Create(notionalScheduleFpML, currency);
            InterestRateStream        interestRateStream   = GetCashflowsScheduleWithNotionalSchedule(fixingCalendar, paymentCalendar, legParametersRange, amountSchedule);

            UpdateCashflowsWithAmounts(logger, cache, nameSpace, interestRateStream, legParametersRange, valuationRange);
            var list = new List <DetailedCashflowRangeItem>();

            //int periodNumber = 1;
            foreach (PaymentCalculationPeriod paymentCalculationPeriod in interestRateStream.cashflows.paymentCalculationPeriod)
            {
                var detailedCashflowRangeItem = new DetailedCashflowRangeItem();
                list.Add(detailedCashflowRangeItem);
                detailedCashflowRangeItem.PaymentDate = paymentCalculationPeriod.adjustedPaymentDate;
                detailedCashflowRangeItem.StartDate   = PaymentCalculationPeriodHelper.GetCalculationPeriodStartDate(paymentCalculationPeriod);
                detailedCashflowRangeItem.EndDate     = PaymentCalculationPeriodHelper.GetCalculationPeriodEndDate(paymentCalculationPeriod);
                //detailedCashflowRangeItem.NumberOfDays = PaymentCalculationPeriodHelper.GetNumberOfDays(paymentCalculationPeriod);
                //detailedCashflowRangeItem.FutureValue = MoneyHelper.ToDouble(paymentCalculationPeriod.forecastPaymentAmount);
                //detailedCashflowRangeItem.PresentValue = MoneyHelper.ToDouble(paymentCalculationPeriod.presentValueAmount);
                //detailedCashflowRangeItem.DiscountFactor = (double)paymentCalculationPeriod.discountFactor;
                detailedCashflowRangeItem.NotionalAmount = (double)PaymentCalculationPeriodHelper.GetNotionalAmount(paymentCalculationPeriod);
                detailedCashflowRangeItem.CouponType     = GetCouponType(paymentCalculationPeriod);
                detailedCashflowRangeItem.Rate           = (double)PaymentCalculationPeriodHelper.GetRate(paymentCalculationPeriod);
                //  If  floating rate - retrieve the spread.
                //
                if (legParametersRange.IsFloatingLegType())
                {
                    detailedCashflowRangeItem.Spread = (double)PaymentCalculationPeriodHelper.GetSpread(paymentCalculationPeriod);
                }
            }

            return(list);
        }
Exemple #28
0
 public static void UpdatePaymentsAmounts(ILogger logger, ICoreCache cache,
                                          String nameSpace, Swap swap,
                                          SwapLegParametersRange leg1Parameters,
                                          SwapLegParametersRange leg2Parameters,
                                          IRateCurve leg1DiscountCurve,
                                          IRateCurve leg2DiscountCurve,
                                          DateTime valuationDate, IBusinessCalendar paymentCalendar)
 {
     foreach (Payment payment in swap.additionalPayment)
     {
         //  choose correct discount curve
         //
         IRateCurve discountCurve;
         if (payment.payerPartyReference.href == leg1Parameters.Payer)
         {
             discountCurve = leg1DiscountCurve;
         }
         else if (payment.payerPartyReference.href == leg2Parameters.Payer)
         {
             discountCurve = leg2DiscountCurve;
         }
         else
         {
             throw new NotImplementedException();
         }
         if (paymentCalendar == null)
         {
             var containsPaymentDateAdjustments = AdjustableOrAdjustedDateHelper.Contains(payment.paymentDate, ItemsChoiceType.dateAdjustments, out var dateAdjustments);
             if (containsPaymentDateAdjustments && dateAdjustments != null)
             {
                 paymentCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, ((BusinessDayAdjustments)dateAdjustments).
                                                                           businessCenters, nameSpace);
             }
         }
         var date = AdjustedDateHelper.GetAdjustedDate(paymentCalendar, payment.paymentDate);
         if (date == null)
         {
             continue;
         }
         payment.discountFactor          = (decimal)discountCurve.GetDiscountFactor(valuationDate, (DateTime)date);
         payment.discountFactorSpecified = true;
         payment.presentValueAmount      = MoneyHelper.Mul(payment.paymentAmount, payment.discountFactor);
     }
 }
Exemple #29
0
        /// <summary>
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="interestRateStream"></param>
        /// <param name="listAdjustedResetDates"></param>
        /// <param name="businessCalendar"></param>
        /// <param name="nameSpace"></param>
        /// <returns></returns>
        /// <exception cref="NotSupportedException"></exception>
        public static List <DateTime> GetAdjustedFixingDates(ICoreCache cache, InterestRateStream interestRateStream, List <DateTime> listAdjustedResetDates, IBusinessCalendar businessCalendar, string nameSpace)
        {
            var result = new List <DateTime>();
            RelativeDateOffset fixingDatesOffset = interestRateStream.resetDates.fixingDates;
            int numberOfDays = int.Parse(fixingDatesOffset.periodMultiplier);

            // Only NON-POSITIVE offset expressed in BUSINESS DAYS is supported.
            //
            if (!(fixingDatesOffset.dayType == DayTypeEnum.Business & fixingDatesOffset.period == PeriodEnum.D & numberOfDays <= 0))
            {
                string exceptionMessage =
                    $"[{fixingDatesOffset.dayType} {fixingDatesOffset.period} {numberOfDays} days] fixing day offset is not supported.";
                throw new NotSupportedException(exceptionMessage);
            }
            var businessDayAdjustments = new BusinessDayAdjustments
            {
                businessCenters       = fixingDatesOffset.businessCenters,
                businessDayConvention =
                    fixingDatesOffset.businessDayConvention
            };

            if (businessCalendar == null)
            {
                businessCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, businessDayAdjustments.businessCenters, nameSpace);
            }
            foreach (DateTime adjustedResetDate in listAdjustedResetDates)
            {
                int      offsetInBusinessDays = numberOfDays;
                DateTime adjustedFixingDate   = adjustedResetDate;
                while (offsetInBusinessDays++ < 0)
                {
                    // Adjust fixing date for one days back.
                    //
                    do
                    {
                        adjustedFixingDate = adjustedFixingDate.AddDays(-1);
                    } while (!businessCalendar.IsBusinessDay(adjustedFixingDate));

                    // adjustedFixingDate has been adjusted for 1 BUSINESS DAY
                }
                result.Add(adjustedFixingDate);
            }
            return(result);
        }
Exemple #30
0
        private static void LoadFPMLTrades(
            ILogger logger,
            ICoreCache client,
            Assembly assembly,
            string sourceSystem)
        {
            logger.LogDebug("Loading FPML trades...");
            Dictionary <string, string> chosenFiles = ResourceHelper.GetResources(assembly, ResourcePath + "." + sourceSystem, "xml");

            if (chosenFiles.Count == 0)
            {
                throw new InvalidOperationException(String.Format("No trades found!"));
            }

            // load gwml-to-fpml mappings
            //EnumMaps enumMaps = client.LoadObject<EnumMaps>("Orion.Configuration.GwmlEnumMaps");
            //GwmlFpmlEnumMap gwmlFpmlEnumMap = new GwmlFpmlEnumMap(enumMaps);
            foreach (KeyValuePair <string, string> file in chosenFiles)
            {
                string fpmlText = file.Value;
                // convert gwml
                //var fpmlDoc = XmlSerializerHelper.DeserializeFromString<DataDocument>(fpmlText);
                var tradeConfirmed = XmlSerializerHelper.DeserializeFromString <RequestConfirmation>(fpmlText);
                var trade          = tradeConfirmed.trade;
                //Converter imp = new Converter(gwmlFpmlEnumMap);
                var tradeProps = new NamedValueSet();
                tradeProps.Set(TradeProp.AsAtDate, DateTime.Today);
                tradeProps.Set(TradeProp.TradeSource, sourceSystem);
                // Document fpmlDoc = imp.ToFpml(gwmlDoc, tradeProps);
                // get trade properties
                //Trade trade = (Trade)(((DataDocument)fpmlDoc).Items[0]);
                ProductTypeSimpleEnum productType = ProductTypeSimpleScheme.ParseEnumString(trade.Item.Items[0].ToString());//TODO fix this
                DateTime tradeDate = trade.tradeHeader.tradeDate.Value;
                // now we can set the actual item name correctly
                string fpmlTradeItemName = $"{sourceSystem}.Trade.{productType}.{trade.id}";
                //gwmlDocItemName = String.Format("{0}.GWML.{1}.{2}", sourceSystem, productType, trade.id);
                tradeProps.Set(TradeProp.TradeDate, tradeDate);
                tradeProps.Set(TradeProp.TradeId, trade.id);
                tradeProps.Set(TradeProp.ProductType, ProductTypeSimpleScheme.GetEnumString(productType));
                tradeProps.Set(TradeProp.TradeState, TradeState.Verified.ToString());
                client.SaveObject(trade, fpmlTradeItemName, tradeProps, false, TimeSpan.FromDays(30));
            } // foreach file
            logger.LogDebug("Loaded {0} FPML trades.", chosenFiles.Count);
        }