//---------------------------------------------------------------------------------------------------------
         //[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();
             }


         }
예제 #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]
         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();

             }
         }