Ejemplo n.º 1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="logger">The logger.</param>
 /// <param name="cache">The cache.</param>
 /// <param name="nameSpace"></param>
 /// <param name="properties"></param>
 /// <param name="expiries"></param>
 /// <param name="vols"></param>
 /// <param name="inputInstruments"></param>
 /// <param name="inputSwapRates"></param>
 /// <param name="blackVolatilities"></param>
 public RateVolatilitySurface(ILogger logger, ICoreCache cache, String nameSpace, NamedValueSet properties, DateTime[] expiries, double[] vols,
                              string[] inputInstruments, double[] inputSwapRates, double[] blackVolatilities)
     : base(logger, cache, nameSpace, properties, expiries, vols, inputInstruments, inputSwapRates, blackVolatilities)
 {
     PricingStructureData = new PricingStructureData(CurveType.Parent, AssetClass.Rates);
 }
Ejemplo n.º 2
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="uniqueId"></param>
 /// <param name="properties"></param>
 /// <param name="summary"></param>
 public CachedSummary(string uniqueId, NamedValueSet properties, ValuationReport summary)
 {
     UniqueId   = uniqueId;
     Properties = properties;
     Summary    = summary;
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Create a series of CapFloor 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>
        /// <param name="dfDataTimeGrid">The discount factor dates array.</param>
        /// <param name="dfGrid">The discount factors required for bootstrapping</param>
        /// <returns>The engine handle or an error message</returns>
        public string CreateCapFloorATMCurve(ILogger logger, ICoreCache cache, string nameSpace, NamedValueSet properties,
                                             String[] instruments, Decimal[] rawVolatilityGrid, DateTime[] dfDataTimeGrid, Decimal[] dfGrid)
        {
            var volatilityCheck = CheckVolatilities(rawVolatilityGrid);

            if (volatilityCheck != null)
            {
                throw new ArgumentException(volatilityCheck);
            }
            var id            = properties.GetString("EngineHandle", true);
            var baseDate      = properties.GetValue <DateTime>("BaseDate", true);
            var valuationDate = properties.GetValue("ValuationDate", DateTime.MinValue);

            if (valuationDate == DateTime.MinValue)
            {
                properties.Set("ValuationDate", baseDate);
            }
            properties.Set("PricingStructureType", PricingStructureTypeEnum.CapVolatilityCurve.ToString());
            var strikeQuoteUnits = properties.GetString("StrikeQuoteUnits", null);

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

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

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

            if (algorithm == null)
            {
                properties.Set("Algorithm", "Default");
            }
            InterpolationMethod interp = InterpolationMethodHelper.Parse("LogLinearInterpolation");
            // Check there are valid strikes
            IRateCurve discountCurve =
                new SimpleDiscountFactorCurve(baseDate, interp, true, dfDataTimeGrid, dfGrid);

            // Create the engines and either add to, or overwrite the existing, collection
            if (_capFloorEngine.ContainsKey(id))
            {
                _capFloorEngine[id] = CreateCurves(logger, cache, nameSpace, properties, discountCurve, discountCurve, instruments, rawVolatilityGrid);
            }
            else
            {
                _capFloorEngine.Add(id, CreateCurves(logger, cache, nameSpace, properties, discountCurve, discountCurve, instruments, rawVolatilityGrid));
            }
            return(id);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates the basic rate curve risk set, using the current curve as the base curve.
        /// This function takes a curves, creates a rate curve for each instrument and applying
        /// supplied basis point perturbation/spread to the underlying instrument in the spread curve
        /// </summary>
        /// <param name="basisPointPerturbation">The basis point perturbation.</param>
        /// <param name="pricingStructureRiskSetType">This determine which assets to perturb. </param>
        /// <returns>A list of perturbed rate curves</returns>
        public List <IPricingStructure> CreateCurveRiskSet(decimal basisPointPerturbation, PricingStructureRiskSetType pricingStructureRiskSetType)
        {
            var structures = new List <IPricingStructure>();

            if (PriceableCommoditySpreadAssets == null)
            {
                return(structures);
            }
            //Add the spread asset perturbed curves.
            //
            //Set the parameters and properties.
            decimal       perturbation = basisPointPerturbation / 10000.0m;
            NamedValueSet properties   = GetPricingStructureId().Properties.Clone();

            properties.Set("PerturbedAmount", basisPointPerturbation);
            string uniqueId = GetPricingStructureId().UniqueIdentifier;
            int    index    = 0;

            //Perturb the base curve quote set
            if (BaseCurve.PriceableCommodityAssets != null && pricingStructureRiskSetType != PricingStructureRiskSetType.Child)
            {
                var basequotes = GetMarketQuotes(BaseCurve.PriceableCommodityAssets);
                foreach (var instrument in BaseCurve.PriceableCommodityAssets)
                {
                    var perturbations = new decimal[basequotes.Count];
                    basequotes.CopyTo(perturbations);
                    //Clone the properties.
                    NamedValueSet curveProperties = properties.Clone();
                    perturbations[index] = basequotes[index] + perturbation;
                    curveProperties.Set("PerturbedAsset", instrument.Id);
                    curveProperties.Set("BaseCurve", uniqueId);
                    curveProperties.Set(CurveProp.UniqueIdentifier, uniqueId + "." + instrument.Id);
                    curveProperties.Set(CurveProp.Tolerance, Tolerance);
                    //Perturb the quotes
                    PerturbedPriceableAssets(BaseCurve.PriceableCommodityAssets, perturbations);
                    //Create the new curve.
                    var baseCurve = new CommodityCurve(curveProperties, BaseCurve.PriceableCommodityAssets, Holder);
                    IPricingStructure rateCurve = new CommoditySpreadCurve2(curveProperties, baseCurve,
                                                                            PriceableCommoditySpreadAssets, Holder);
                    structures.Add(rateCurve);
                    //Set the counter.
                    perturbations[index] = 0;
                    index++;
                }
            }
            //Perturb the spread curve quotes
            if (pricingStructureRiskSetType != PricingStructureRiskSetType.Parent)
            {
                var spreadquotes = GetMarketQuotes(PriceableCommoditySpreadAssets);
                index = 0;
                foreach (var instrument in PriceableCommoditySpreadAssets)
                {
                    var perturbations = new decimal[spreadquotes.Count];
                    spreadquotes.CopyTo(perturbations);
                    //Clone the properties.
                    NamedValueSet curveProperties = properties.Clone();
                    perturbations[index] = spreadquotes[index] + perturbation;
                    curveProperties.Set("PerturbedAsset", instrument.Id);
                    curveProperties.Set("BaseCurve", uniqueId);
                    curveProperties.Set(CurveProp.UniqueIdentifier, uniqueId + "." + instrument.Id);
                    curveProperties.Set(CurveProp.Tolerance, Tolerance);
                    //Perturb the quotes
                    PerturbedPriceableAssets(new List <IPriceableCommodityAssetController>(PriceableCommoditySpreadAssets),
                                             perturbations);
                    IPricingStructure rateCurve = new CommoditySpreadCurve2(curveProperties, BaseCurve,
                                                                            PriceableCommoditySpreadAssets, Holder);
                    structures.Add(rateCurve);
                    //Set the counter.
                    perturbations[index] = 0;
                    index++;
                }
            }
            return(structures);
        }
Ejemplo n.º 5
0
        private static PricingStructureAlgorithmsHolder GenerateHolder(ILogger logger, ICoreCache cache, String nameSpace, NamedValueSet properties)
        {
            var pricingStructureId = new CommodityCurveIdentifier(properties);
            var holder             = new PricingStructureAlgorithmsHolder(logger, cache, nameSpace, pricingStructureId.PricingStructureType, pricingStructureId.Algorithm);

            return(holder);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Bootstraps the specified priceable assets.
        /// </summary>
        /// <param name="priceableAssets">The priceable assets.</param>
        /// <param name="forecastCurve">The forecast rate curve.</param>
        /// <param name="baseDate">The base date.</param>
        /// <param name="extrapolationPermitted">The extrapolationPermitted flag.</param>
        /// <param name="interpolationMethod">The interpolationMethod.</param>
        /// <param name="tolerance">Solver tolerance to use.</param>
        /// <param name="discountCurve">The discount rate curve.</param>
        /// <param name="curveProperties">The properties.</param>
        /// <returns></returns>
        public static SortedList <DateTime, Decimal> Bootstrap(IEnumerable <IPriceableOptionAssetController> priceableAssets,
                                                               NamedValueSet curveProperties, IRateCurve discountCurve, IRateCurve forecastCurve, DateTime baseDate, Boolean extrapolationPermitted,
                                                               InterpolationMethod interpolationMethod, Double tolerance)
        {
            const double min = 0.000000001;
            const double max = 2;

            if (interpolationMethod == null)
            {
                interpolationMethod = InterpolationMethodHelper.Parse("LinearInterpolation");
            }
            var  points = new SortedList <DateTime, Decimal>();
            var  solver = new Brent();
            bool first  = true;

            // Add the rest
            foreach (var priceableOptionAssetController in priceableAssets)
            {
                var      priceableAsset    = (IPriceableRateOptionAssetController)priceableOptionAssetController;
                DateTime assetMaturityDate = priceableAsset.GetExpiryDate();
                if (points.Keys.Contains(assetMaturityDate))
                {
                    continue;
                }
                if (priceableAsset is PriceableRateFuturesOptionAsset || priceableAsset is PriceableSimpleRateOptionAsset)
                {
                    points[assetMaturityDate] = priceableAsset.VolatilityAtRiskMaturity;
                    first = false;
                }
                if (priceableAsset is PriceableCapRateAsset asset)
                {
                    //Some new code which creates flat volatilities out to the first expiry when no ETOs are supplied.
                    if (first)
                    {
                        var maturityDate = priceableAsset.GetRiskMaturityDate();
                        int weeks        = DateHelper.GetWeeks(baseDate, maturityDate);
                        for (var i = 1; i <= weeks; i++)
                        {
                            var shortEndDate = baseDate.AddDays(7 * i);
                            points[shortEndDate] = priceableAsset.VolatilityAtRiskMaturity;
                        }
                        points[assetMaturityDate] = priceableAsset.VolatilityAtRiskMaturity;
                    }
                    else
                    {
                        //The first guess, which should be correct for all priceable assets with analytical solutions that have been implemented.
                        points[assetMaturityDate] = priceableAsset.VolatilityAtRiskMaturity;
                        //Set the ATM strike
                        asset.DiscountCurve = discountCurve;
                        asset.ForecastCurve = forecastCurve;
                        asset.Strike        = asset.CalculateImpliedParRate(baseDate);
                        var objectiveFunction = new CapFloorAssetQuote(asset, discountCurve, forecastCurve, baseDate, interpolationMethod,
                                                                       extrapolationPermitted, points, tolerance);
                        // Check whether the guess was close enough
                        var initialValue = objectiveFunction.InitialValue();
                        if (initialValue)
                        {
                            continue;
                        }
                        var    tempMax = (double)points[assetMaturityDate];
                        double guess   = Math.Max(min, tempMax);
                        var    result  = solver.Solve(objectiveFunction, tolerance, guess, min, max);
                        points[assetMaturityDate] = (decimal)result;
                    }
                }
            }
            return(points);
        }
Ejemplo n.º 7
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="properties">The properties.</param>
 /// <param name="refCurve">The reference parent curve id.</param>
 /// <param name="value">The values.</param>
 /// <param name="fixingCalendar">The fixingCalendar.</param>
 /// <param name="rollCalendar">The rollCalendar.</param>
 public CommoditySpreadCurve2(ILogger logger, ICoreCache cache, string nameSpace, NamedValueSet properties, IPricingStructure refCurve, Decimal value,
                              IBusinessCalendar fixingCalendar, IBusinessCalendar rollCalendar)
     : base(logger, cache, nameSpace, AdjustMarketQuotes(value, refCurve.GetFpMLData(), PropertyHelper.ExtractUniqueCurveIdentifier(properties)), properties,
            fixingCalendar, rollCalendar)
 {
     PricingStructureData = new PricingStructureData(CurveType.Child, AssetClass.Rates, properties);
     ReferenceCurveId     = refCurve.GetPricingStructureId();
 }
Ejemplo n.º 8
0
 public Guid SaveObject <T>(T data, string name, NamedValueSet props)
 {
     return(SaveTypedObject(typeof(T), data, name, props, false, TimeSpan.MaxValue));
 }
Ejemplo n.º 9
0
 public Guid SaveObject <T>(T data, string name, NamedValueSet props, bool transient, DateTimeOffset expires)
 {
     return(SaveTypedObject(typeof(T), data, name, props, transient, expires));
 }
Ejemplo n.º 10
0
 public ICoreItem MakeItem <T>(T data, string name, NamedValueSet props, bool transient, TimeSpan lifetime)
 {
     return(Client.MakeItem(data, name, props, transient, lifetime));
 }
Ejemplo n.º 11
0
        public Guid SaveTypedObject(Type dataType, object data, string name, NamedValueSet props)
        {
            ICoreItem item = Client.MakeTypedItem(dataType, data, name, props, false);

            return(SaveItem(item));
        }
Ejemplo n.º 12
0
 // ------------------------------ make item methods ------------------------------
 public ICoreItem MakeItem <T>(T data, string name, NamedValueSet props, bool transient, DateTimeOffset expires)
 {
     return(Client.MakeItem(data, name, props, transient, expires));
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RateBasisCurve"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        ///  <param name="nameSpace">The client namespace</param>
        /// <param name="baseDiscountingCurve">The reference curve.</param>
        /// <param name="clearedRateAssets">The cleared rate asset.</param>
        /// <param name="properties">The properties of the new spread curve.</param>
        /// <param name="fixingCalendar">The fixingCalendar.</param>
        /// <param name="rollCalendar">The rollCalendar.</param>
        public ClearedRateCurve(ILogger logger, ICoreCache cache, string nameSpace,
                                IRateCurve baseDiscountingCurve, QuotedAssetSet clearedRateAssets, NamedValueSet properties,
                                IBusinessCalendar fixingCalendar, IBusinessCalendar rollCalendar)
            : base(logger, cache, nameSpace, new RateCurveIdentifier(properties), fixingCalendar, rollCalendar)
        {
            PricingStructureData        = new PricingStructureData(CurveType.Child, AssetClass.Rates, properties);
            BaseDiscountingCurve        = baseDiscountingCurve;
            ReferenceDiscountingCurveId = BaseDiscountingCurve.GetPricingStructureId();
            if (PricingStructureIdentifier.PricingStructureType != PricingStructureTypeEnum.ClearedRateCurve)
            {
                return;
            }
            var termCurve  = SetConfigurationData();
            var curveId    = GetRateCurveId();
            var indexTenor = curveId.ForecastRateIndex?.indexTenor;

            //Set the priceable assets.
            PriceableClearedRateAssets = PriceableAssetFactory.CreatePriceableClearedRateAssetsWithBasisSwaps(logger, cache, nameSpace, indexTenor, clearedRateAssets, PricingStructureIdentifier.BaseDate, fixingCalendar, rollCalendar);
            termCurve.point            = ClearedRateBootstrapper.Bootstrap(PriceableClearedRateAssets, BaseDiscountingCurve, curveId.BaseDate, termCurve.extrapolationPermitted,
                                                                           termCurve.interpolationMethod, Tolerance);
            CreatePricingStructure(curveId, termCurve, clearedRateAssets);
            // CreatePricingStructure(curveId, termCurve, PriceableAssetFactory.Parse(PriceableClearedRateAssets));
            // Interpolate the DiscountFactor curve based on the respective curve interpolation
            SetInterpolator(termCurve, curveId.Algorithm, curveId.PricingStructureType);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Takes a range of volatilities, an array of tenor expiries and an
 /// array of strikes to create a VolatilitySurface
 /// </summary>
 /// <param name="logger">The logger.</param>
 /// <param name="cache">The cache.</param>
 /// <param name="instrumentIds">A set of valid instrumentIds</param>
 /// <param name="expiryTenors">the expiry tenors.</param>
 /// <param name="strikes">The strikes.</param>
 /// <param name="values">The values.</param>
 /// <param name="nameSpace">The nameSpace</param>
 /// <param name="properties">The properties.</param>
 public RateVolatilitySurface(ILogger logger, ICoreCache cache, String nameSpace, NamedValueSet properties, String[] instrumentIds, String[] expiryTenors, Double[] strikes, Double[,] values)
     : base(logger, cache, nameSpace, properties, expiryTenors, strikes, MapFromRatePremiums(instrumentIds, values))//TODO map into the volsurface.
 {
     PricingStructureData = new PricingStructureData(CurveType.Parent, AssetClass.Rates);
 }
        /// <summary>
        /// Takes a range of volatilities, an array of tenor expiries and an
        /// array of strikes to create a VolatilitySurface
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        /// <param name="expiryTenors">the expiry tenors.</param>
        /// <param name="strikes">The strikes.</param>
        /// <param name="volSurface">The vol surface.</param>
        /// <param name="nameSpace">The nameSpace</param>
        /// <param name="properties">The properties.</param>
        /// <param name="forwards">The array of forwards. The first element is the spot value. Conseuently, the length of this array is expiryTenors.Length + 1.</param>
        protected ExtendedExpiryTermStrikeVolatilitySurface(ILogger logger, ICoreCache cache, String nameSpace, NamedValueSet properties, String[] expiryTenors, Double[] strikes, Double[] forwards, Double[,] volSurface)
        {
            var surfaceId = new VolatilitySurfaceIdentifier(properties);

            Algorithm = surfaceId.Algorithm;
            PricingStructureIdentifier = surfaceId;
            //Build the parameteric adjustment set from th3e forwards.
            var parametricAdjustment = GenerateForwards(forwards);
            var holder = new PricingStructureAlgorithmsHolder(logger, cache, nameSpace, surfaceId.PricingStructureType, surfaceId.Algorithm);
            var xDimensionInterpolationMethod = InterpolationMethodHelper.Parse(holder.GetValue("xDimensionInterpolation"));
            var yDimensionInterpolationMethod = InterpolationMethodHelper.Parse(holder.GetValue("yDimensionInterpolation"));

            _matrixIndexHelper = new SortedList <ExpiryTenorStrikeKey, int>(new ExpiryTenorStrikeKey());
            var points = ProcessRawSurface(expiryTenors, strikes, volSurface, surfaceId.StrikeQuoteUnits, surfaceId.UnderlyingAssetReference);

            PricingStructure = new VolatilityRepresentation
            {
                name     = surfaceId.Name,
                id       = surfaceId.Id,
                currency = surfaceId.Currency,
                asset    = new AnyAssetReference {
                    href = surfaceId.Instrument
                },
            };
            var datapoints = new MultiDimensionalPricingData {
                point             = points,
                businessCenter    = surfaceId.BusinessCenter,
                timing            = surfaceId.QuoteTiming,
                currency          = surfaceId.Currency,
                cashflowType      = surfaceId.CashflowType,
                informationSource = surfaceId.InformationSources,
                measureType       = surfaceId.MeasureType,
                quoteUnits        = surfaceId.QuoteUnits
            };

            if (surfaceId.ExpiryTime != null)
            {
                datapoints.expiryTime          = (DateTime)surfaceId.ExpiryTime;
                datapoints.expiryTimeSpecified = true;
            }
            if (surfaceId.ValuationDate != null)
            {
                datapoints.valuationDate          = (DateTime)surfaceId.ValuationDate;
                datapoints.valuationDateSpecified = true;
            }
            if (surfaceId.Time != null)
            {
                datapoints.time          = (DateTime)surfaceId.Time;
                datapoints.timeSpecified = true;
            }
            if (surfaceId.QuotationSide != null)
            {
                datapoints.side          = (QuotationSideEnum)surfaceId.QuotationSide;
                datapoints.sideSpecified = true;
            }
            PricingStructureValuation = new VolatilityMatrix
            {
                dataPoints = datapoints
                ,
                adjustment = parametricAdjustment
                ,
                objectReference = new AnyAssetReference {
                    href = surfaceId.Instrument
                }
                ,
                baseDate = new IdentifiedDate {
                    Value = surfaceId.BaseDate
                }
                ,
                buildDateTime = DateTime.Now
                ,
                buildDateTimeSpecified = true
            };
            var expiries = new double[expiryTenors.Length];
            var index    = 0;

            foreach (var term in expiryTenors)//TODO include business day holidays and roll conventions.
            {
                expiries[index] = PeriodHelper.Parse(term).ToYearFraction();
                index++;
            }
            // Record the row/column sizes of the inputs
            _matrixRowCount = expiryTenors.Length;
            // Columns includes expiry and term (tenor) if it exists.
            _matrixColumnCount = strikes.Length + 1;
            // Generate an interpolator to use
            Interpolator = new ExtendedVolatilitySurfaceInterpolator(expiries, strikes, forwards, new Matrix(volSurface), xDimensionInterpolationMethod.Value, yDimensionInterpolationMethod.Value);
        }
Ejemplo n.º 16
0
 public Guid SaveObject <T>(T data, string name, NamedValueSet props, bool transient, TimeSpan lifetime)
 {
     return(SaveTypedObject(typeof(T), data, name, props, transient, lifetime));
 }
        /// <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 ExtendedExpiryTermStrikeVolatilitySurface(ILogger logger, ICoreCache cache, String nameSpace, Pair <PricingStructure, PricingStructureValuation> fpmlData, NamedValueSet properties)
        {
            var surfaceId = new VolatilitySurfaceIdentifier(properties);

            Algorithm = surfaceId.Algorithm;
            PricingStructureIdentifier = surfaceId;
            var data   = (VolatilityMatrix)fpmlData.Second;
            var holder = new PricingStructureAlgorithmsHolder(logger, cache, nameSpace, surfaceId.PricingStructureType, surfaceId.Algorithm);
            //Get the forwards from the surface.
            var adjustments = new ParametricAdjustment();

            if (data.adjustment != null)
            {
                //assume the forwards are the first parameter set.
                adjustments = data.adjustment[0];
            }
            //Creates the property collection. This should be backward compatable with V1.
            PricingStructureIdentifier = new VolatilitySurfaceIdentifier(properties);
            var xDimensionInterpolationMethod = InterpolationMethodHelper.Parse(holder.GetValue("xDimensionInterpolation"));
            var yDimensionInterpolationMethod = InterpolationMethodHelper.Parse(holder.GetValue("yDimensionInterpolation"));

            // Generate an interpolator to use
            if (adjustments?.datapoint != null)
            {
                Interpolator = new ExtendedVolatilitySurfaceInterpolator(data.dataPoints, adjustments.datapoint, xDimensionInterpolationMethod.Value, yDimensionInterpolationMethod.Value);
            }
            SetFpMLData(fpmlData);
            _matrixIndexHelper = new SortedList <ExpiryTenorStrikeKey, int>(new ExpiryTenorStrikeKey());
            ProcessVolatilityRepresentation();
        }
Ejemplo n.º 18
0
        private static PricingStructureValuation ApplyStress(CachedStressRule stressRule, PricingStructureValuation psvInput)
        {
            string marketQuote = AssetMeasureScheme.GetEnumString(AssetMeasureEnum.MarketQuote);
            string decimalRate = PriceQuoteUnitsScheme.GetEnumString(PriceQuoteUnitsEnum.DecimalRate);
            var    psv         = BinarySerializerHelper.Clone(psvInput);
            // extract the market quotes from the cloned base curve
            QuotedAssetSet curveDefinition;

            if (psv is YieldCurveValuation yieldCurveValuation)
            {
                curveDefinition = yieldCurveValuation.inputs;
            }
            else
            {
                if (psv is FxCurveValuation curveValuation)
                {
                    curveDefinition = new QuotedAssetSet
                    {
                        instrumentSet = curveValuation.spotRate.instrumentSet,
                        assetQuote    = curveValuation.spotRate.assetQuote
                    };
                }
                else
                {
                    throw new NotSupportedException("Unsupported PricingStructureValuation type: " +
                                                    psv.GetType().Name);
                }
            }
            // stress the market quotes
            foreach (BasicAssetValuation asset in curveDefinition.assetQuote)
            {
                var stressDefQuotes = new List <BasicQuotation>();
                foreach (BasicQuotation quote in asset.quote)
                {
                    if (quote.measureType.Value.Equals(marketQuote) &&
                        quote.quoteUnits.Value.Equals(decimalRate))
                    {
                        var exprProps = new NamedValueSet(new NamedValue("MarketQuote", quote.value));
                        quote.valueSpecified = true;
                        quote.value          = Convert.ToDecimal(stressRule.UpdateExpr.Evaluate(exprProps));
                    }
                    quote.informationSource      = null;
                    quote.timeSpecified          = false;
                    quote.valuationDateSpecified = false;
                    stressDefQuotes.Add(quote);
                }
                asset.quote = stressDefQuotes.ToArray();
            }
            // replace the market quotes in the cloned base curve with the stressed values
            if (psv is YieldCurveValuation valuation)
            {
                valuation.inputs = curveDefinition;
                valuation.discountFactorCurve = null;
                valuation.zeroCurve           = null;
            }
            else
            {
                ((FxCurveValuation)psv).spotRate
                    = new FxRateSet
                    {
                    instrumentSet = curveDefinition.instrumentSet,
                    assetQuote    = curveDefinition.assetQuote
                    };
            }
            return(psv);
        }
Ejemplo 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="referenceCurve">The reference parent curveid.</param>
 /// <param name="spreadAssets">The spreads by asset.</param>
 /// <param name="properties">The properties of the new spread curve.</param>
 /// <param name="calendar">The calendar.</param>
 public CommoditySpreadCurve2(ILogger logger, ICoreCache cache, string nameSpace,
                              ICommodityCurve referenceCurve, FxRateSet spreadAssets, NamedValueSet properties,
                              IBusinessCalendar calendar)
     : base(logger, cache, nameSpace, ProcessQuotedAssetSet(logger, cache, nameSpace, referenceCurve, spreadAssets, properties, calendar), properties, calendar, calendar)
 {
     PricingStructureData = new PricingStructureData(CurveType.Child, AssetClass.Commodity, properties);
     BaseCurve            = referenceCurve;
     ReferenceCurveId     = BaseCurve.GetPricingStructureId();
     if (PricingStructureIdentifier.PricingStructureType != PricingStructureTypeEnum.CommoditySpreadCurve)
     {
         return;
     }
     //Set the spread sets.
     PriceableCommoditySpreadAssets = PriceableAssetFactory.CreatePriceableCommoditySpreadAssets(logger, cache, nameSpace, PricingStructureIdentifier.BaseDate, spreadAssets, calendar);
     Build(logger, cache, nameSpace, calendar, calendar);
 }
Ejemplo n.º 20
0
        public void ProcessRequest(RequestBase baseRequest, HandlerResponse response)
        {
            if (baseRequest == null)
            {
                throw new ArgumentNullException(nameof(baseRequest));
            }
            var request = baseRequest as StressedCurveGenRequest;

            if (request == null)
            {
                throw new InvalidCastException(
                          $"{typeof(RequestBase).Name} is not a {typeof(StressedCurveGenRequest).Name}");
            }
            // check for workflow cancellation
            if (Cancelled)
            {
                throw new OperationCanceledException(CancelReason);
            }
            DateTime lastStatusPublishedAt = DateTime.Now;

            CurveSelection[] curveSelectors = request.CurveSelector ?? new List <CurveSelection>().ToArray();

            #region Load stress rules

            //find the uniques namespaces
            var uniquesNameSpaces = new List <string>();
            foreach (CurveSelection curveSelector in curveSelectors)
            {
                if (!uniquesNameSpaces.Contains(curveSelector.NameSpace))
                {
                    uniquesNameSpaces.Add(curveSelector.NameSpace);
                }
            }
            var cachedStressRules = new Dictionary <string, List <CachedStressRule> >();
            {
                IExpression       queryExpr         = Expr.IsEQU(EnvironmentProp.NameSpace, uniquesNameSpaces[0]);//TODO only does the first namespace....
                List <StressRule> storedStressRules = Context.Cache.LoadObjects <StressRule>(queryExpr);
                foreach (StressRule storedStressRule in storedStressRules)
                {
                    if ((storedStressRule.Disabled) || (storedStressRule.StressId == null))
                    {
                        continue;
                    }
                    string key = storedStressRule.StressId.ToLower();
                    List <CachedStressRule> rules;
                    if (!cachedStressRules.TryGetValue(key, out rules))
                    {
                        rules = new List <CachedStressRule>();
                        cachedStressRules[key] = rules;
                    }
                    rules.Add(new CachedStressRule(storedStressRule));
                    rules.Sort();
                }
            }
            #endregion

            response.ItemCount = curveSelectors.Length * cachedStressRules.Count;
            // iterate selected base curves
            foreach (CurveSelection curveSelector in curveSelectors)
            {
                // check for workflow cancellation
                if (Cancelled)
                {
                    throw new OperationCanceledException(CancelReason);
                }
                // publish 'intermediate' in-progress result (throttled)
                if ((DateTime.Now - lastStatusPublishedAt) > TimeSpan.FromSeconds(5))
                {
                    lastStatusPublishedAt = DateTime.Now;
                    response.Status       = RequestStatusEnum.InProgress;
                    Context.Cache.SaveObject(response);
                }
                string nameSpace       = curveSelector.NameSpace;
                string inputMarketName = curveSelector.MarketName;
                var    marketDate      = curveSelector.MarketDate;
                if (marketDate != null && marketDate != DateTime.MinValue)
                {
                    inputMarketName += "." + ((DateTime)marketDate).ToString(CurveProp.MarketDateFormat);
                }
                string inputCurveName = curveSelector.CurveName;
                string inputCurveType = curveSelector.CurveType;
                Context.Logger.LogDebug("Building stressed curve(s): {0}.{1}.{2}", inputMarketName, inputCurveType, inputCurveName);

                #region Load base curve

                var curveGenProps = new NamedValueSet();
                curveGenProps.Set(CurveProp.BaseDate, request.BaseDate);
                IPricingStructureIdentifier baseCurveId =
                    PricingStructureIdentifier.CreateMarketCurveIdentifier(curveGenProps, inputMarketName, null, inputCurveType, inputCurveName, null);
                var       baseCurveUniqueId = baseCurveId.Properties.GetValue <string>(CurveProp.UniqueIdentifier, true);
                ICoreItem baseCurveItem     = LoadAndCheckMarketItem(Context.Cache, nameSpace, baseCurveUniqueId);
                var       stressNameProp    = baseCurveItem.AppProps.GetValue <string>(CurveProp.StressName, null);
                if (stressNameProp != null)
                {
                    throw new ApplicationException("The Market with name '" + baseCurveUniqueId + "' is NOT a base curve! (Stress name is not null)");
                }
                var baseCurveFpml = (Market)baseCurveItem.Data;
                var baseCurveType = PropertyHelper.ExtractPricingStructureType(baseCurveItem.AppProps);

                #endregion

                #region Load the reference curves - if required

                string        fxCurveName = null, refCurveName = null, quoteCurveName = null;
                NamedValueSet fxProperties = null, refProperties = null, quoteProperties = null;
                Market        fxMarket = null, refMarket = null, quoteMarket = null;
                if (baseCurveType == PricingStructureTypeEnum.RateBasisCurve ||
                    baseCurveType == PricingStructureTypeEnum.RateXccyCurve)
                {
                    // rate basis curves require a reference curve
                    refCurveName = baseCurveItem.AppProps.GetValue <string>(CurveProp.ReferenceCurveUniqueId, true);
                    // load the reference curve
                    var refCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, refCurveName);
                    refMarket     = (Market)refCurveItem.Data;
                    refProperties = refCurveItem.AppProps;
                }
                if (baseCurveType == PricingStructureTypeEnum.RateXccyCurve)
                {
                    // rate basis curves require an fx curve
                    fxCurveName = baseCurveItem.AppProps.GetValue <string>(CurveProp.ReferenceFxCurveUniqueId, true);
                    // load the reference curve
                    var fxCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, fxCurveName);
                    fxMarket     = (Market)fxCurveItem.Data;
                    fxProperties = fxCurveItem.AppProps;
                    // rate basis curves require a reference curve
                    quoteCurveName = baseCurveItem.AppProps.GetValue <string>(CurveProp.ReferenceCurrency2CurveId, true);
                    // load the reference curve
                    var quoteCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, quoteCurveName);
                    quoteMarket     = (Market)quoteCurveItem.Data;
                    quoteProperties = quoteCurveItem.AppProps;
                }
                #endregion

                // process stress rules
                foreach (var kvp in cachedStressRules)
                {
                    CachedStressRule stressRule = kvp.Value.FirstOrDefault(item => (item.FilterExpr == null) || (Expr.CastTo(item.FilterExpr.Evaluate(baseCurveItem.AppProps), false)));
                    // find stress rule that applies
                    if (stressRule == null)
                    {
                        // this stress does not apply to this base curve
                        Context.Logger.LogWarning("Stress '{0}' does not apply to base curve '{1}'!", kvp.Key, baseCurveUniqueId);
                        response.IncrementItemsPassed();
                        continue;
                    }
                    // apply the stress rule
                    //_Context.Logger.LogDebug("Applying stress '{0}' (rule {1}) to base curve '{2}'", stressRule.StressId, stressRule.RuleId, baseCurveUniqueId);
                    var stressDefProps = new NamedValueSet(baseCurveItem.AppProps, curveGenProps);
                    stressDefProps.Set("Identifier", null);//THis is done for backward compatability eith the old ratecurves.
                    stressDefProps.Set(CurveProp.BaseCurveType, baseCurveType);
                    IPricingStructureIdentifier stressCurveId = PricingStructureIdentifier.CreateMarketCurveIdentifier(
                        stressDefProps, inputMarketName, null, baseCurveType.ToString(), inputCurveName, stressRule.StressId);
                    NamedValueSet stressCurveProps = stressCurveId.Properties;
                    var           stressCurveName  = stressCurveProps.GetValue <string>(CurveProp.UniqueIdentifier, true);
                    // from here on a curve will be published (with error details included)
                    var stressCurve = new Market(); // empty
                    try
                    {
                        // clone the base curve and adjust the market quotes
                        var ps = BinarySerializerHelper.Clone(baseCurveFpml.Items[0]);
                        PricingStructureValuation psv = ApplyStress(stressRule, baseCurveFpml.Items1[0]);
                        // hack - supply base date
                        psv.baseDate = new IdentifiedDate {
                            Value = request.BaseDate
                        };
                        Triplet <PricingStructure, PricingStructureValuation, NamedValueSet> refCurveFpmlTriplet = null;
                        if (baseCurveType == PricingStructureTypeEnum.RateBasisCurve ||
                            baseCurveType == PricingStructureTypeEnum.RateXccyCurve)
                        {
                            var psRef = BinarySerializerHelper.Clone(refMarket.Items[0]);
                            //var psvRef = BinarySerializerHelper.Clone<PricingStructureValuation>(refcurveFpml.Items1[0]);
                            var psvRef = ApplyStress(stressRule, refMarket.Items1[0]);
                            refCurveFpmlTriplet =
                                new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                    psRef, psvRef, refProperties);
                        }
                        IPricingStructure ips;
                        switch (baseCurveType)
                        {
                        case PricingStructureTypeEnum.RateBasisCurve:
                            stressCurveProps.Set(CurveProp.ReferenceCurveUniqueId, refCurveName);
                            var basisCurveFpmlTriplet =
                                new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                    ps, psv, stressCurveProps);
                            //create and set the pricingstructure
                            ips = CurveLoader.LoadInterestRateCurve(Context.Logger, Context.Cache, nameSpace, refCurveFpmlTriplet, basisCurveFpmlTriplet);
                            //Creator.Create(refCurveFpmlTriplet, basisCurveFpmlTriplet);
                            break;

                        case PricingStructureTypeEnum.RateXccyCurve:
                            stressCurveProps.Set(CurveProp.ReferenceCurveUniqueId, refCurveName);
                            stressCurveProps.Set(CurveProp.ReferenceFxCurveUniqueId, fxCurveName);
                            stressCurveProps.Set(CurveProp.ReferenceCurrency2CurveId, quoteCurveName);
                            var xccyCurveFpmlTriplet =
                                new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(ps, psv,
                                                                                                         stressCurveProps);
                            //Format the ref curve data and call the pricing structure helper.
                            var psvFx = ApplyStress(stressRule, fxMarket.Items1[0]);
                            var fxCurveFpmlTriplet
                                = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                      fxMarket.Items[0],
                                      psvFx, fxProperties);

                            var psvRef = ApplyStress(stressRule, quoteMarket.Items1[0]);
                            var quoteCurveFpmlTriplet
                                = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                      quoteMarket.Items[0],
                                      psvRef, quoteProperties);
                            //create and set the pricingstructure
                            ips = CurveLoader.LoadInterestRateCurve(Context.Logger, Context.Cache, nameSpace, refCurveFpmlTriplet, fxCurveFpmlTriplet, quoteCurveFpmlTriplet,
                                                                    xccyCurveFpmlTriplet);
                            //Creator.Create(refCurveFpmlTriplet, fxCurveFpmlTriplet, quoteCurveFpmlTriplet, xccyCurveFpmlTriplet);
                            break;

                        default:
                            ips = CurveLoader.LoadCurve(Context.Logger, Context.Cache,
                                                        nameSpace, new Pair <PricingStructure, PricingStructureValuation>(ps, psv),
                                                        stressCurveProps);
                            //Creator.Create( new Pair<PricingStructure, PricingStructureValuation>(ps, psv), stressCurveProps);
                            break;
                        }
                        var identifier = ips.GetPricingStructureId().UniqueIdentifier;
                        // retrieve curve
                        stressCurve = PricingStructureHelper.CreateMarketFromFpML(
                            identifier,
                            ips.GetFpMLData());
                        // curve done
                        response.IncrementItemsPassed();
                    }
                    catch (Exception innerExcp)
                    {
                        response.IncrementItemsFailed();
                        Context.Logger.Log(innerExcp);
                        stressCurveProps.Set(WFPropName.ExcpName, WFHelper.GetExcpName(innerExcp));
                        stressCurveProps.Set(WFPropName.ExcpText, WFHelper.GetExcpText(innerExcp));
                    }
                    // save stressed curve with same lifetime as base curve
                    stressCurveProps.Set(EnvironmentProp.NameSpace, nameSpace);
                    Context.Cache.SaveObject(stressCurve, nameSpace + "." + stressCurveName, stressCurveProps, true, baseCurveItem.Expires);
                } // foreach stress rule
            }     // foreach base curve

            // success
            response.Status = RequestStatusEnum.Completed;
        }
Ejemplo n.º 21
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="spreadFpmlData">The FPML data.</param>
        /// <param name="properties">The properties</param>
        /// <param name="fixingCalendar">The fixingCalendar.</param>
        /// <param name="rollCalendar">The rollCalendar.</param>
        public CommoditySpreadCurve2(ILogger logger, ICoreCache cache, string nameSpace,
                                     Pair <PricingStructure, PricingStructureValuation> spreadFpmlData, NamedValueSet properties,
                                     IBusinessCalendar fixingCalendar, IBusinessCalendar rollCalendar)
            : base(logger, cache, nameSpace, spreadFpmlData, properties, fixingCalendar, rollCalendar)
        {
            PricingStructureData = new PricingStructureData(CurveType.Child, AssetClass.Rates, properties);
            var refCurveId = PropertyHelper.ExtractReferenceCurveUniqueId(properties);

            ReferenceCurveId = refCurveId != null ? new Identifier(refCurveId) : ReferenceCurveId = null;
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Takes a range of volatilities, an array of tenor expiries and an
 /// array of strikes to create a VolatilitySurface
 /// </summary>
 /// <param name="logger">The logger.</param>
 /// <param name="cache">The cache.</param>
 /// <param name="expiryTenors">the expiry tenors.</param>
 /// <param name="strikes">The strikes.</param>
 /// <param name="volSurface">The vol surface.</param>
 /// <param name="nameSpace">The nameSpace</param>
 /// <param name="properties">The properties.</param>
 public EquityVolatilitySurface(ILogger logger, ICoreCache cache, String nameSpace, NamedValueSet properties, String[] expiryTenors, Double[] strikes, Double[,] volSurface)
     : base(logger, cache, nameSpace, properties, expiryTenors, strikes, volSurface)
 {
     PricingStructureData = new PricingStructureData(CurveType.Parent, AssetClass.Equity);
 }
Ejemplo n.º 23
0
        //Clones a curve, maps the quoted assets specified and then returns an FpML structure back.
        //
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <param name="referenceCurve"></param>
        /// <param name="spreadValues"></param>
        /// <param name="properties"></param>
        /// <param name="calendar"></param>
        /// <returns></returns>
        public static Pair <PricingStructure, PricingStructureValuation> ProcessQuotedAssetSet(ILogger logger, ICoreCache cache,
                                                                                               string nameSpace, ICommodityCurve referenceCurve, FxRateSet spreadValues, NamedValueSet properties, IBusinessCalendar calendar)
        {
            var identifier = new CommodityCurveIdentifier(properties);
            //Clone the ref curves.
            //
            Pair <PricingStructure, PricingStructureValuation> fpml = CloneCurve(referenceCurve.GetFpMLData(), identifier.UniqueIdentifier);

            if (identifier.PricingStructureType != PricingStructureTypeEnum.CommoditySpreadCurve)
            {
                var ycvCurveCloned = (FxCurveValuation)fpml.Second;
                //  assign id to the cloned YieldCurve
                //
                ycvCurveCloned.fxForwardCurve.point = null;
                ycvCurveCloned.fxForwardCurve       = null;
                //Manipulate the quoted asset set.
                ycvCurveCloned.spotRate = MappedQuotedAssetSet(logger, cache, nameSpace, referenceCurve, spreadValues,
                                                               properties, calendar);
            }
            return(fpml);
        }
Ejemplo n.º 24
0
 /// <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>
 public EquityVolatilitySurface(ILogger logger, ICoreCache cache, String nameSpace, Pair <PricingStructure, PricingStructureValuation> fpmlData, NamedValueSet properties)
     : base(logger, cache, nameSpace, fpmlData, properties)
 {
     PricingStructureData = new PricingStructureData(CurveType.Parent, AssetClass.Equity);
 }
Ejemplo n.º 25
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="properties">The properties.</param>
 /// <param name="algorithmHolder">The algorithmHolder.</param>
 protected CommoditySpreadCurve2(NamedValueSet properties, PricingStructureAlgorithmsHolder algorithmHolder)
     : base(properties, algorithmHolder)
 {
     PricingStructureData = new PricingStructureData(CurveType.Child, AssetClass.Commodity, properties);
 }
Ejemplo n.º 26
0
 ///<summary>
 /// An id.
 ///</summary>
 ///<param name="properties">The properties.</param>
 public Identifier(NamedValueSet properties)
 {
     Properties = properties;
 }
Ejemplo n.º 27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="product"></param>
 /// <param name="properties"></param>
 /// <returns></returns>
 public abstract object[,] DoReport(Product product, NamedValueSet properties);
Ejemplo n.º 28
0
        private string CreateCurve(DateTime baseDate)
        {
            NamedValueSet propertySet = new NamedValueSet();
            const string  currency    = "AUD";
            const string  index       = "LIBOR-BBA";
            string        curveType   = "RateCurve";
            const string  indexName   = "AUDSwap";
            string        indexTenor  = "6M";
            string        curveName   = indexName + "-" + indexTenor;
            string        identifier  = curveType + "." + curveName;
            string        marketName  = "UnitTest";

            propertySet.Set(CurveProp.PricingStructureType, curveType);
            propertySet.Set(CurveProp.Market, marketName);
            propertySet.Set(CurveProp.IndexTenor, indexTenor);
            propertySet.Set("Currency", currency);
            propertySet.Set("Index", index);
            propertySet.Set("Algorithm", "Default");
            propertySet.Set("BuildDateTime", baseDate);
            propertySet.Set(CurveProp.IndexName, indexName);
            propertySet.Set(CurveProp.CurveName, curveName);
            propertySet.Set("Identifier", identifier);

            object[,] values =
            {
                { "AUD-Deposit-1D",                         0.03, 0 },
                { "AUD-Deposit-1M",                       0.0311, 0 },
                { "AUD-Deposit-2M",                       0.0311, 0 },
                { "AUD-Deposit-88D",                      0.0311, 0 },

                { "AUD-IRFuture-IR-U9", (100.0 - 96.895) / 100.0, 0 },      // IR01
                { "AUD-IRFuture-IR-Z9", (100.0 - 96.825) / 100.0, 0 },      // IR02
                { "AUD-IRFuture-IR-H0", (100.0 - 96.545) / 100.0, 0 },      // IR03
                { "AUD-IRFuture-IR-M0", (100.0 - 96.115) / 100.0, 0 },      //IR04
                { "AUD-IRFuture-IR-U0", (100.0 - 95.665) / 100.0, 0 },      // IR05
                { "AUD-IRFuture-IR-Z0", (100.0 - 95.285) / 100.0, 0 },      // IR06
                { "AUD-IRFuture-IR-H1", (100.0 - 94.955) / 100.0, 0 },      // IR07
                { "AUD-IRFuture-IR-M1", (100.0 - 94.645) / 100.0, 0 },      //IR08

                { "AUD-IRSwap-3Y",            0.0455749999999999, 0 },
                { "AUD-IRSwap-4Y",            0.0500999999999999, 0 },
                { "AUD-IRSwap-5Y",            0.0526999999999999, 0 },
                { "AUD-IRSwap-7Y",                        0.0558, 0 },
                { "AUD-IRSwap-10Y",                     0.057975, 0 },
                { "AUD-IRSwap-15Y",                     0.059725, 0 },
                { "AUD-IRSwap-20Y",                     0.058825, 0 },
                { "AUD-IRSwap-25Y",                     0.057675, 0 },
                { "AUD-IRSwap-26Y",                      0.05741, 0 },
                { "AUD-IRSwap-27Y",                     0.057145, 0 },
                { "AUD-IRSwap-28Y",                      0.05688, 0 },
                { "AUD-IRSwap-29Y",                     0.056615, 0 },
                { "AUD-IRSwap-30Y",                      0.05635, 0 }
            };

            int length = values.GetLength(0);

            string[]  instrument = new string[length];
            decimal[] value      = new decimal[length];
            decimal[] extra      = new decimal[length];
            for (int i = 0; i < length; i++)
            {
                instrument[i] = (string)values[i, 0];
                value[i]      = Convert.ToDecimal(values[i, 1]);
                extra[i]      = Convert.ToDecimal(values[i, 2]);
            }
            var curve = Engine.CreateCurve(propertySet, instrument, value, extra, null, null);

            Engine.SaveCurve(curve);
            return(curve.GetPricingStructureId().UniqueIdentifier);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Create a series of CapFloor 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 CreateCapFloorATMCurve(ILogger logger, ICoreCache cache, string nameSpace, NamedValueSet properties,
                                             String[] instruments, Decimal[] rawVolatilityGrid)
        {
            var volatilityCheck = CheckVolatilities(rawVolatilityGrid);

            if (volatilityCheck != null)
            {
                throw new ArgumentException(volatilityCheck);
            }
            var id            = properties.GetString("EngineHandle", true);
            var baseDate      = properties.GetValue <DateTime>("BaseDate", true);
            var valuationDate = properties.GetValue("ValuationDate", DateTime.MinValue);

            if (valuationDate == DateTime.MinValue)
            {
                properties.Set("ValuationDate", baseDate);
            }
            properties.Set("PricingStructureType", PricingStructureTypeEnum.CapVolatilityCurve.ToString());
            var strikeQuoteUnits = properties.GetString("StrikeQuoteUnits", null);

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

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

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

            if (algorithm == null)
            {
                properties.Set("Algorithm", "Default");
            }
            var referenceDiscountCurve = properties.GetString("ReferenceCurveUniqueId", true);
            var referenceForecastCurve = properties.GetString("ReferenceCurrency2CurveId", referenceDiscountCurve);
            var discountCurve          = CurveLoader.LoadInterestRateCurve(logger, cache, nameSpace, null, null, referenceDiscountCurve);
            var forecastCurve          = CurveLoader.LoadInterestRateCurve(logger, cache, nameSpace, null, null, referenceForecastCurve);

            // Create the engines and either add to, or overwrite the existing, collection
            if (_capFloorEngine.ContainsKey(id))
            {
                _capFloorEngine[id] = CreateCurves(logger, cache, nameSpace, properties, discountCurve, forecastCurve, instruments, rawVolatilityGrid);
            }
            else
            {
                _capFloorEngine.Add(id, CreateCurves(logger, cache, nameSpace, properties, discountCurve, forecastCurve, instruments, rawVolatilityGrid));
            }
            return(id);
        }
Ejemplo n.º 30
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="logger"></param>
 /// <param name="cache"></param>
 /// <param name="nameSpace"></param>
 /// <param name="fpMLPair"></param>
 /// <param name="properties"></param>
 /// <returns></returns>
 public static IPricingStructure GetRateATMVolatilityMatrix(ILogger logger, ICoreCache cache, String nameSpace, Pair <PricingStructure, PricingStructureValuation> fpMLPair, NamedValueSet properties)
 {
     return(new RateATMVolatilitySurface(logger, cache, nameSpace, fpMLPair, properties));
 }