Exemplo n.º 1
0
        public void CheckExpiryRollForCodeExamples(string futureCode, DateTime expiry, DateTime roll)
        {
            var code = new FutureCode(futureCode, 2016, TestProviderHelper.FutureSettingsProvider);

            Assert.Equal(expiry, code.GetExpiry());
            Assert.Equal(roll, code.GetRollDate());
        }
Exemplo n.º 2
0
        public BlackFuturesCurve(IATMVolSurface volSurface, DateTime startDate, DateTime expiryDate, int nTimeSteps, Func <DateTime, double> forwardCurve, string name, IFutureSettingsProvider futureSettingsProvider, Dictionary <DateTime, double> pastFixings = null)
        {
            _surface                = volSurface;
            _startDate              = startDate;
            _expiryDate             = expiryDate;
            _numberOfSteps          = nTimeSteps;
            _name                   = name;
            _forwardCurve           = forwardCurve;
            _pastFixings            = pastFixings ?? (new Dictionary <DateTime, double>());
            _futureSettingsProvider = futureSettingsProvider;
            if (startDate > expiryDate)
            {
                throw new Exception("Start date must be before expiry date");
            }
            _codes           = new List <string>();
            _futuresExpiries = new List <DateTime>();
            var fCode       = new FutureCode(name, _futureSettingsProvider);
            var currentCode = fCode.GetFrontMonth(startDate);

            _codes.Add(currentCode);
            fCode = new FutureCode(currentCode, DateTime.Today.Year - 2, _futureSettingsProvider);
            _futuresExpiries.Add(fCode.GetRollDate());
            fCode = new FutureCode(currentCode, DateTime.Today.Year - 2, _futureSettingsProvider);
            var targetCode = fCode.GetFrontMonth(expiryDate);

            while (currentCode != targetCode)
            {
                currentCode = fCode.GetNextCode(false);
                _futuresExpiries.Add(fCode.GetRollDate());
                _codes.Add(currentCode);
            }
        }
Exemplo n.º 3
0
 public static object FuturesExpiryFromCode(
     [ExcelArgument(Description = "Futures code, e.g. CLZ3")] string FuturesCode)
 {
     return(ExcelHelper.Execute(_logger, () =>
     {
         return FutureCode.GetExpiryFromCode(FuturesCode, ContainerStores.SessionContainer.GetService <IFutureSettingsProvider>());
     }));
 }
Exemplo n.º 4
0
        public static RiskyFlySurface GetSurfaceForCode(string nymexSymbol, string nymexOptionFilename, string qwackCode, BasicPriceCurve priceCurve, ICalendarProvider calendarProvider, ICurrencyProvider currency, IFutureSettingsProvider futureSettingsProvider)
        {
            var parsed = NYMEXOptionParser.Instance.Parse(nymexOptionFilename).Where(r => r.Symbol == nymexSymbol);

            var(optionExerciseType, optionMarginingType) = OptionTypeFromCode(nymexSymbol);
            var origin = DateTime.ParseExact(parsed.First().TradeDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);

            var q = parsed.Where(x => x.Settle > 0).Select(x => new ListedOptionSettlementRecord
            {
                CallPut               = x.PutCall == "C"?OptionType.C:OptionType.P,
                ExerciseType          = optionExerciseType,
                MarginType            = optionMarginingType,
                PV                    = x.Settle,
                Strike                = x.Strike,
                UnderlyingFuturesCode = Year2to1(x.Contract.Split(' ')[0].Replace(nymexSymbol, qwackCode)),
                ExpiryDate            = OptionExpiryFromNymexRecord(x, calendarProvider),
                ValDate               = origin
            }).Where(z => z.ExpiryDate > origin).ToList();

            var priceDict = priceCurve.PillarLabels.ToDictionary(x => x, x => priceCurve.GetPriceForDate(priceCurve.PillarDatesForLabel(x)));

            ListedSurfaceHelper.ImplyVols(q, priceDict, new ConstantRateIrCurve(0.0, origin, "dummy", currency.GetCurrency("USD")));
            var smiles = ListedSurfaceHelper.ToDeltaSmiles(q, priceDict);

            var allOptionExpiries = new List <DateTime>();
            var lastDate          = q.Max(x => x.ExpiryDate);

            var dummyFutureCode = $"{qwackCode}Z{DateExtensions.SingleDigitYear(DateTime.Today.Year + 2)}";
            var c = new FutureCode(dummyFutureCode, DateTime.Today.Year - 2, futureSettingsProvider);

            var contract     = c.GetFrontMonth(origin, false);
            var lastContract = c.GetFrontMonth(lastDate, false);

            while (contract != lastContract)
            {
                var cc     = new FutureCode(contract, origin.Year, futureSettingsProvider);
                var exp    = ListedUtils.FuturesCodeToDateTime(contract);
                var record = new NYMEXOptionRecord
                {
                    ContractMonth = exp.Month,
                    ContractYear  = exp.Year,
                    Symbol        = nymexSymbol
                };
                var optExpiry = OptionExpiryFromNymexRecord(record, calendarProvider);
                if (optExpiry > origin)
                {
                    allOptionExpiries.Add(optExpiry);
                }

                contract = cc.GetNextCode(false);
            }

            var surface = ListedSurfaceHelper.ToRiskyFlySurfaceStepFlat(smiles, origin, priceCurve, allOptionExpiries, currency);

            return(surface);
        }
Exemplo n.º 5
0
        public static object FuturesPreviousCode(
            [ExcelArgument(Description = "Futures code, e.g. CLZ3")] string FuturesCode)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                var c = new FutureCode(FuturesCode, DateTime.Today.Year - 2, ContainerStores.SessionContainer.GetService <IFutureSettingsProvider>());

                return c.GetPreviousCode();
            }));
        }
Exemplo n.º 6
0
        public static object FuturesGetFrontMonth(
            [ExcelArgument(Description = "Value date")] DateTime ValueDate,
            [ExcelArgument(Description = "Futures code root, e.g. CL")] string FuturesCodeRoot,
            [ExcelArgument(Description = "Use expiry rather than roll date")] bool UseExpiryRatherThanRoll)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                var dummyFutureCode = $"{FuturesCodeRoot}Z{DateExtensions.SingleDigitYear(DateTime.Today.Year + 2)}";

                var c = new FutureCode(dummyFutureCode, DateTime.Today.Year - 2, ContainerStores.SessionContainer.GetService <IFutureSettingsProvider>());

                return c.GetFrontMonth(ValueDate, UseExpiryRatherThanRoll);
            }));
        }
Exemplo n.º 7
0
        public void StripCrackedCurve()
        {
            var buildDate = new DateTime(2018, 07, 28);

            string[] futures       = { "COV8", "COX8", "COZ8", "COF9", "COG9" };
            double[] futuresPrices = { 77, 78, 79, 79.5, 79.75 };
            string[] periods       = { "AUG18", "SEP18", "OCT18", "NOV18" };
            double[] strikes       = { -10, -11, -12, -13 };

            var cal = TestProviderHelper.CalendarProvider.Collection["LON"];
            var usd = TestProviderHelper.CurrencyProvider["USD"];

            var bPillars   = futures.Select(x => FutureCode.GetExpiryFromCode(x, TestProviderHelper.FutureSettingsProvider)).ToArray();
            var brentCurve = new PriceCurve(buildDate, bPillars, futuresPrices, PriceCurveType.ICE, TestProviderHelper.CurrencyProvider, futures)
            {
                AssetId = "Brent"
            };


            var instruments = periods.Select((p, ix) =>
                                             (IAssetInstrument)AssetProductFactory.CreateTermAsianBasisSwap(p, strikes[ix], "Brent", "Sing180", cal, cal, cal, 0.Bd(), usd, 0.Bd(), 0.Bd(), 1000, 1000 / 6.35))
                              .ToList();
            var pillars = instruments.Select(x => ((AsianBasisSwap)x).RecSwaplets.Max(sq => sq.AverageEndDate)).ToList();

            DateTime[] dPillars      = { buildDate, buildDate.AddDays(1000) };
            double[]   dRates        = { 0, 0 };
            var        discountCurve = new IrCurve(dPillars, dRates, buildDate, "zeroDiscount", Interpolator1DType.LinearFlatExtrap, usd);

            var s = new Calibrators.NewtonRaphsonAssetBasisCurveSolver(TestProviderHelper.CurrencyProvider);

            if (IsCoverageOnly)
            {
                s.Tollerance = 1.0;
            }

            var curve = s.SolveCurve(instruments, pillars, discountCurve, brentCurve, buildDate, PriceCurveType.ICE);

            if (!IsCoverageOnly)
            {
                for (var i = 0; i < instruments.Count; i++)
                {
                    var resultPV = Calibrators.NewtonRaphsonAssetBasisCurveSolver.BasisSwapPv(curve, instruments[i], discountCurve, brentCurve);
                    Assert.Equal(0, resultPV, 6);
                }
            }
        }
Exemplo n.º 8
0
        private static IFundingInstrument ToQwackIns(this CMEFileRecord record, string qwackCode, IFutureSettingsProvider futureSettingsProvider, ICurrencyProvider currencyProvider, Dictionary <string, FloatRateIndex> indices, Dictionary <string, string> forecastCurves)
        {
            switch (qwackCode)
            {
            case "ED":
                var edExp = FutureCode.GetExpiryFromCode(MmmYtoCode(record.MMY, qwackCode), futureSettingsProvider);
                return(new STIRFuture
                {
                    ContractSize = 1e6,
                    Currency = currencyProvider.GetCurrency("USD"),
                    DCF = 0.25,
                    ConvexityAdjustment = 0,
                    Price = record.SettlePrice.Value,
                    Index = indices["ED"],
                    Expiry = edExp,
                    PillarDate = edExp.AddMonths(3),
                    TradeId = qwackCode + record.MMY,
                    Position = 1,
                    SolveCurve = forecastCurves["ED"],
                    ForecastCurve = forecastCurves["ED"],
                });

            case "FF":
                var ffEnd   = FutureCode.GetExpiryFromCode(MmmYtoCode(record.MMY, qwackCode), futureSettingsProvider);
                var ffStart = ffEnd.FirstDayOfMonth();
                return(new OISFuture
                {
                    ContractSize = 1e6,
                    Currency = currencyProvider.GetCurrency("USD"),
                    DCF = ffStart.CalculateYearFraction(ffEnd, DayCountBasis.ACT360),
                    Price = record.SettlePrice.Value,
                    Index = indices["FF"],
                    PillarDate = ffEnd,
                    TradeId = qwackCode + record.MMY,
                    Position = 1,
                    SolveCurve = forecastCurves["FF"],
                    ForecastCurve = forecastCurves["FF"],
                    AverageStartDate = ffStart,
                    AverageEndDate = ffEnd,
                });

            default:
                throw new Exception($"No mapping found for code {qwackCode}");
            }
        }
Exemplo n.º 9
0
        public static object CreateSTIRFromCode(
            [ExcelArgument(Description = "Object name")] string ObjectName,
            [ExcelArgument(Description = "Value date")] DateTime ValDate,
            [ExcelArgument(Description = "Futures Code, e.g. EDZ9")] string FuturesCode,
            [ExcelArgument(Description = "Rate Index")] string RateIndex,
            [ExcelArgument(Description = "Price")] double Price,
            [ExcelArgument(Description = "Quantity in lots")] double Quantity,
            [ExcelArgument(Description = "Convexity adjustment")] double ConvexityAdjustment,
            [ExcelArgument(Description = "Forecast Curve")] string ForecastCurve,
            [ExcelArgument(Description = "Solve Curve name ")] object SolveCurve,
            [ExcelArgument(Description = "Solve Pillar Date")] object SolvePillarDate)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                if (!ContainerStores.GetObjectCache <FloatRateIndex>().TryGetObject(RateIndex, out var rIndex))
                {
                    _logger?.LogInformation("Rate index {index} not found in cache", RateIndex);
                    return $"Rate index {RateIndex} not found in cache";
                }

                var c = new FutureCode(FuturesCode, DateTime.Today.Year - 2, ContainerStores.SessionContainer.GetService <IFutureSettingsProvider>());

                var expiry = c.GetExpiry();
                var accrualStart = expiry.AddPeriod(RollType.F, rIndex.Value.HolidayCalendars, rIndex.Value.FixingOffset);
                var accrualEnd = accrualStart.AddPeriod(rIndex.Value.RollConvention, rIndex.Value.HolidayCalendars, rIndex.Value.ResetTenor);
                //var dcf = accrualStart.CalculateYearFraction(accrualEnd, rIndex.Value.DayCountBasis);
                var product = new STIRFuture
                {
                    Currency = rIndex.Value.Currency,
                    ContractSize = c.Settings.LotSize,
                    //DCF = dcf,
                    ConvexityAdjustment = ConvexityAdjustment,
                    Expiry = expiry,
                    ForecastCurve = ForecastCurve,
                    Index = rIndex.Value,
                    Position = Quantity,
                    Price = Price,
                    SolveCurve = SolveCurve.OptionalExcel(ForecastCurve),
                    PillarDate = SolvePillarDate.OptionalExcel(accrualEnd),
                    TradeId = ObjectName
                };

                return ExcelHelper.PushToCache(product, ObjectName);
            }));
        }
Exemplo n.º 10
0
        public static BasicPriceCurve GetCurveForCode(string nymexSymbol, string nymexFutureFilename, string qwackCode, IFutureSettingsProvider provider, ICurrencyProvider currency)
        {
            var parsed    = NYMEXFutureParser.Instance.Parse(nymexFutureFilename).Where(r => r.Symbol == nymexSymbol);
            var q         = parsed.Where(x => x.Settle.HasValue).ToDictionary(x => Year2to1(x.Contract.Replace(nymexSymbol, qwackCode)), x => x.Settle);
            var datesDict = q.ToDictionary(x => FutureCode.GetExpiryFromCode(x.Key, provider), x => x.Key);
            var datesVec  = datesDict.Keys.OrderBy(x => x).ToArray();
            var labelsVec = datesVec.Select(d => datesDict[d]).ToArray();
            var pricesVec = labelsVec.Select(l => System.Math.Max(q[l].Value, MinPrice)).ToArray();
            var origin    = DateTime.ParseExact(parsed.First().TradeDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
            var curve     = new BasicPriceCurve(origin, datesVec, pricesVec, PriceCurveType.NYMEX, currency, labelsVec)
            {
                AssetId = qwackCode,
                Name    = qwackCode,
                SpotLag = 0.Bd()
            };

            return(curve);
        }
Exemplo n.º 11
0
        public static object CreateOISFutureFromCode(
            [ExcelArgument(Description = "Object name")] string ObjectName,
            [ExcelArgument(Description = "Value date")] DateTime ValDate,
            [ExcelArgument(Description = "Futures Code, e.g. EDZ9")] string FuturesCode,
            [ExcelArgument(Description = "Rate Index")] string RateIndex,
            [ExcelArgument(Description = "Price")] double Price,
            [ExcelArgument(Description = "Quantity in lots")] double Quantity,
            [ExcelArgument(Description = "Forecast Curve")] string ForecastCurve,
            [ExcelArgument(Description = "Solve Curve name ")] object SolveCurve,
            [ExcelArgument(Description = "Solve Pillar Date")] object SolvePillarDate)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                if (!ContainerStores.GetObjectCache <FloatRateIndex>().TryGetObject(RateIndex, out var rIndex))
                {
                    _logger?.LogInformation("Rate index {index} not found in cache", RateIndex);
                    return $"Rate index {RateIndex} not found in cache";
                }

                var c = new FutureCode(FuturesCode, DateTime.Today.Year - 2, ContainerStores.SessionContainer.GetService <IFutureSettingsProvider>());

                var expiry = c.GetExpiry();
                var accrualStart = expiry.FirstDayOfMonth();
                var accrualEnd = expiry.LastDayOfMonth();
                var dcf = accrualStart.CalculateYearFraction(accrualEnd, rIndex.Value.DayCountBasis);
                var product = new OISFuture
                {
                    Currency = rIndex.Value.Currency,
                    ContractSize = c.Settings.LotSize,
                    DCF = dcf,
                    AverageStartDate = accrualStart,
                    AverageEndDate = accrualEnd,
                    ForecastCurve = ForecastCurve,
                    Index = rIndex.Value,
                    Position = Quantity,
                    Price = Price,
                    SolveCurve = SolveCurve.OptionalExcel(rIndex.Name),
                    PillarDate = SolvePillarDate.OptionalExcel(accrualEnd),
                    TradeId = ObjectName
                };

                return ExcelHelper.PushToCache(product, ObjectName);
            }));
        }
Exemplo n.º 12
0
        public static object CreateFixingDictionaryForRollingFuture(
            [ExcelArgument(Description = "Object name")] string ObjectName,
            [ExcelArgument(Description = "Asset Id")] string AssetId,
            [ExcelArgument(Description = "Futures code, e.g. QS or CO")] string FuturesCode,
            [ExcelArgument(Description = "1st month fixings array, 1st column dates / 2nd column fixings")] object[,] Fixings1m,
            [ExcelArgument(Description = "2nd month fixings array, 1st column dates / 2nd column fixings")] object[,] Fixings2m)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                var dict = new FixingDictionary
                {
                    Name = AssetId,
                    AssetId = AssetId,
                    FixingDictionaryType = FixingDictionaryType.Asset
                };
                var futuresProvider = ContainerStores.SessionContainer.GetRequiredService <IFutureSettingsProvider>();
                var dictData1m = Fixings1m.RangeToDictionary <DateTime, double>();
                var dictData2m = Fixings2m.RangeToDictionary <DateTime, double>();
                var fc = new FutureCode(FuturesCode, futuresProvider);
                fc.YearBeforeWhich2DigitDatesAreUsed = DateTime.Today.Year - 2;

                foreach (var kv in dictData1m)
                {
                    var currentFM = fc.GetFrontMonth(kv.Key, true);
                    var cfm = new FutureCode(currentFM, DateTime.Today.Year - 2, futuresProvider);
                    if (kv.Key <= cfm.GetRollDate())
                    {
                        dict.Add(kv.Key, kv.Value);
                    }
                    else
                    {
                        dict.Add(kv.Key, dictData2m[kv.Key]);
                    }
                }
                return ExcelHelper.PushToCache <IFixingDictionary>(dict, ObjectName);
            }));
        }
Exemplo n.º 13
0
        public void Finish(IFeatureCollection collection)
        {
            if (!_timesteps.IsComplete)
            {
                return;
            }
            //vols...
            _vols = new double[_timesteps.TimeStepCount][];
            for (var t = 0; t < _vols.Length; t++)
            {
                _vols[t] = new double[_codes.Count];
                for (var c = 0; c < _vols[t].Length; c++)
                {
                    _vols[t][c] = _surface.GetVolForDeltaStrike(0.5, _futuresExpiries[c], 1.0);
                }
            }
            //work out which futures are front-month
            var fCode          = new FutureCode(_name, _futureSettingsProvider);
            var codesForDate   = _timesteps.Dates.Select(d => fCode.GetFrontMonth(d));
            var mappingFeature = collection.GetFeature <IPathMappingFeature>();

            _frontMonthFactors = codesForDate.Select(c => mappingFeature.GetDimension(c)).ToList();
            _isComplete        = true;
        }
Exemplo n.º 14
0
        public void CheckPreviousCodeExamples(string previousCode, string futureCode)
        {
            var code = new FutureCode(futureCode, 2016, TestProviderHelper.FutureSettingsProvider);

            Assert.Equal(previousCode, code.GetPreviousCode());
        }
Exemplo n.º 15
0
        public void CheckNextCodeExamples(string futureCode, string nextCode)
        {
            var code = new FutureCode(futureCode, 2016, TestProviderHelper.FutureSettingsProvider);

            Assert.Equal(nextCode, code.GetNextCode(false));
        }