Ejemplo n.º 1
0
        public void CanMerge()
        {
            var x = new ResultCube();

            x.Initialize(new Dictionary <string, Type> {
                { "gwah", typeof(string) }, { "wwahh", typeof(int) }
            });
            var y = new ResultCube();

            y.Initialize(new Dictionary <string, Type> {
                { "gwah", typeof(string) }, { "wwahh", typeof(int) }
            });

            x.AddRow(new object[] { "woooh", 6 }, 77.6);
            y.AddRow(new object[] { "woooh", 6 }, 77.4);

            var d = x.MergeQuick(y);

            Assert.Equal(2, d.GetAllRows().Length);
            d = x.Merge(y);
            Assert.Equal(2, d.GetAllRows().Length);

            var z = new ResultCube();

            z.Initialize(new Dictionary <string, Type> {
                { "gwah", typeof(bool) }, { "wwahh", typeof(int) }
            });
            Assert.Throws <Exception>(() => x.MergeQuick(z));
            Assert.Throws <Exception>(() => x.Merge(z));
        }
Ejemplo n.º 2
0
        public void CanDifference()
        {
            var x = new ResultCube();

            x.Initialize(new Dictionary <string, Type> {
                { "gwah", typeof(string) }, { "wwahh", typeof(int) }
            });
            var y = new ResultCube();

            y.Initialize(new Dictionary <string, Type> {
                { "gwah", typeof(string) }, { "wwahh", typeof(int) }
            });

            x.AddRow(new object[] { "woooh", 6 }, 77.6);
            y.AddRow(new object[] { "woooh", 6 }, 77.4);

            var d = x.Difference(y);

            Assert.Equal(0.2, d.GetAllRows().First().Value, 10);

            var z = new ResultCube();

            z.Initialize(new Dictionary <string, Type> {
                { "gwah", typeof(bool) }, { "wwahh", typeof(int) }
            });
            Assert.Throws <Exception>(() => x.Difference(z));
            Assert.Throws <Exception>(() => x.QuickDifference(z));

            y.AddRow(new object[] { "woooh", 7 }, 77.4);
            Assert.Throws <Exception>(() => x.QuickDifference(y));
        }
Ejemplo n.º 3
0
        public void RoundTrip()
        {
            //one cup of cube...
            var cube   = new ResultCube();
            var fields = new Dictionary <string, Type>
            {
                { "A", typeof(string) },
                { "B", typeof(int) },
                { "C", typeof(double) },
            };

            cube.Initialize(fields);

            //a pinch of data
            cube.AddRow(new object[] { "Z", 1, 1.1 }, 6.6);
            cube.AddRow(new object[] { "FF", 2, 1.0 }, 7.7);
            cube.AddRow(new object[] { "QQQ", 3, 1.101 }, 8.8);
            cube.AddRow(new object[] { "ABC", 4, 1.111 }, 9.9);

            //serialize @ 180c for .25ms
            var to = cube.ToTransportObject();
            var ms = new MemoryStream();

            ProtoBuf.Serializer.Serialize(ms, to);
            ms.Seek(0, SeekOrigin.Begin);
            var to2 = ProtoBuf.Serializer.Deserialize <TO_ResultCube>(ms);

            var hyperCube = new ResultCube(to2);

            Assert.Equal(cube.SumOfAllRows, hyperCube.SumOfAllRows);
        }
Ejemplo n.º 4
0
        public ICube Generate(IPvModel model, Portfolio portfolio = null)
        {
            var o = new ResultCube();

            o.Initialize(new Dictionary <string, Type>
            {
                { "AxisA", typeof(string) },
                { "AxisB", typeof(string) }
            });

            var scenarios = GenerateScenarios(model);

            ICube baseRiskCube = null;

            if (ReturnDifferential)
            {
                var baseModel = model;
                if (portfolio != null)
                {
                    baseModel = baseModel.Rebuild(baseModel.VanillaModel, portfolio);
                }
                baseRiskCube = GetRisk(baseModel);
            }

            var threadLock = new object();
            var results    = new ICube[scenarios.Count];
            var scList     = scenarios.ToList();

            ParallelUtils.Instance.For(0, scList.Count, 1, i =>
            {
                var scenario = scList[i];
                var pvModel  = scenario.Value;
                if (portfolio != null)
                {
                    pvModel = pvModel.Rebuild(pvModel.VanillaModel, portfolio);
                }
                var result = GetRisk(pvModel);

                if (ReturnDifferential)
                {
                    result = result.Difference(baseRiskCube);
                }

                results[i] = result;
            }).Wait();

            for (var i = 0; i < results.Length; i++)
            {
                o = (ResultCube)o.Merge(results[i],
                                        new Dictionary <string, object>
                {
                    { "AxisA", scList[i].Key.Item1 },
                    { "AxisB", scList[i].Key.Item2 }
                }, null, true);
            }

            return(o);
        }
Ejemplo n.º 5
0
        public ICube ToCube()
        {
            var cube      = new ResultCube();
            var dataTypes = new Dictionary <string, Type>
            {
                { "PointDate", typeof(DateTime) },
                { "PointType", typeof(string) },
                { "QuoteType", typeof(string) },
                { "PointDelta", typeof(double) },
            };

            cube.Initialize(dataTypes);

            for (var i = 0; i < Expiries.Length; i++)
            {
                var rowF = new Dictionary <string, object>
                {
                    { "PointDate", Expiries[i] },
                    { "PointType", "Forward" },
                    { "QuoteType", string.Empty },
                    { "PointDelta", 0.5 },
                };
                cube.AddRow(rowF, Forwards[i]);

                var rowA = new Dictionary <string, object>
                {
                    { "PointDate", Expiries[i] },
                    { "PointType", "ATM" },
                    { "QuoteType", AtmVolType.ToString() },
                    { "PointDelta", 0.5 },
                };
                cube.AddRow(rowA, ATMs[i]);

                for (var j = 0; j < WingDeltas.Length; j++)
                {
                    var rowRR = new Dictionary <string, object>
                    {
                        { "PointDate", Expiries[i] },
                        { "PointType", "RR" },
                        { "QuoteType", WingQuoteType.ToString() },
                        { "PointDelta", WingDeltas[j] },
                    };
                    cube.AddRow(rowRR, Riskies[i][j]);

                    var rowBF = new Dictionary <string, object>
                    {
                        { "PointDate", Expiries[i] },
                        { "PointType", "BF" },
                        { "QuoteType", WingQuoteType.ToString() },
                        { "PointDelta", WingDeltas[j] },
                    };
                    cube.AddRow(rowBF, Flies[i][j]);
                }
            }

            return(cube);
        }
Ejemplo n.º 6
0
        public ICube ResultCube()
        {
            var cube      = new ResultCube();
            var dataTypes = new Dictionary <string, Type>
            {
                { "ExposureDate", typeof(DateTime) }
            };

            cube.Initialize(dataTypes);

            foreach (var kv in EAD)
            {
                cube.AddRow(new object[] { kv.Key }, kv.Value);
            }
            return(cube);
        }
Ejemplo n.º 7
0
        public void ComputeEADFacts()
        {
            var curve = new PriceCurve(DateTime.MinValue, new[] { DateTime.MinValue }, new[] { 0.0 }, PriceCurveType.Flat, ContainerStores.CurrencyProvider)
            {
                Currency = ContainerStores.CurrencyProvider.GetCurrency("ZAR")
            };
            var moqModel = new Mock <IAssetFxModel>();

            moqModel.Setup(m => m.GetPriceCurve("fakeAsset", null)).Returns(curve);
            moqModel.Setup(m => m.VanillaModel).Returns(moqModel.Object);
            moqModel.Setup(m => m.Rebuild(It.IsAny <IAssetFxModel>(), It.IsAny <Portfolio>())).Returns(moqModel.Object);
            var cube = new ResultCube();

            cube.Initialize(new Dictionary <string, Type>()
            {
                { "xxx", typeof(string) }
            });
            moqModel.Setup(m => m.PV(It.IsAny <Currency>())).Returns(cube);
            var swap = new AsianSwap()
            {
                AssetId         = "fakeAsset",
                PaymentCurrency = ContainerStores.CurrencyProvider.GetCurrency("ZAR"),
                FixingDates     = new[] { DateTime.MinValue }
            };
            var pf = new Portfolio {
                Instruments = new List <IInstrument>()
                {
                    swap
                }
            };

            ContainerStores.GetObjectCache <Portfolio>().PutObject("moqPf", new SessionItem <Portfolio>()
            {
                Name = "moqPf", Value = pf
            });
            ContainerStores.GetObjectCache <IAssetFxModel>().PutObject("moqModel", new SessionItem <IAssetFxModel>()
            {
                Name = "moqModel", Value = moqModel.Object
            });

            Assert.Equal("Could not find portfolio or trade with name blash", CapitalFunctions.ComputeEAD("blash", "frah", "ZAR", null));
            Assert.Equal("Model frah not found", CapitalFunctions.ComputeEAD("moqPf", "frah", "ZAR", null));
            Assert.Equal(0.0, CapitalFunctions.ComputeEAD("moqPf", "moqModel", "ZAR", new object[, ] {
                { "fakeAsset", "woooh" }
            }));
        }
Ejemplo n.º 8
0
        private ICube GetSUT2()
        {
            var x = new ResultCube();

            x.Initialize(new Dictionary <string, Type> {
                { "gwah", typeof(string) }, { "wwahh", typeof(DateTime) }
            });
            x.AddRow(new object[] { "woooh", DateTime.Today.AddDays(10) }, 77.6);
            x.AddRow(new Dictionary <string, object> {
                { "gwah", "gloop" }, { "wwahh", DateTime.Today.AddDays(20) }
            }, 78.6);
            x.AddRow(new Dictionary <string, object> {
                { "wwahh", DateTime.Today.AddDays(30) }, { "gwah", "bah!" }
            }, 79.6);

            return(x);
        }
Ejemplo n.º 9
0
        private ICube GetSUT()
        {
            var x = new ResultCube();

            x.Initialize(new Dictionary <string, Type> {
                { "gwah", typeof(string) }, { "wwahh", typeof(int) }
            });
            x.AddRow(new object[] { "woooh", 6 }, 77.6);
            x.AddRow(new Dictionary <string, object> {
                { "gwah", "gloop" }, { "wwahh", 14 }
            }, 78.6);
            x.AddRow(new Dictionary <string, object> {
                { "wwahh", 83 }, { "gwah", "bah!" }
            }, 79.6);

            return(x);
        }
Ejemplo n.º 10
0
        public static ICube PackToCube(DateTime[] dates, double[] values, string metric)
        {
            if (dates.Length != values.Length)
            {
                throw new DataMisalignedException();
            }

            var cube      = new ResultCube();
            var dataTypes = new Dictionary <string, Type>
            {
                { "ExposureDate", typeof(DateTime) },
                { "Metric", typeof(string) }
            };

            cube.Initialize(dataTypes);

            for (var i = 0; i < values.Length; i++)
            {
                cube.AddRow(new object[] { dates[i], metric }, values[i]);
            }
            return(cube);
        }
Ejemplo n.º 11
0
        public static object CreateCube(
            [ExcelArgument(Description = "Cube name")] string ObjectName,
            [ExcelArgument(Description = "Header range")] object[] Headers,
            [ExcelArgument(Description = "Metadata range")] object[,] MetaData,
            [ExcelArgument(Description = "Value range")] double[] Data)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                if (Headers.Length != MetaData.GetLength(1))
                {
                    throw new Exception("Headers must match width of metadata range");
                }

                if (Data.Length != MetaData.GetLength(0))
                {
                    throw new Exception("Data vector must match length of metadata range");
                }

                var cube = new ResultCube();
                var dataTypes = Headers.ToDictionary(h => (string)h, h => typeof(string));
                cube.Initialize(dataTypes);

                for (var r = 0; r < MetaData.GetLength(0); r++)
                {
                    var rowMeta = new object[MetaData.GetLength(1)];
                    for (var c = 0; c < MetaData.GetLength(1); c++)
                    {
                        rowMeta[c] = MetaData[r, c];
                    }
                    cube.AddRow(rowMeta, Data[r]);
                }
                var cubeCache = ContainerStores.GetObjectCache <ICube>();
                cubeCache.PutObject(ObjectName, new SessionItem <ICube> {
                    Name = ObjectName, Value = cube
                });
                return ObjectName + '¬' + cubeCache.GetObject(ObjectName).Version;
            }));
        }
Ejemplo n.º 12
0
        public static ICube BenchmarkRisk(this IPvModel pvModel, FundingInstrumentCollection riskCollection, ICurrencyProvider currencyProvider, Currency reportingCcy)
        {
            var cube      = new ResultCube();
            var dataTypes = new Dictionary <string, Type>
            {
                { "TradeId", typeof(string) },
                { "TradeType", typeof(string) },
                { "Curve", typeof(string) },
                { "RiskDate", typeof(DateTime) },
                { "Benchmark", typeof(string) },
                { "Metric", typeof(string) },
                { "Units", typeof(string) },
                { "BumpSize", typeof(double) },
            };

            cube.Initialize(dataTypes);

            //var lastDate = pvModel.Portfolio.LastSensitivityDate;
            var insByCurve      = riskCollection.GroupBy(x => x.SolveCurve);
            var dependencies    = riskCollection.FindDependenciesInverse(pvModel.VanillaModel.FundingModel.FxMatrix);
            var lastDateByCurve = insByCurve.ToDictionary(x => x.Key, x => DateTime.MinValue);

            foreach (var ins in pvModel.Portfolio.UnWrapWrappers().Instruments)
            {
                if (ins is IFundingInstrument fins)
                {
                    var cvs = fins.Dependencies(pvModel.VanillaModel.FundingModel.FxMatrix);
                    foreach (var c in cvs)
                    {
                        if (!lastDateByCurve.ContainsKey(c))
                        {
                            lastDateByCurve[c] = DateTime.MinValue;
                        }

                        lastDateByCurve[c] = lastDateByCurve[c].Max(ins.LastSensitivityDate);
                    }
                }
                else if (ins is IAssetInstrument ains)
                {
                    var cvs = ains.IrCurves(pvModel.VanillaModel);
                    foreach (var c in cvs)
                    {
                        if (!lastDateByCurve.ContainsKey(c))
                        {
                            lastDateByCurve[c] = DateTime.MinValue;
                        }

                        lastDateByCurve[c] = lastDateByCurve[c].Max(ins.LastSensitivityDate);
                    }
                }
            }

            foreach (var c in lastDateByCurve.Keys.ToArray())
            {
                if (dependencies.ContainsKey(c))
                {
                    foreach (var d in dependencies[c])
                    {
                        lastDateByCurve[c] = lastDateByCurve[c].Max(lastDateByCurve[d]);
                    }
                }
            }


            var insToRisk = new List <IFundingInstrument>();

            foreach (var gp in insByCurve)
            {
                var lastDate = lastDateByCurve[gp.Key];
                var sorted   = gp.OrderBy(x => x.LastSensitivityDate).ToList();
                if (sorted.Last().LastSensitivityDate <= lastDate)
                {
                    insToRisk.AddRange(sorted);
                }
                else
                {
                    var lastIns = sorted.First(x => x.LastSensitivityDate > lastDate);
                    var lastIx  = sorted.IndexOf(lastIns);
                    lastIx = System.Math.Min(lastIx + 1, sorted.Count);
                    insToRisk.AddRange(sorted.Take(lastIx));
                }
            }

            var parRates = insToRisk.Select(x => x.CalculateParRate(pvModel.VanillaModel.FundingModel)).ToList();
            var newIns   = insToRisk.Select((x, ix) => x.SetParRate(parRates[ix]));
            var newFic   = new FundingInstrumentCollection(currencyProvider);

            newFic.AddRange(newIns.OrderBy(x => x.SolveCurve).ThenBy(x => x.PillarDate));

            var fModel = pvModel.VanillaModel.FundingModel.DeepClone(null);
            var s      = new NewtonRaphsonMultiCurveSolverStaged();

            s.Solve(fModel, newFic);

            var vModel     = pvModel.VanillaModel.Clone(fModel);
            var newPvModel = pvModel.Rebuild(vModel, pvModel.Portfolio);

            //var basePVbyCurrency = new Dictionary<Currency, ICube>();

            var basePV = newPvModel.PV(reportingCcy);

            ParallelUtils.Instance.For(0, newIns.Count(), 1, i =>
                                       //for (var i = 0; i < newIns.Count(); i++)
            {
                //if (!basePVbyCurrency.TryGetValue(insToRisk[i].Currency, out var basePV))
                //{
                //    basePV = newPvModel.PV(insToRisk[i].Currency);
                //    basePVbyCurrency[insToRisk[i].Currency] = basePV;
                //}

                var tIdIx   = basePV.GetColumnIndex("TradeId");
                var tTypeIx = basePV.GetColumnIndex("TradeType");

                var bumpSize = GetBumpSize(insToRisk[i]);

                var bumpedIns = newIns.Select((x, ix) => x.SetParRate(parRates[ix] + (ix == i ? bumpSize : 0.0)));
                var newFicb   = new FundingInstrumentCollection(currencyProvider);
                newFicb.AddRange(bumpedIns);

                var fModelb = fModel.DeepClone(null);

                var sb = new NewtonRaphsonMultiCurveSolverStaged();
                sb.Solve(fModelb, newFicb);

                var vModelb     = pvModel.VanillaModel.Clone(fModelb);
                var newPvModelb = pvModel.Rebuild(vModelb, pvModel.Portfolio);

                //var bumpedPV = newPvModelb.PV(insToRisk[i].Currency);
                var bumpedPV = newPvModelb.PV(reportingCcy);

                var bumpName  = insToRisk[i].TradeId;
                var riskDate  = insToRisk[i].PillarDate;
                var riskCurve = insToRisk[i].SolveCurve;
                var riskUnits = GetRiskUnits(insToRisk[i]);

                var deltaCube    = bumpedPV.QuickDifference(basePV);
                var deltaScale   = GetScaleFactor(insToRisk[i], parRates[i], parRates[i] + bumpSize, fModel);
                var fxToCurveCcy = fModel.GetFxRate(fModel.BuildDate, reportingCcy, insToRisk[i].Currency);

                foreach (var dRow in deltaCube.GetAllRows())
                {
                    if (dRow.Value == 0.0)
                    {
                        continue;
                    }

                    var row = new Dictionary <string, object>
                    {
                        { "TradeId", dRow.MetaData[tIdIx] },
                        { "TradeType", dRow.MetaData[tTypeIx] },
                        { "Benchmark", bumpName },
                        { "RiskDate", riskDate },
                        { "Curve", riskCurve },
                        { "Metric", "IrBenchmarkDelta" },
                        { "Units", riskUnits },
                        { "BumpSize", bumpSize },
                    };
                    cube.AddRow(row, dRow.Value * deltaScale * fxToCurveCcy);
                }
            }).Wait();

            return(cube.Sort(new List <string> {
                "Curve", "RiskDate", "TradeId"
            }));
        }