예제 #1
0
        //------------------------------------------------------------------------------------------------
        public SpreadSeriesBuilder(string metric, FuturesSeriesBuilder rawfuturesBuilder, SwapCurveSeriesBuilder swapBuilder,
            Dictionary<string, TimeSeriesBondStatic> bondStatics, SpreadConventions conventions, List<DateTime> holidays=null)
        //------------------------------------------------------------------------------------------------
        {

            if (holidays == null)
            {
                holidays = new List<DateTime>();
            }

            // Setup Everything
            var futuresBuilder = new FuturesSeriesBuilder(rawfuturesBuilder); //use copy constructor
            FuturesPrices = futuresBuilder.RawFuturesPrices;
            FuturesStatic = futuresBuilder.FuturesStatic;

            BondStatic = bondStatics;
            CombinedStatic = SpreadSeriesBuilder.combineFuturesAndBondStatic(BondStatic, FuturesStatic);

            if (conventions.bForecastCurve)
            {
                ForecastCurves = swapBuilder.ForecastCurves;
                DiscountCurves = swapBuilder.DiscountCurves;
            }
            else
            {
                ForecastCurves = swapBuilder.DiscountCurves;
                DiscountCurves = swapBuilder.DiscountCurves;
            }

            SpreadMetric_   = metric;
            Conv_           = conventions;

            Holidays_       = holidays;

            var rawSpreads = computeFuturesSpreads();

            // Now use this to get rolling futures too
            futuresBuilder.RawFuturesPrices = rawSpreads;
            futuresBuilder.interpolateRawPriceFrame();
            SpreadValues = futuresBuilder.getCombinedResults();

            FuturesBuilder_ = futuresBuilder;

        }
예제 #2
0
        //----------------------------------------------------------------------------------------
        public static Frame<DateTime, String> GenerateInvoiceSpreadTRS(
                    List<string> tickers, 
                    DateTime start,  
                    DateTime end,         
                    string countryCode, 
                    string pnlType = "InvoiceSpread",
                    bool bCumulative = true,
                    bool bOIS = true,
                    string samplingFreq= "1b",   
                    string rollMethod = "FirstNoticeDate", 
                    string holcal = "",
                    double notional = double.NaN,
                    ICarbonClient client = null)
        //----------------------------------------------------------------------------------------
        {
            var eRollMethod         = TimeSeriesUtilities.GetRollMethods(rollMethod);
            var eInterpolationTypes = TimeSeriesUtilities.GetInterpolationType("None");
            var eSmoothingTypes     = TimeSeriesUtilities.GetSmoothingTypes("None"); // Don't smooth, doesn't make sense for PnL
            bool bForecastCurve     = !bOIS;

            /* CARBON REQUIRES UTC TIME - MODIFY DATES TO ACCOMODATE */
            start = new DateTime(start.Year, start.Month, start.Day, 0, 0, 0, DateTimeKind.Utc);
            end = new DateTime(end.Year, end.Month, end.Day, 0, 0, 0, DateTimeKind.Utc);

            #region cache
            string all_tickers = ";";
            foreach (var s in tickers) all_tickers += s;

            string cacheKey = "GenerateInvoiceSpread" + tickers.ToString() + start.ToString() + end.ToString() +
                              countryCode + pnlType + bCumulative.ToString() + bOIS.ToString() + samplingFreq +
                              rollMethod + holcal + notional.ToString();

            if (TimeSeriesCache.ContainsKey(cacheKey))
            {
                return TimeSeriesCache[cacheKey];
            }
            #endregion
            if (client == null)
            {
                throw new ArgumentException("No Carbon Client!");
            }
            
            #region MeasureSetup

            string swapMeasure = "";
            string futMeasure = "";
            string ratio = "";
            bool bDefaultNoCumulative = false;
            switch (pnlType)
            {

                case "InvoiceSpread":
                    if (double.IsNaN(notional)) // work in DV01 terms
                    {
                        swapMeasure = "SwapPnlDV01Adj";
                        futMeasure = "FuturesPnlDV01Adj";
                    }
                    else
                    {
                        swapMeasure = "SwapPnl";
                        futMeasure = "FuturesPnl";
                        //ratio = "SpreadHedgeRatio"; // required to construct the correct pnl
                    }
                    
                    break;
                case "Futures":
                    if (double.IsNaN(notional)) // work in DV01 terms
                    {
                        swapMeasure = "";
                        futMeasure = "FuturesPnlDV01Adj";
                    }
                    else
                    {
                        swapMeasure = "";
                        futMeasure = "FuturesPnl";
                    }
                    break;
                case "MMS":
                    if (double.IsNaN(notional)) // work in DV01 terms
                    {
                        swapMeasure = "SwapPnlDV01Adj";
                        futMeasure = "";
                    }
                    else
                    {
                        swapMeasure = "SwapPnl";
                        futMeasure = "";
                    }
                    break;

                case "MMSDV01":
                    swapMeasure = "MMSDV01";
                    futMeasure = "";
                    bDefaultNoCumulative = true;
                    break;

                case "FuturesDV01":
                    swapMeasure = "FuturesDV01";
                    futMeasure = "";
                    bDefaultNoCumulative = true;
                    break;

                case "HedgeRatio":
                    swapMeasure = "SpreadHedgeRatio";
                    futMeasure = "";
                    bDefaultNoCumulative = true;
                    break;

                default:
                    throw new ArgumentException("");
            }
            #endregion

            #region Configs
            
            SpreadTimeSeriesConfigs config = new SpreadTimeSeriesConfigs(countryCode, !bOIS);

            string ccy = config.ccy;
            string calendarcode = (holcal != "") ? holcal : config.calendarcode;
            string futuresStaticMoniker = config.futuresStaticMoniker;
            string carbonEnv = config.carbonEnv;
            BondAnalytics.Country country = config.country;
            BondAnalytics.DayCountType dct = config.dct;
            long swpfixfreq = config.swpfixfreq;
            long swpfloatfreq = config.swpfloatfreq;
            long bndCouponFreq = config.bndCouponFreq;
            int BlendIndex = config.BlendIndex;
            string symForecastCurveName = config.SymForecastCurveName;
            string symDiscountCurveName = config.SymDiscountCurveName;
            List<string> contractSortOrder = config.contractSortOrder;

            List<DateTime> holidays = TimeSeriesUtilities.GetHolidays(calendarcode, client);

            #endregion

            var dateRange = TimeSeriesUtilities.GetAllDatesInDateime(start, end, calendarcode, client, samplingFreq);

            // Spread Static.
            SpreadConventions
                spreadconventions = new SpreadConventions(country, dct, swpfixfreq, swpfloatfreq, bndCouponFreq, bForecastCurve, BlendIndex);

            // Futures.
            FuturesSeriesBuilder
                   seriesBuilder = new FuturesSeriesBuilder(tickers, dateRange, holidays, futuresStaticMoniker, client, carbonEnv, rollMthd: eRollMethod, interpType: eInterpolationTypes, contractSortOrder: contractSortOrder, smoothingType: eSmoothingTypes);
            
            // Bond Static
            var bndStatics = TimeSeriesUtilities.GetBondStaticsFromFuturesBuilder(seriesBuilder, config, client);

            // Swap Curves
            var curves = TimeSeriesUtilities.GetCurvesFromCarbon(dateRange, ccy, client);

            if (curves == null || bndStatics == null) return null;

            var forecastCurves = curves.Item1;
            var discountCurves = curves.Item2;

            SwapCurveSeriesBuilder
                    swapBuilder = new SwapCurveSeriesBuilder(dateRange, symForecastCurveName, symDiscountCurveName, ccy, holidays, forecastCurves, discountCurves, client);

            // Generate Pnls
            Frame<DateTime,string> swapPnl = null;
            Frame<DateTime, string> futPnl = null;
            
            if (swapMeasure != "")
            {
                SpreadSeriesBuilder swapPnlBuilder = new SpreadSeriesBuilder(swapMeasure, seriesBuilder, swapBuilder,
                    bndStatics, spreadconventions, holidays);
                    
                swapPnl = swapPnlBuilder.SpreadValues;
            }
            if (futMeasure != "")
            {
                SpreadSeriesBuilder futPnlBuilder = new SpreadSeriesBuilder(futMeasure, seriesBuilder, swapBuilder,
                    bndStatics, spreadconventions, holidays);

                futPnl = futPnlBuilder.SpreadValues;
            }

            // Setup pnl correctly
            Frame<DateTime, string> pnl;
            if ( (swapPnl != null) && (futPnl != null))
            {
                // This allows it to match movements on the invoice spread chart.
                // Long TRS = pay fixed, long bond
                // Spread increases, mms increases, yield decreases -> swap/bond +ve pnl

                pnl = futPnl - swapPnl; 
            }
            else if (swapPnl != null)
            {
                pnl = swapPnl;
            }
            else
            {
                pnl = futPnl;
            }

           
           
            // Make it cumulative if flagged, but not for hedge ratios etc
            if (bCumulative && !bDefaultNoCumulative)
            {
                pnl = pnl.SortRowsByKey(); // in case
                pnl = TimeSeriesUtilities.DeedleFrameCumsum(pnl);
            }

            //Notional Adjust this thing
            if (!double.IsNaN(notional) && pnlType!="HedgeRatio")
            {
                pnl *= notional/100; // Default 100
            }
            

            TimeSeriesCache[cacheKey] = pnl;

            return pnl;

        }
         //---------------------------------------------------------------------------------------------------------
         //[Test]
         //  Price to Yield
         public void SwapSeriesTests()
         //---------------------------------------------------------------------------------------------------------
         {
             // Params
             DateTime start = new DateTime(2016,3,7);
             DateTime end = new DateTime(2016, 3, 11);
             string forecastCurveName   = "Symmetry_LIB3M";
             string discountCurveName   = "Symmetry_OIS";
             string ccy                 = "USD";
             string calendarcode        = "USNY";


             var swapBuilder = new SwapCurveSeriesBuilder(start, end, forecastCurveName, discountCurveName, ccy, mCarbonClient, calendarcode);
             swapBuilder.buildAllCurves();

             var forecastCurves = swapBuilder.ForecastCurves;
             var discountCurves = swapBuilder.DiscountCurves;



             // Check that we have the same number of curves on both ends
             Assert.AreEqual(forecastCurves.Count, discountCurves.Count,
                 "Discount and forecast curves have different counts! forec= " + forecastCurves.Count.ToString() +
                 " , disc= " + discountCurves.Count.ToString());

             // Now let's compare 11 Mar's curve to OT - make sure it uses the Fincad format.
             Dictionary<DateTime, double> usd3mLibor = new Dictionary<DateTime, double>()
             {
                {new DateTime(2016,06,15),0.99833466686521},
                {new DateTime(2016,06,16),0.998308555870634},
                {new DateTime(2016,09,15),0.996323400306606},
                {new DateTime(2016,12,21),0.993970514678176},
                {new DateTime(2017,03,21),0.991543542322688},
                {new DateTime(2017,06,15),0.989049450652512},
                {new DateTime(2017,09,21),0.986006268100615},
                {new DateTime(2017,12,20),0.983010351499106},
                {new DateTime(2018,03,20),0.979813454458774},
                {new DateTime(2018,06,21),0.976357131081902},
                {new DateTime(2018,09,20),0.97282759941777},
                {new DateTime(2019,03,15),0.965805631134839},
                {new DateTime(2020,03,16),0.949766985972098},
                {new DateTime(2021,03,15),0.932337062472182},
                {new DateTime(2022,03,15),0.913492071830929},
                {new DateTime(2023,03,15),0.893897883633253},
                {new DateTime(2024,03,15),0.873591217513506},
                {new DateTime(2025,03,17),0.852931807719771},
                {new DateTime(2026,03,16),0.832545151400381},
                {new DateTime(2028,03,15),0.791512055524562},
                {new DateTime(2031,03,17),0.73308525037499},
                {new DateTime(2036,03,17),0.644457551104283},
                {new DateTime(2041,03,15),0.568653627389078},
                {new DateTime(2046,03,15),0.503610865260006},
                {new DateTime(2056,03,15),0.398730962090625}
             };

             var forecastCurve = forecastCurves[new DateTime(2016, 3, 11)];

             System.Diagnostics.Debug.WriteLine("Processing curve points");
             foreach (var kvp in usd3mLibor)
             {
                 DateTime d8 = kvp.Key;
                 double val = kvp.Value;
                 
                 Assert.LessOrEqual(Math.Abs(val -  forecastCurve.CurveMap[d8]), Math.Pow(10,-8), "Discount Factors differ on " + d8.ToShortDateString() + " Test = " + val.ToString() + ", OT = " + forecastCurve.CurveMap[d8].ToString());
                 System.Diagnostics.Debug.WriteLine("{0}:    {1}", d8, val);
             }

         }
         //---------------------------------------------------------------------------------------------------------
         //[Test]
         public void SpreadSeriesToArrayTests()
        //---------------------------------------------------------------------------------------------------------
         {
             // Params.
             DateTime start = new DateTime(2016, 2, 28);
             DateTime end = new DateTime(2016, 3, 18);
             List<String> tickers = new List<string>() { "TUH6", "TUM6", "TUU6" };
             string samplingFreq = "1b";

             // Default Configs
             SpreadTimeSeriesConfigs config = new SpreadTimeSeriesConfigs("US");
             string forecastCurveName = config.forecastCurveName;
             string discountCurveName = config.discountCurveName;
             string ccy = config.ccy;
             string calendarcode = config.calendarcode;
             string futuresStaticMoniker = config.futuresStaticMoniker;
             string carbonEnv = config.carbonEnv;
             BondAnalytics.Country country = config.country;
             BondAnalytics.DayCountType dct = config.dct;
             long swpfixfreq = config.swpfixfreq;
             long swpfloatfreq = config.swpfloatfreq;
             long bndCouponFreq = config.bndCouponFreq;
             int BlendIndex = config.BlendIndex;
             bool bForecastCurve = true;

             // Bond Static
             Dictionary<string, TimeSeriesBondStatic> bondstatic = new Dictionary<string, TimeSeriesBondStatic>()
             {
                 {"US912828G799", new TimeSeriesBondStatic("US912828G799", new DateTime(2017,12,15), new DateTime(2015,12,15),DateTime.MinValue,1.0)},
                 {"US912828J686", new TimeSeriesBondStatic("US912828J686", new DateTime(2018,03,15), new DateTime(2015,03,16),DateTime.MinValue,1.0)},
                 {"US912828VK31", new TimeSeriesBondStatic("US912828VK31", new DateTime(2018,06,30), new DateTime(2015,07,01),DateTime.MinValue,1.0)}
             };


             //Spread Static
             SpreadConventions spreadconventions = new SpreadConventions(country, dct, swpfixfreq, swpfloatfreq, bndCouponFreq, bForecastCurve, BlendIndex);


             // Dates
             var holidays = new List<DateTime>();
             var dateRange = new List<DateTime>();

             using (var client = new CarbonClient(carbonEnv))
             {

                 // Holidays
                 if (calendarcode != "")
                 {
                     var nodaHols = client.GetCalendarAsync(calendarcode).Result.Dates;

                     foreach (LocalDate hol in nodaHols)
                     {
                         holidays.Add(hol.ToDateTime());
                     }
                 }

                 // DateRange
                 DateTime startDate = start.AddTenor(Tenor.FromString("1b"), "").AddTenor(Tenor.FromString("-1b"), "");
                 DateTime nextDate = end.AddTenor(Tenor.FromString("1b"), "").AddTenor(Tenor.FromString("-1b"), "");
                 //TimeSpan EOD = new TimeSpan(23, 59, 59);
                 /*if (startDate > nextDate)
                 {
                     return "Error! Bad Inputs!";
                 }*/
                 var tenor = Tenor.FromString("-" + samplingFreq);
                 while (nextDate >= startDate)
                 {
                     dateRange.Add(nextDate);
                     nextDate = BondAnalytics.PrevBusDay(nextDate.AddTenor(tenor, ""), holidays);
                 }

             }

             //Swap.
             var swapBuilder = new SwapCurveSeriesBuilder(dateRange, forecastCurveName, discountCurveName, ccy, holidays, mCarbonClient);
             swapBuilder.buildAllCurves();

             // Futures.
             var seriesBuilder = new FuturesSeriesBuilder(tickers, dateRange, holidays, futuresStaticMoniker, mCarbonClient, carbonEnv);

             // Spread Series.
             Dictionary<string, double> testVals = new Dictionary<string, double>()
             {
                 {"Price", 109.1015625},
                 {"Yield", 0.009007303 * 10000},
                 {"TrueSpread",6.7788999},
                 {"MMS", 0.009689381* 10000},
                 {"Spread", 6.820787365}
             };


             Dictionary<string /*metric*/, SpreadSeriesBuilder /*builder*/> spreadbuildermap = new Dictionary<string, SpreadSeriesBuilder>();

             SpreadSeriesBuilder output = null;
             foreach (var metric in testVals.Keys.ToList())
             {
                 output = new SpreadSeriesBuilder(metric, seriesBuilder, swapBuilder, bondstatic, spreadconventions);
                 Console.WriteLine(metric + " :");
                 output.SpreadValues.Print();

                 var row = output.SpreadValues.GetRow<double>(new DateTime(2016, 03, 18));

                 double TUM6 = row.Get("TUM6");
                 double error = Math.Abs(TUM6 - testVals[metric]);
                 Assert.LessOrEqual(error, Math.Pow(10, -3) * 5, "Error found in " + metric + ", test: " + testVals[metric].ToString() + ", actual: " + TUM6.ToString());  // 0.005bps

                 Console.WriteLine("Error :{0}", error);
             }

             // Now let's look at converting this to an array
             if (output != null)
             {
                 var objArr = output.getSpreadAsObjArr();
             }


         }
         //---------------------------------------------------------------------------------------------------------
         //[Test]
         public void SpreadSeries()
         //---------------------------------------------------------------------------------------------------------
         {
             
             // Params.
             DateTime start = new DateTime(2016, 2, 28);
             DateTime end = new DateTime(2016, 3, 18);
             List<String> tickers = new List<string>() { "TUH6", "TUM6", "TUU6","TU.Front" };

             // Default Configs
             SpreadTimeSeriesConfigs config = new SpreadTimeSeriesConfigs("US");
             string forecastCurveName       = config.forecastCurveName;
             string discountCurveName       = config.discountCurveName;
             string ccy                     = config.ccy;
             string calendarcode            = config.calendarcode;
             string futuresStaticMoniker    = config.futuresStaticMoniker;
             string carbonEnv               = config.carbonEnv;
             BondAnalytics.Country country  = config.country;
             BondAnalytics.DayCountType dct = config.dct;
             long swpfixfreq                = config.swpfixfreq;
             long swpfloatfreq              = config.swpfloatfreq;
             long bndCouponFreq             = config.bndCouponFreq;
             int BlendIndex                 = config.BlendIndex;
             bool bForecastCurve = true;

             // Bond Static
             Dictionary<string, TimeSeriesBondStatic> bondstatic = new Dictionary<string, TimeSeriesBondStatic>()
             {
                 {"US912828G799", new TimeSeriesBondStatic("US912828G799", new DateTime(2017,12,15), new DateTime(2015,12,15),DateTime.MinValue,1.0)},
                 {"US912828J686", new TimeSeriesBondStatic("US912828J686", new DateTime(2018,03,15), new DateTime(2015,03,16),DateTime.MinValue,1.0)},
                 {"US912828VK31", new TimeSeriesBondStatic("US912828VK31", new DateTime(2018,06,30), new DateTime(2015,07,01),DateTime.MinValue,1.0)}
             };

             //Spread Static
             SpreadConventions spreadconventions = new SpreadConventions(country,dct,swpfixfreq,swpfloatfreq,bndCouponFreq,bForecastCurve,BlendIndex);

             //Swap.
             var swapBuilder = new SwapCurveSeriesBuilder(start, end, forecastCurveName, discountCurveName, ccy, mCarbonClient, calendarcode);
             swapBuilder.buildAllCurves();
             //swapBuilder.DiscountCurves[new DateTime(2016, 03, 18)].PrintDump();
             swapBuilder.ForecastCurves[new DateTime(2016, 03, 18)].PrintDump();
             // Futures.
             var seriesBuilder                  = new FuturesSeriesBuilder(tickers, start, end, calendarcode, futuresStaticMoniker, mCarbonClient,carbonEnv);
             
             // Spread Series.
             Dictionary<string, double> testVals = new Dictionary<string, double>()
             {
                 {"Price", 109.1015625},
                 {"Yield", 0.009007303 * 10000},
                 {"TrueSpread",6.7788999},
                 {"MMS", 0.009689381* 10000},
                 {"Spread", 6.820787365}
             };


             Dictionary<string /*metric*/, SpreadSeriesBuilder /*builder*/> spreadbuildermap = new Dictionary<string, SpreadSeriesBuilder>();
             SpreadSeriesBuilder output = null;
             foreach (var metric in testVals.Keys.ToList())
             {
                 output = new SpreadSeriesBuilder(metric, seriesBuilder, swapBuilder, bondstatic, spreadconventions);
                 Console.WriteLine(metric + " :");
                 output.SpreadValues.Print();

                 var row = output.SpreadValues.GetRow<double>(new DateTime(2016, 03, 18));

                 double TUM6 = row.Get("TUM6");
                 double error = Math.Abs(TUM6 - testVals[metric]);
                 Assert.LessOrEqual(error, Math.Pow(10, -3) * 5, "Error found in " + metric + ", test: " + testVals[metric].ToString() + ", actual: " + TUM6.ToString());  // 0.005bps

                 Console.WriteLine("Error :{0}", error);
             }            


             // Now let's try to index 1 Mar
             if (output != null)
             {
                 var spreadVals = output.SpreadValues;
                 var myList = spreadVals.RowKeys.ToList();
                 Console.WriteLine("Key List: {0}", myList);

                 // Try on individual series
                 Dictionary<string/*colname*/, Series<DateTime,object>/*actualsrs*/> tmp = new Dictionary<string, Series<DateTime, object>>();

                 foreach (string colname in spreadVals.ColumnKeys)
                 {
                     tmp[colname] = spreadVals.Columns[colname].FillMissing("#N/A");
                 }

                 spreadVals = Frame.FromColumns(tmp);

                 //spreadVals.FillMissing("#N/A").Print();
                 var row = spreadVals.GetRow<string>(new DateTime(2016, 03, 01));
                 Console.WriteLine("Row values");
                 row.Print();

             }
         }