public static object TurnbullWakemanFuturesPV( [ExcelArgument(Description = "Fixing dates")] double[] FixingDates, [ExcelArgument(Description = "Eval date")] DateTime EvalDate, [ExcelArgument(Description = "Pay date")] DateTime PayDate, [ExcelArgument(Description = "Forward curve")] string Curve, [ExcelArgument(Description = "Fixings")] string FixingDictionary, [ExcelArgument(Description = "Vol surface")] string Surface, [ExcelArgument(Description = "Strike")] double K, [ExcelArgument(Description = "Discounting rate")] double R, [ExcelArgument(Description = "Call or Put")] string CP) { return(ExcelHelper.Execute(_logger, () => { if (!Enum.TryParse(CP, out OptionType optType)) { return $"Could not parse call or put flag - {CP}"; } var curve = ContainerStores.GetObjectCache <IPriceCurve>().GetObjectOrThrow(Curve, $"Curve {Curve} not found"); var surface = ContainerStores.GetObjectCache <IVolSurface>().GetObjectOrThrow(Surface, $"Surface {Surface} not found"); var fd = new FixingDictionary(); var dates = FixingDates.ToDateTimeArray(); if (dates.First() < EvalDate) { fd = ContainerStores.GetObjectCache <FixingDictionary>().GetObjectOrThrow(FixingDictionary, $"Fixing dictionary {FixingDictionary} not found").Value; } var fwds = dates.Select(d => d > EvalDate?curve.Value.GetPriceForDate(d): fd.GetFixing(d)).ToArray(); var vols = dates.Select((d, ix) => surface.Value.GetVolForAbsoluteStrike(K, d, fwds[ix])).ToArray(); return Qwack.Options.Asians.TurnbullWakeman.PV(fwds, dates, EvalDate, PayDate, vols, K, R, optType); })); }
public static object PortfolioPvCvaCapital_B2_SM( [ExcelArgument(Description = "Discount curve")] string DiscountCurve, [ExcelArgument(Description = "Portfolio")] string Portfolio, [ExcelArgument(Description = "Asset-FX Model")] string Model, [ExcelArgument(Description = "Reporting currency")] string Currency, [ExcelArgument(Description = "Exposure dates")] double[] ExposureDates, [ExcelArgument(Description = "Party risk weight")] double CvaRiskWeight, [ExcelArgument(Description = "AssetId to Category map")] object[,] AssetIdToCategoryMap, [ExcelArgument(Description = "Category to CCF map")] object[,] CategoryToCCFMap) { return(ExcelHelper.Execute(_logger, () => { var disc = ContainerStores.GetObjectCache <IIrCurve>().GetObjectOrThrow(DiscountCurve, $"Discount curve {DiscountCurve} not found"); var portfolio = Instruments.InstrumentFunctions.GetPortfolioOrTradeFromCache(Portfolio); var model = ContainerStores.GetObjectCache <IAssetFxModel>().GetObjectOrThrow(Model, $"Asset-FX model {Model} not found"); var repCcy = ContainerStores.CurrencyProvider.GetCurrency(Currency); var expDates = ExposureDates.ToDateTimeArray(model.Value.BuildDate); var models = new IAssetFxModel[expDates.Length]; var m = model.Value.Clone(); for (var i = 0; i < models.Length; i++) { m = m.RollModel(expDates[i], ContainerStores.CurrencyProvider); models[i] = m; } var assetIdToCategory = AssetIdToCategoryMap.RangeToDictionary <string, string>(); var categoryToCCF = CategoryToCCFMap.RangeToDictionary <string, double>(); var result = CapitalCalculator.PvCvaCapital_BII_SM(model.Value.BuildDate, expDates, models, portfolio, repCcy, disc.Value, CvaRiskWeight, assetIdToCategory, categoryToCCF, ContainerStores.CurrencyProvider); return result; })); }
public static object FilterCubeSpecific( [ExcelArgument(Description = "Output cube name")] string OutputObjectName, [ExcelArgument(Description = "Input cube name")] string InputObjectName, [ExcelArgument(Description = "Filter field")] string FilterField, [ExcelArgument(Description = "Filter value")] object FilterValue, [ExcelArgument(Description = "Filter out? default false (i.e. filter in)")] object FilterOut) { return(ExcelHelper.Execute(_logger, () => { var filterOut = FilterOut.OptionalExcel(false); var cubeCache = ContainerStores.GetObjectCache <ICube>(); var inCube = cubeCache.GetObjectOrThrow(InputObjectName, $"Could not find cube {InputObjectName}"); var filterDeets = new Dictionary <string, object>() { { FilterField, FilterValue } }; var outCube = inCube.Value.Filter(filterDeets, filterOut); cubeCache.PutObject(OutputObjectName, new SessionItem <ICube> { Name = OutputObjectName, Value = outCube }); return OutputObjectName + '¬' + cubeCache.GetObject(OutputObjectName).Version; })); }
public static object GenerateCompoSurface( [ExcelArgument(Description = "Output surface name")] string ObjectName, [ExcelArgument(Description = "Asset-fx model name")] string AssetFxModel, [ExcelArgument(Description = "AssetId")] string AssetId, [ExcelArgument(Description = "FxPair")] string FxPair, [ExcelArgument(Description = "Correlation")] double Correlation, [ExcelArgument(Description = "Number of samples")] int NumberOfSamples) { return(ExcelHelper.Execute(_logger, () => { if (ContainerStores.GetObjectCache <IAssetFxModel>().TryGetObject(AssetFxModel, out var model)) { if (!model.Value.FundingModel.VolSurfaces.ContainsKey(FxPair)) { throw new Exception($"No vol surface found in model for fx pair {FxPair}"); } model.Value.GetVolSurface(AssetId); var surface = model.Value.GenerateCompositeSurface(AssetId, FxPair, NumberOfSamples, Correlation, true); return ExcelHelper.PushToCache <IVolSurface>(surface, ObjectName); } else { return $"Model {AssetFxModel} not found in cache"; } })); }
public static object GetForwardRate( [ExcelArgument(Description = "Curve object name")] string ObjectName, [ExcelArgument(Description = "Rate start date")] DateTime StartDate, [ExcelArgument(Description = "Rate end date")] DateTime EndDate, [ExcelArgument(Description = "Rate type, e.g. linear, CC")] object RateType, [ExcelArgument(Description = "Basis, e.g. Act365F")] object Basis) { return(ExcelHelper.Execute(_logger, () => { if (StartDate >= EndDate) { return "End date must be strictly greater that start date"; } var rateType = RateType.OptionalExcel <string>("Linear"); var basis = Basis.OptionalExcel <string>("Act365F"); if (!Enum.TryParse(rateType, out RateType rType)) { return $"Could not parse rate type - {rateType}"; } if (!Enum.TryParse(basis, out DayCountBasis dType)) { return $"Could not daycount basis - {basis}"; } if (ContainerStores.GetObjectCache <IIrCurve>().TryGetObject(ObjectName, out var curve)) { return curve.Value.GetForwardRate(StartDate, EndDate, rType, dType); } return $"IR curve {ObjectName} not found in cache"; })); }
public static object CreateFxMatrix( [ExcelArgument(Description = "Fx matrix name")] string ObjectName, [ExcelArgument(Description = "Base currency")] string BaseCurrency, [ExcelArgument(Description = "Build date")] DateTime BuildDate, [ExcelArgument(Description = "Spot rates")] object[,] SpotRateMap, [ExcelArgument(Description = "Fx pair definitions")] object[] FxPairDefinitions, [ExcelArgument(Description = "DiscountCurves")] object[,] DiscountCurves) { return(ExcelHelper.Execute(_logger, () => { var fxPairsCache = ContainerStores.GetObjectCache <FxPair>(); var fxPairs = FxPairDefinitions .Where(s => fxPairsCache.Exists(s as string)) .Select(s => fxPairsCache.GetObject(s as string).Value) .ToList(); var currencies = ContainerStores.GlobalContainer.GetRequiredService <ICurrencyProvider>(); var spotRatesRaw = SpotRateMap.RangeToDictionary <string, double>(); var spotRates = spotRatesRaw.ToDictionary(y => currencies[y.Key], y => y.Value); var discountCurvesRaw = DiscountCurves.RangeToDictionary <string, string>(); var discountCurves = discountCurvesRaw.ToDictionary(y => currencies[y.Key], y => y.Value); var matrix = new FxMatrix(currencies); matrix.Init(currencies[BaseCurrency], BuildDate, spotRates, fxPairs, discountCurves); return ExcelHelper.PushToCache(matrix, ObjectName); })); }
public static object TurnbullWakemanStrikeForPVFutures( [ExcelArgument(Description = "Evaluation Date")] DateTime EvalDate, [ExcelArgument(Description = "Fixing dates")] double[] FixingDates, [ExcelArgument(Description = "Settlement Date")] DateTime PayDate, [ExcelArgument(Description = "Target PV")] double PV, [ExcelArgument(Description = "Forward curve")] string FwdCurve, [ExcelArgument(Description = "Fixing dictionary")] string FixingDictionary, [ExcelArgument(Description = "Discounting rate")] double R, [ExcelArgument(Description = "Volatility Surface")] string VolSurface, [ExcelArgument(Description = "Call or Put")] string CP) { return(ExcelHelper.Execute(_logger, () => { var surface = ContainerStores.GetObjectCache <IVolSurface>().GetObjectOrThrow(VolSurface, $"Could not parse find vol surface {VolSurface} in the cache"); var curve = ContainerStores.GetObjectCache <IPriceCurve>().GetObjectOrThrow(FwdCurve, $"Fwd curve {FwdCurve} not found"); var fd = new FixingDictionary(); var dates = FixingDates.ToDateTimeArray(); if (dates.First() < EvalDate) { fd = ContainerStores.GetObjectCache <FixingDictionary>().GetObjectOrThrow(FixingDictionary, $"Fixing dictionary {FixingDictionary} not found").Value; } var F = dates.Select(d => d > EvalDate ? curve.Value.GetPriceForDate(d) : fd.GetFixing(d)).ToArray(); if (!Enum.TryParse(CP, out OptionType optType)) { return $"Could not parse call or put flag - {CP}"; } return Qwack.Options.Asians.TurnbullWakeman.StrikeForPV(PV, F, FixingDates.ToDateTimeArray(), surface.Value, EvalDate, PayDate, R, optType); })); }
public static object PortfolioExpectedEad_B2_SM( [ExcelArgument(Description = "Output cube name")] string OutputName, [ExcelArgument(Description = "Portfolio")] string Portfolio, [ExcelArgument(Description = "Asset-FX Model")] string Model, [ExcelArgument(Description = "Reporting currency")] string Currency, [ExcelArgument(Description = "EPE cube")] string EPECube, [ExcelArgument(Description = "AssetId to Category map")] object[,] AssetIdToCategoryMap, [ExcelArgument(Description = "Category to CCF map")] object[,] CategoryToCCFMap) { return(ExcelHelper.Execute(_logger, () => { var epeCube = ContainerStores.GetObjectCache <ICube>().GetObjectOrThrow(EPECube, $"EPE cube {EPECube} not found"); var portfolio = Instruments.InstrumentFunctions.GetPortfolioOrTradeFromCache(Portfolio); var model = ContainerStores.GetObjectCache <IAssetFxModel>().GetObjectOrThrow(Model, $"Asset-FX model {Model} not found"); var repCcy = ContainerStores.CurrencyProvider.GetCurrency(Currency); var expDates = epeCube.Value.GetAllRows().Select(r => (DateTime)r.MetaData[0]).ToArray(); var epeValues = epeCube.Value.GetAllRows().Select(r => r.Value).ToArray(); var models = new IAssetFxModel[expDates.Length]; var m = model.Value.TrimModel(portfolio); for (var i = 0; i < models.Length; i++) { m = m.RollModel(expDates[i], ContainerStores.CurrencyProvider); models[i] = m; } var assetIdToCategory = AssetIdToCategoryMap.RangeToDictionary <string, string>(); var categoryToCCF = CategoryToCCFMap.RangeToDictionary <string, double>(); var result = CapitalCalculator.EAD_BII_SM(model.Value.BuildDate, expDates, epeValues, models, portfolio, repCcy, assetIdToCategory, categoryToCCF, ContainerStores.CurrencyProvider); var cube = ExcelHelper.PackResults(expDates, result, "EAD"); return ExcelHelper.PushToCache(cube, OutputName); })); }
public static object ExtractCalibrationInfoFromModel( [ExcelArgument(Description = "Funding model name")] string FundingModelName) { return(ExcelHelper.Execute(_logger, () => { var model = ContainerStores.GetObjectCache <IFundingModel>().GetObject(FundingModelName).Value; if (model.CalibrationItterations != null) { var o = new object[model.CalibrationItterations.Count() + 1, 3]; o[0, 0] = "Time (ms)"; o[0, 1] = model.CalibrationTimeMs; o[0, 2] = "Curves in stage"; for (var i = 1; i <= model.CalibrationItterations.Count(); i++) { o[i, 0] = $"Passes Stage {i - 1}"; o[i, 1] = model.CalibrationItterations[i - 1]; o[i, 2] = model.CalibrationCurves[i - 1]; } return o; } else { var o = new object[1, 2]; o[0, 0] = "Time (ms)"; o[0, 1] = model.CalibrationTimeMs; return o; } })); }
public void PortfolioPVFact() { InstrumentFunctions.CreateAsianSwap("swpFake", "Jan-19", "xx", "USD", 0.0, 0.0, "NYC", "NYC", "2b", "2b", Value, "disco", Value); var model = new Mock <IAssetFxModel>(); model.Setup(m => m.GetPriceCurve("xx", null)).Returns(new ConstantPriceCurve(100, DateTime.Today, TestProviderHelper.CurrencyProvider)); var fModel = new Mock <IFundingModel>(); fModel.Setup(fm => fm.GetDf(It.IsAny <Currency>(), It.IsAny <DateTime>(), It.IsAny <DateTime>())).Returns(1.0); model.Setup(m => m.FundingModel).Returns(fModel.Object); ContainerStores.GetObjectCache <IAssetFxModel>().PutObject("model", new SessionItem <IAssetFxModel>() { Name = "model", Value = model.Object }); Assert.Equal("Could not find portfolio or trade with name trd", InstrumentFunctions.AssetPortfolioPV("out", "trd", "xxx", Value)); Assert.Equal("Could not find model with name xxx", InstrumentFunctions.AssetPortfolioPV("out", "swpFake", "xxx", Value)); Assert.Equal("out¬0", InstrumentFunctions.AssetPortfolioPV("out", "swpFake", "model", Value)); Assert.Equal("out¬1", InstrumentFunctions.AssetPortfolioPV("out", "swpFake", "model", "USD")); }
public static object PortfolioExpectedEadSplit( [ExcelArgument(Description = "Output cube name")] string OutputName, [ExcelArgument(Description = "Portfolio")] string Portfolio, [ExcelArgument(Description = "Asset-FX Model")] string Model, [ExcelArgument(Description = "Reporting currency")] string Currency, [ExcelArgument(Description = "Exposure dates")] double[] ExposureDates, [ExcelArgument(Description = "AssetId to Category map")] object[,] AssetIdToCategoryMap, [ExcelArgument(Description = "Category to CCF map")] object[,] CategoryToCCFMap, [ExcelArgument(Description = "Basel II / Basel II cutover date")] DateTime ChangeOverDate) { return(ExcelHelper.Execute(_logger, () => { var portfolio = Instruments.InstrumentFunctions.GetPortfolioOrTradeFromCache(Portfolio); var model = ContainerStores.GetObjectCache <IAssetFxModel>().GetObjectOrThrow(Model, $"Asset-FX model {Model} not found"); var repCcy = ContainerStores.CurrencyProvider.GetCurrency(Currency); var expDates = ExposureDates.ToDateTimeArray(model.Value.BuildDate); var models = new IAssetFxModel[expDates.Length]; var m = model.Value.Clone(); for (var i = 0; i < models.Length; i++) { m = m.RollModel(expDates[i], ContainerStores.CurrencyProvider); models[i] = m; } var assetIdToCategory = AssetIdToCategoryMap.RangeToDictionary <string, string>(); var categoryToCCF = CategoryToCCFMap.RangeToDictionary <string, double>(); var result = CapitalCalculator.EAD_Split(model.Value.BuildDate, expDates, models, portfolio, repCcy, assetIdToCategory, categoryToCCF, ChangeOverDate, ContainerStores.CurrencyProvider); var cube = ExcelHelper.PackResults(expDates, result, "EAD"); return ExcelHelper.PushToCache(cube, OutputName); })); }
public static object SolveStrikeForTargetRoC( [ExcelArgument(Description = "Hazzard curve")] string HazzardCurveName, [ExcelArgument(Description = "Discount curve")] string DiscountCurve, [ExcelArgument(Description = "Portfolio")] string Portfolio, [ExcelArgument(Description = "Asset-FX Model")] string Model, [ExcelArgument(Description = "Loss-given-default, e.g. 0.4")] double LGD, [ExcelArgument(Description = "Party risk weight, e.g. 1.0")] double PartyRiskWeight, [ExcelArgument(Description = "Reporting currency")] string Currency, [ExcelArgument(Description = "Target RoC")] double TargetRoC, [ExcelArgument(Description = "Weight for CVA Capital")] double CVACapitalWeight, [ExcelArgument(Description = "(Optional) LGD for xVA")] object LGDOverrideXVA, [ExcelArgument(Description = "AssetId to Category map")] object[,] AssetIdToCategoryMap, [ExcelArgument(Description = "Category to CCF map")] object[,] CategoryToCCFMap) { return(ExcelHelper.Execute(_logger, () => { var hz = ContainerStores.GetObjectCache <HazzardCurve>().GetObjectOrThrow(HazzardCurveName, $"Hazzard curve {HazzardCurveName} not found"); var disc = ContainerStores.GetObjectCache <IIrCurve>().GetObjectOrThrow(DiscountCurve, $"Discount curve {DiscountCurve} not found"); var portfolio = Instruments.InstrumentFunctions.GetPortfolioOrTradeFromCache(Portfolio); var model = ContainerStores.GetObjectCache <IAssetFxModel>().GetObjectOrThrow(Model, $"Asset-FX model {Model} not found"); var repCcy = ContainerStores.CurrencyProvider.GetCurrency(Currency); var xvaLgd = LGDOverrideXVA.OptionalExcel(LGD); var assetIdToCategory = AssetIdToCategoryMap.RangeToDictionary <string, string>(); var categoryToCCF = CategoryToCCFMap.RangeToDictionary <string, double>(); return SimplePortfolioSolver.SolveStrikeForGrossRoC(portfolio, model.Value, TargetRoC, repCcy, hz.Value, LGD, xvaLgd, PartyRiskWeight, CVACapitalWeight, disc.Value, ContainerStores.CurrencyProvider, assetIdToCategory, categoryToCCF); })); }
public static object ComputeCVACapitalBaselIII( [ExcelArgument(Description = "Origin date")] DateTime OriginDate, [ExcelArgument(Description = "EPE profile, cube or array")] object EPEProfile, [ExcelArgument(Description = "Loss-given-default, e.g. 0.4")] double LGD, [ExcelArgument(Description = "Probability-of-default, e.g. 0.02")] double PD, [ExcelArgument(Description = "Counterparty weighting, e.g. 0.1")] double PartyWeight) { return(ExcelHelper.Execute(_logger, () => { if (EPEProfile is object[,] arr) { if (arr.GetLength(1) != 2) { throw new Exception("Expected Nx2 array for EPE"); } var epeDates = new DateTime[arr.GetLength(0)]; var epeValues = new double[arr.GetLength(0)]; for (var i = 0; i < arr.GetLength(0); i++) { epeDates[i] = (DateTime)arr[i, 0]; epeValues[i] = (double)arr[i, 1]; } return XVACalculator.RWA_BaselIII_CVA_IMM(OriginDate, epeDates, epeValues, PD, LGD, PartyWeight); } else if (EPEProfile is string epeCubeName) { var cube = ContainerStores.GetObjectCache <ICube>().GetObjectOrThrow(epeCubeName, $"Cube {epeCubeName} not found"); return XVACalculator.RWA_BaselIII_IMM(OriginDate, cube.Value, PD, LGD, PartyWeight); } throw new Exception("EPE profile must be cube reference or Nx2 array"); })); }
public static object CreateConstantHazzardCurve( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "Hazzard rate")] double HazzardRate, [ExcelArgument(Description = "Build date")] DateTime BuildDate, [ExcelArgument(Description = "Basis, default Act365F")] object Basis) { return(ExcelHelper.Execute(_logger, () => { var basis = Basis.OptionalExcel("Act365F"); if (!Enum.TryParse(basis, out DayCountBasis dayCountBasis)) { throw new Exception($"Could not parse basis type - {basis}"); } var cObj = new HazzardCurve(BuildDate, dayCountBasis, new ConstantHazzardInterpolator(HazzardRate)) { ConstantPD = HazzardRate }; var cache = ContainerStores.GetObjectCache <HazzardCurve>(); cache.PutObject(ObjectName, new SessionItem <HazzardCurve> { Name = ObjectName, Value = cObj }); return ObjectName + '¬' + cache.GetObject(ObjectName).Version; })); }
public static object GenerateCompoSmile( [ExcelArgument(Description = "Output interpolator name")] string ObjectName, [ExcelArgument(Description = "Volsurface name")] string VolSurface, [ExcelArgument(Description = "Fx Volsurface name")] string FxVolSurface, [ExcelArgument(Description = "Expiry date")] DateTime ExpiryDate, [ExcelArgument(Description = "Forward")] double Forward, [ExcelArgument(Description = "Fx Forward")] double FxForward, [ExcelArgument(Description = "Correlation")] double Correlation, [ExcelArgument(Description = "Number of samples")] int NumberOfSamples) { return(ExcelHelper.Execute(_logger, () => { if (ContainerStores.GetObjectCache <IVolSurface>().TryGetObject(VolSurface, out var volSurface)) { if (ContainerStores.GetObjectCache <IVolSurface>().TryGetObject(FxVolSurface, out var volSurfaceFx)) { var interpolator = volSurface.Value.GenerateCompositeSmile(volSurfaceFx.Value, NumberOfSamples, ExpiryDate, Forward, FxForward, Correlation); return ExcelHelper.PushToCache(interpolator, ObjectName); } else { return $"Fx vol surface {FxVolSurface} not found in cache"; } } else { return $"Vol surface {VolSurface} not found in cache"; } })); }
public void AssetPnLAttributionExplainWithActivityFacts() { InstrumentFunctions.CreateAsianSwap("swpFake", "Jan-19", "xx", "USD", 0.0, 0.0, "NYC", "NYC", "2b", "2b", Value, "disco", Value); var model = new Mock <IAssetFxModel>(); ContainerStores.GetObjectCache <IAssetFxModel>().PutObject("model", new SessionItem <IAssetFxModel>() { Name = "model", Value = model.Object }); var pnlAttribMock = new Mock <IPnLAttributor>(); pnlAttribMock .Setup(p => p.ExplainAttribution(It.IsAny <Portfolio>(), It.IsAny <Portfolio>(), It.IsAny <IAssetFxModel>(), It.IsAny <IAssetFxModel>(), It.IsAny <Currency>(), It.IsAny <ICurrencyProvider>(), It.IsAny <bool>())) .Returns(new ResultCube()); ContainerStores.PnLAttributor = pnlAttribMock.Object; Assert.Equal("Could not find portfolio or trade with name trdS", InstrumentFunctions.AssetPnLAttributionExplainWithActivity("outzzy", "trdS", "trdE", "ms1", "ms2", "USD", false)); Assert.Equal("Could not find portfolio or trade with name trdE", InstrumentFunctions.AssetPnLAttributionExplainWithActivity("outzzy", "swpFake", "trdE", "ms1", "ms2", "USD", false)); Assert.Equal("Could not find model with name ms1", InstrumentFunctions.AssetPnLAttributionExplainWithActivity("outzzy", "swpFake", "swpFake", "ms1", "ms2", "USD", false)); Assert.Equal("Could not find model with name ms2", InstrumentFunctions.AssetPnLAttributionExplainWithActivity("outzzy", "swpFake", "swpFake", "model", "ms2", "USD", false)); Assert.Equal("outzzy¬0", InstrumentFunctions.AssetPnLAttributionExplainWithActivity("outzzy", "swpFake", "swpFake", "model", "model", "USD", false)); pnlAttribMock.Verify(p => p.ExplainAttribution(It.IsAny <Portfolio>(), It.IsAny <Portfolio>(), It.IsAny <IAssetFxModel>(), It.IsAny <IAssetFxModel>(), It.IsAny <Currency>(), It.IsAny <ICurrencyProvider>(), It.IsAny <bool>()), Times.Once); }
public static object CreateDiscountCurveFromCCRates( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "Curve name")] object CurveName, [ExcelArgument(Description = "Build date")] DateTime BuildDate, [ExcelArgument(Description = "Array of pillar dates")] double[] Pillars, [ExcelArgument(Description = "Array of CC zero rates")] double[] ZeroRates, [ExcelArgument(Description = "Type of interpolation")] object InterpolationType, [ExcelArgument(Description = "Currency - default USD")] object Currency, [ExcelArgument(Description = "Collateral Spec - default LIBOR.3M")] object CollateralSpec) { return(ExcelHelper.Execute(_logger, () => { var curveName = CurveName.OptionalExcel(ObjectName); var curveTypeStr = InterpolationType.OptionalExcel("Linear"); var ccyStr = Currency.OptionalExcel("USD"); var colSpecStr = CollateralSpec.OptionalExcel("LIBOR.3M"); if (!Enum.TryParse(curveTypeStr, out Interpolator1DType iType)) { return $"Could not parse interpolator type - {curveTypeStr}"; } var pDates = Pillars.ToDateTimeArray(); ContainerStores.SessionContainer.GetService <ICalendarProvider>().Collection.TryGetCalendar(ccyStr, out var ccyCal); var ccy = ContainerStores.GlobalContainer.GetRequiredService <ICurrencyProvider>()[ccyStr]; var cObj = new IrCurve(pDates, ZeroRates, BuildDate, curveName, iType, ccy, colSpecStr); var cache = ContainerStores.GetObjectCache <IIrCurve>(); cache.PutObject(ObjectName, new SessionItem <IIrCurve> { Name = ObjectName, Value = cObj }); return ObjectName + '¬' + cache.GetObject(ObjectName).Version; })); }
public static object SurfaceFromCube( [ExcelArgument(Description = "Output Surface name")] string SurfaceName, [ExcelArgument(Description = "Cube name")] string CubeName, [ExcelArgument(Description = "Build date")] DateTime BuildDate, [ExcelArgument(Description = "Currency")] string Currency, [ExcelArgument(Description = "Asset Id")] string AssetId, [ExcelArgument(Description = "Stike Interpolation - default GaussianKernel")] object StrikeInterpolation, [ExcelArgument(Description = "Time Interpolation - default LinearInVariance")] object TimeInterpolation) { return(ExcelHelper.Execute(_logger, () => { var cube = ContainerStores.GetObjectCache <ICube>().GetObjectOrThrow(CubeName, $"Cube {CubeName} not found"); var strikeInterpType = StrikeInterpolation.OptionalExcel("GaussianKernel"); var timeInterpType = TimeInterpolation.OptionalExcel("LinearInVariance"); if (!Enum.TryParse(strikeInterpType, out Interpolator1DType siType)) { return $"Could not parse strike interpolator type - {strikeInterpType}"; } if (!Enum.TryParse(timeInterpType, out Interpolator1DType tiType)) { return $"Could not parse time interpolator type - {timeInterpType}"; } var rrbf = RiskyFlySurface.FromCube(cube.Value, BuildDate, siType, tiType); rrbf.AssetId = AssetId; rrbf.Name = AssetId; if (!string.IsNullOrWhiteSpace(Currency)) { rrbf.Currency = ContainerStores.CurrencyProvider.GetCurrency(Currency); } return ExcelHelper.PushToCache <IVolSurface>(rrbf, SurfaceName); })); }
public static object CreateFundingModelParallel( [ExcelArgument(Description = "Funding model name")] string ObjectName, [ExcelArgument(Description = "Build date")] DateTime BuildDate, [ExcelArgument(Description = "Funding instrument collection")] string FundingInstrumentCollection, [ExcelArgument(Description = "Curve to solve stage mappings")] object SolveStages, [ExcelArgument(Description = "Fx matrix object")] object FxMatrix, [ExcelArgument(Description = "Fx vol surfaces")] object FxVolSurfaces) { return(ExcelHelper.Execute(_logger, () => { ContainerStores.GetObjectCache <FundingInstrumentCollection>().TryGetObject(FundingInstrumentCollection, out var fic); IFxMatrix fxMatrix = null; if (!(FxMatrix is ExcelMissing)) { var fxMatrixCache = ContainerStores.GetObjectCache <FxMatrix>(); fxMatrix = fxMatrixCache.GetObject((string)FxMatrix).Value; } var stageDict = fic.Value.ImplySolveStages2(fxMatrix); var emptyCurves = fic.Value.ImplyContainedCurves(BuildDate, Interpolator1DType.LinearFlatExtrap); var model = new FundingModel(BuildDate, emptyCurves.Values.ToArray(), ContainerStores.CurrencyProvider, ContainerStores.CalendarProvider); if (!(FxMatrix is ExcelMissing)) { model.SetupFx(fxMatrix); } if (!(FxVolSurfaces is ExcelMissing)) { IEnumerable <IVolSurface> surfaces = null; if (FxVolSurfaces is string vsStr) { surfaces = (new object[] { vsStr }).GetAnyFromCache <IVolSurface>(); } else { surfaces = ((object[, ])FxVolSurfaces).GetAnyFromCache <IVolSurface>(); } if (surfaces.Any()) { model.VolSurfaces = surfaces.ToDictionary(k => k.Name, v => v); } } if (fic != null) { var calibrator = new NewtonRaphsonMultiCurveSolverStaged() { InLineCurveGuessing = true }; calibrator.Solve(model, fic.Value, stageDict); } return ExcelHelper.PushToCache <IFundingModel>(model, ObjectName); })); }
public static IEnumerable <T> GetAnyFromCache <T>(this object[] Names) { var tCache = ContainerStores.GetObjectCache <T>(); var tS = Names .Where(s => !(s is ExcelMissing) && !(s is ExcelEmpty) && !string.IsNullOrWhiteSpace(s as string) && tCache.Exists(s as string)) .Select(s => tCache.GetObject(s as string).Value); return(tS); }
public static object CreateMcSettings( [ExcelArgument(Description = "Settings object name")] string ObjectName, [ExcelArgument(Description = "Number of paths")] int NumberOfPaths, [ExcelArgument(Description = "Number of timesteps")] int NumberOfTimesteps, [ExcelArgument(Description = "Random number generator, e.g. Sobol or MersenneTwister")] object RandomGenerator, [ExcelArgument(Description = "Reporting currency")] object ReportingCurrency, [ExcelArgument(Description = "Model to use, e.g. Black,LocalVol or TurboSkew")] string McModel, [ExcelArgument(Description = "Full futures simulation? (True/False)")] bool FuturesSim, [ExcelArgument(Description = "Parallel execution? (True/False)")] bool Parallel, [ExcelArgument(Description = "Futures mapping dictionary, assetId to futures code")] object FutMappingDict, [ExcelArgument(Description = "Enable debug mode")] object DebugMode, [ExcelArgument(Description = "Enable average path correction")] object PathCorrection, [ExcelArgument(Description = "Enable reduced memory operation")] object CompactMemoryMode, [ExcelArgument(Description = "Avoid regresison if possible for BackPricing options")] object AvoidBPRegression, [ExcelArgument(Description = "Enable local correlation? (True/False)")] bool LocalCorrelation, [ExcelArgument(Description = "Credit settings object")] object CreditSettings) { return(ExcelHelper.Execute(_logger, () => { if (!ContainerStores.GlobalContainer.GetRequiredService <ICurrencyProvider>().TryGetCurrency(ReportingCurrency.OptionalExcel("USD"), out var repCcy)) { return $"Could not find currency {ReportingCurrency} in cache"; } if (!Enum.TryParse(RandomGenerator.OptionalExcel("MersenneTwister"), true, out RandomGeneratorType randomGenerator)) { return $"Could not parse random generator name - {RandomGenerator}"; } if (!Enum.TryParse(McModel.OptionalExcel("Black"), true, out McModelType mcModel)) { return $"Could not parse model type - {McModel}"; } var settings = new McSettings { Generator = randomGenerator, NumberOfPaths = NumberOfPaths, NumberOfTimesteps = NumberOfTimesteps, ReportingCurrency = repCcy, McModelType = mcModel, ExpensiveFuturesSimulation = FuturesSim, Parallelize = Parallel, FuturesMappingTable = (FutMappingDict is ExcelMissing) ? new Dictionary <string, string>() : ((object[, ])FutMappingDict).RangeToDictionary <string, string>(), DebugMode = DebugMode.OptionalExcel(false), AveragePathCorrection = PathCorrection.OptionalExcel(false), CompactMemoryMode = CompactMemoryMode.OptionalExcel(false), AvoidRegressionForBackPricing = AvoidBPRegression.OptionalExcel(false), LocalCorrelation = LocalCorrelation, CreditSettings = (CreditSettings is ExcelMissing) ? null : ContainerStores.GetObjectCache <CreditSettings>().GetObjectOrThrow(CreditSettings as string, $"Unable to find Credit Settings {CreditSettings}").Value }; return ExcelHelper.PushToCache(settings, ObjectName); })); }
public static object SumAllRows( [ExcelArgument(Description = "Cube name")] string ObjectName) { return(ExcelHelper.Execute(_logger, () => { var cube = ContainerStores.GetObjectCache <ICube>().GetObjectOrThrow(ObjectName, $"Could not find cube {ObjectName}"); return cube.Value.SumOfAllRows; })); }
public static object Interpolate1dAverage( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "X values to interpolate")] double[] Xs) { return(ExcelHelper.Execute(_logger, () => { var interpolator = ContainerStores.GetObjectCache <IInterpolator1D>().GetObjectOrThrow(ObjectName, $"1d interpolator {ObjectName} not found in cache"); return interpolator.Value.Average(Xs); })); }
public static object SurfaceToQuotes( [ExcelArgument(Description = "Surface name")] string SurfaceName) { return(ExcelHelper.Execute(_logger, () => { var surface = ContainerStores.GetObjectCache <IVolSurface>().GetObjectOrThrow(SurfaceName, $"Vol surface {SurfaceName} not found"); var rrbf = (RiskyFlySurface)surface.Value; return rrbf.DisplayQuotes(); })); }
public static object ListCurvesInModel( [ExcelArgument(Description = "Funding model name")] string FundingModelName) { return(ExcelHelper.Execute(_logger, () => { var modelCache = ContainerStores.GetObjectCache <IFundingModel>(); var model = modelCache.GetObject(FundingModelName).Value; return model.Curves.Keys.Select(x => x as string).ToArray().ReturnExcelRangeVector(); })); }
public static object Interpolate2d( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "X value to interpolate")] double X, [ExcelArgument(Description = "Y value to interpolate")] double Y) { return(ExcelHelper.Execute(_logger, () => { var interpolator = ContainerStores.GetObjectCache <IInterpolator2D>().GetObjectOrThrow(ObjectName, $"2d interpolator {ObjectName} not found in cache"); return interpolator.Value.Interpolate(X, Y); })); }
public void CreateMcPrecursorFact() { ContainerStores.GetObjectCache <IAssetFxModel>().PutObject("van", new SessionItem <IAssetFxModel>() { Name = "van", Value = new AssetFxModel(DateTime.Today, null) }); ContainerStores.GetObjectCache <McSettings>().PutObject("set", new SessionItem <McSettings>() { Name = "set", Value = new McSettings() }); Assert.Equal("boom¬0", ModelFunctions.CreateMcModel("boom", "van", "set")); }
public static object CreateBasisPriceCurve( [ExcelArgument(Description = "Object name")] string ObjectName, [ExcelArgument(Description = "Asset Id")] string AssetId, [ExcelArgument(Description = "Base curve object")] string BaseCurve, [ExcelArgument(Description = "Build date")] DateTime BuildDate, [ExcelArgument(Description = "Array of pillar dates")] double[] Pillars, [ExcelArgument(Description = "Array of swap objects")] object[,] Swaps, [ExcelArgument(Description = "Discount curve name")] string DiscountCurveName, [ExcelArgument(Description = "Type of curve, e.g. LME, ICE, NYMEX etc")] object CurveType, [ExcelArgument(Description = "Currency")] string Currency, [ExcelArgument(Description = "(Optional) Pillar labels")] object PillarLabels) { return(ExcelHelper.Execute(_logger, () => { var curveTypeStr = CurveType.OptionalExcel <string>("Coal"); if (!Enum.TryParse(curveTypeStr, out PriceCurveType cType)) { return $"Could not parse price curve type - {curveTypeStr}"; } var irCache = ContainerStores.GetObjectCache <IIrCurve>(); if (!irCache.TryGetObject(DiscountCurveName, out var irCurveObj)) { return $"Could not find ir curve with name {DiscountCurveName}"; } var irCurve = irCurveObj.Value; var curveCache = ContainerStores.GetObjectCache <IPriceCurve>(); if (!curveCache.TryGetObject(BaseCurve, out var bCurveObj)) { return $"Could not find ir curve with name {DiscountCurveName}"; } var baseCurve = bCurveObj.Value; var pf = Instruments.InstrumentFunctions.GetPortfolio(Swaps); var ccy = ContainerStores.CurrencyProvider.GetCurrency(Currency); var labels = PillarLabels is ExcelMissing ? null : ((object[, ])PillarLabels).ObjectRangeToVector <string>().ToList(); var pDates = Pillars.ToDateTimeArray().ToList(); var cObj = new BasisPriceCurve(pf.Instruments.Where(x => x is IAssetInstrument).Select(x => x as IAssetInstrument).ToList(), pDates, irCurve, baseCurve, BuildDate, cType, new Models.Calibrators.NewtonRaphsonAssetBasisCurveSolver(ContainerStores.CurrencyProvider), labels) { Name = ObjectName, AssetId = AssetId, Currency = ccy }; curveCache.PutObject(ObjectName, new SessionItem <IPriceCurve> { Name = ObjectName, Value = cObj }); return ObjectName + '¬' + curveCache.GetObject(ObjectName).Version; })); }
public static object SurfaceToCube( [ExcelArgument(Description = "Surface name")] string SurfaceName, [ExcelArgument(Description = "Output cube name")] string CubeName) { return(ExcelHelper.Execute(_logger, () => { var surface = ContainerStores.GetObjectCache <IVolSurface>().GetObjectOrThrow(SurfaceName, $"Vol surface {SurfaceName} not found"); var rrbf = (RiskyFlySurface)surface.Value; var cube = rrbf.ToCube(); return RiskFunctions.PushCubeToCache(cube, CubeName); })); }
public static object GetSurvivalProbability( [ExcelArgument(Description = "Curve object name")] string ObjectName, [ExcelArgument(Description = "Start date")] DateTime StartDate, [ExcelArgument(Description = "End date")] DateTime EndDate) { return(ExcelHelper.Execute(_logger, () => { return ContainerStores .GetObjectCache <HazzardCurve>() .GetObjectOrThrow(ObjectName, $"Could not find curve {ObjectName}") .Value.GetSurvivalProbability(StartDate, EndDate); })); }