Exemple #1
0
        public void LessComplexCurve()
        {
            var startDate     = new DateTime(2016, 05, 20);
            var depoTenors    = new Frequency[] { 3.Months() };
            var OISdepoTenors = new Frequency[] { 1.Bd() };

            double[] depoPricesZAR = { 0.06 };

            string[] FRATenors    = { "3x6", "6x9", "9x12", "12x15", "15x18", "18x21", "21x24" };
            double[] FRAPricesZAR = { 0.065, 0.07, 0.075, 0.077, 0.08, 0.081, 0.082 };

            var ZARpillarDatesDepo = depoTenors.Select(x => startDate.AddPeriod(RollType.MF, _jhb, x)).ToArray();
            var ZARpillarDatesFRA  = FRATenors.Select(x => startDate.AddPeriod(RollType.MF, _jhb, new Frequency(x.Split('x')[1] + "M"))).ToArray();
            var ZARpillarDates3m   = ZARpillarDatesDepo.Union(ZARpillarDatesFRA).Distinct().OrderBy(x => x).ToArray();



            var ZARdepos = new IrSwap[depoTenors.Length];
            var ZARFRAs  = new ForwardRateAgreement[FRATenors.Length];

            var FIC = new FundingInstrumentCollection();

            for (var i = 0; i < FRATenors.Length; i++)
            {
                ZARFRAs[i] = new ForwardRateAgreement(startDate, FRATenors[i], FRAPricesZAR[i], _zar3m, SwapPayReceiveType.Payer, FraDiscountingType.Isda, "ZAR.JIBAR.3M", "ZAR.JIBAR.3M")
                {
                    SolveCurve = "ZAR.JIBAR.3M"
                };
                FIC.Add(ZARFRAs[i]);
            }

            for (var i = 0; i < depoTenors.Length; i++)
            {
                ZARdepos[i] = new IrSwap(startDate, depoTenors[i], _zar3m, depoPricesZAR[i], SwapPayReceiveType.Payer, "ZAR.JIBAR.3M", "ZAR.JIBAR.3M")
                {
                    SolveCurve = "ZAR.JIBAR.3M"
                };
                FIC.Add(ZARdepos[i]);
            }



            var ZARcurve3m = new IrCurve(ZARpillarDates3m, new double[ZARpillarDates3m.Length], startDate, "ZAR.JIBAR.3M", Interpolator1DType.LinearFlatExtrap)
            {
                SolveStage = 0
            };

            var engine = new FundingModel(startDate, new IrCurve[] { ZARcurve3m });

            var S = new NewtonRaphsonMultiCurveSolverStagedWithAnalyticJacobian();

            //var S = new NewtonRaphsonMultiCurveSolverStaged();
            S.Solve(engine, FIC);

            foreach (var ins in FIC)
            {
                var pv = ins.Pv(engine, false);
                Assert.Equal(0.0, pv, 7);
            }
        }
Exemple #2
0
        private DateTime GetNextResetDate(DateTime currentReset, bool fwdDirection)
        {
            if (RollDay == "IMM")
            {
                return(fwdDirection ? currentReset.GetNextImmDate() : currentReset.GetPrevImmDate());
            }
            if (RollDay == "EOM")
            {
                if (fwdDirection)
                {
                    var d1 = currentReset.AddPeriod(ResetRollType, ResetCalendar, ResetFrequency);
                    return(d1.LastDayOfMonth().AddPeriod(RollType.P, ResetCalendar, 0.Bd()));
                }
                else
                {
                    var d1 = currentReset.SubtractPeriod(ResetRollType, ResetCalendar, ResetFrequency);
                    return(d1.LastDayOfMonth().AddPeriod(RollType.P, ResetCalendar, 0.Bd()));
                }
            }

            if (int.TryParse(RollDay, out var rollOut))
            {
                if (fwdDirection)
                {
                    var d1 = currentReset.AddPeriod(ResetRollType, ResetCalendar, ResetFrequency);
                    return(new DateTime(d1.Year, d1.Month, rollOut).AddPeriod(ResetRollType, ResetCalendar, 0.Bd()));
                }
                else
                {
                    var d1 = currentReset.SubtractPeriod(ResetRollType, ResetCalendar, ResetFrequency);
                    return(new DateTime(d1.Year, d1.Month, rollOut).AddPeriod(ResetRollType, ResetCalendar, 0.Bd()));
                }
            }
            return(fwdDirection ? currentReset.AddPeriod(ResetRollType, ResetCalendar, ResetFrequency) : currentReset.SubtractPeriod(ResetRollType, ResetCalendar, ResetFrequency));
        }
Exemple #3
0
        public void BasicSelfDiscounting()
        {
            var startDate  = new DateTime(2016, 05, 20);
            var swapTenor2 = new Frequency("2y");
            var jhb        = TestProviderHelper.CalendarProvider.Collection["JHB"];

            var pillarDate     = startDate.AddPeriod(RollType.MF, jhb, 1.Years());
            var pillarDate2    = startDate.AddPeriod(RollType.MF, jhb, swapTenor2);
            var pillarDateDepo = startDate.AddPeriod(RollType.MF, jhb, 3.Months());

            var ccyZar = TestProviderHelper.CurrencyProvider["JHB"];

            var zar3m = new FloatRateIndex()
            {
                Currency           = ccyZar,
                DayCountBasis      = DayCountBasis.Act_365F,
                DayCountBasisFixed = DayCountBasis.Act_365F,
                ResetTenor         = 3.Months(),
                FixingOffset       = 0.Bd(),
                HolidayCalendars   = jhb,
                RollConvention     = RollType.MF
            };

            var swap  = new IrSwap(startDate, 1.Years(), zar3m, 0.06, SwapPayReceiveType.Payer, "ZAR.JIBAR.3M", "ZAR.JIBAR.3M");
            var swap2 = new IrSwap(startDate, swapTenor2, zar3m, 0.06, SwapPayReceiveType.Payer, "ZAR.JIBAR.3M", "ZAR.JIBAR.3M");
            var depo  = new IrSwap(startDate, 3.Months(), zar3m, 0.06, SwapPayReceiveType.Payer, "ZAR.JIBAR.3M", "ZAR.JIBAR.3M");

            var fic = new FundingInstrumentCollection(TestProviderHelper.CurrencyProvider)
            {
                swap,
                swap2,
                depo
            };
            var curve = new IrCurve(new [] { pillarDateDepo, pillarDate, pillarDate2 }, new double[3], startDate, "ZAR.JIBAR.3M", Interpolator1DType.LinearFlatExtrap, ccyZar);
            var model = new FundingModel(startDate, new[] { curve }, TestProviderHelper.CurrencyProvider, TestProviderHelper.CalendarProvider);

            var s = new Calibrators.NewtonRaphsonMultiCurveSolver();

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

            s.Solve(model, fic);

            var resultSwap1 = swap.Pv(model, false);
            var resultSwap2 = swap2.Pv(model, false);
            var resultDepo  = depo.Pv(model, false);

            if (!IsCoverageOnly)
            {
                Assert.Equal(0, resultSwap1, 6);
                Assert.Equal(0, resultSwap2, 6);
                Assert.Equal(0, resultDepo, 6);
            }
        }
Exemple #4
0
        public ForwardRateAgreement(DateTime valDate, string fraCode, double parRate, FloatRateIndex rateIndex, SwapPayReceiveType payRec, FraDiscountingType fraType, string forecastCurve, string discountCurve)
        {
            var code = fraCode.ToUpper().Split('X');

            StartDate = valDate.AddPeriod(rateIndex.RollConvention, rateIndex.HolidayCalendars, new Frequency(code[0] + "M"));
            ResetDate = StartDate.AddPeriod(RollType.P, rateIndex.HolidayCalendars, rateIndex.FixingOffset);
            EndDate   = new TenorDateRelative(rateIndex.ResetTenor);

            ParRate = parRate;
            Basis   = rateIndex.DayCountBasis;
            PayRec  = payRec;

            FraLeg = new GenericSwapLeg(StartDate, EndDate.Date(StartDate, rateIndex.RollConvention, rateIndex.HolidayCalendars), rateIndex.HolidayCalendars, rateIndex.Currency, rateIndex.ResetTenor, Basis)
            {
                FixedRateOrMargin = (decimal)ParRate
            };
            FlowScheduleFra = FraLeg.GenerateSchedule();

            FraLeg.FixedRateOrMargin            = (decimal)ParRate;
            FraLeg.LegType                      = SwapLegType.Fra;
            FlowScheduleFra.Flows[0].SettleDate = StartDate;
            ForecastCurve = forecastCurve;
            DiscountCurve = discountCurve;

            FraType = fraType;
        }
        public MunicipalityTax Create(string name, DateTime date, Period period, decimal tax)
        {
            var municipality = _municipalitiesRepository.GetAllItems().FirstOrDefault(a => a.Name == name);

            if (municipality == default(Municipality))
            {
                municipality = new Municipality
                {
                    Name = name
                };
            }

            var municipalityTax = new MunicipalityTax
            {
                TaxPeriod = new TaxPeriod
                {
                    DateFrom = date.Date,
                    DateTo   = date.AddPeriod(period),
                    Period   = period
                },
                Municipality = municipality,
                Tax          = tax
            };

            return(_taxesRepository.AddOrUpdate(municipalityTax));
        }
Exemple #6
0
        public static AsianOption CreateAsianOption(DateTime start, DateTime end, double strike, string assetId, OptionType putCall, Calendar fixingCalendar, Calendar payCalendar, Frequency payOffset, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
        {
            var fixingDates = start == end ? new List <DateTime> {
                start
            } :
            fixingDateType == DateGenerationType.BusinessDays ?
            start.BusinessDaysInPeriod(end, fixingCalendar) :
            start.FridaysInPeriod(end, fixingCalendar);

            return(new AsianOption
            {
                AssetId = assetId,
                AverageStartDate = start,
                AverageEndDate = end,
                FixingCalendar = fixingCalendar,
                Strike = strike,
                FixingDates = fixingDates.ToArray(),
                SpotLag = spotLag,
                CallPut = putCall,
                PaymentCalendar = payCalendar,
                PaymentLag = payOffset,
                PaymentDate = end.AddPeriod(RollType.F, fixingCalendar, payOffset),
                PaymentCurrency = currency,
                Direction = tradeDirection,
                Notional = notional,
                FxConversionType = currency.Ccy == "USD" ? FxConversionType.None : FxConversionType.AverageThenConvert
            });
        }
Exemple #7
0
        /// <summary>
        /// Returns spot date for a given val date
        /// e.g. for USD/ZAR, calendar would be for ZAR and otherCal would be for USD
        /// </summary>
        /// <param name="valDate"></param>
        /// <param name="spotLag"></param>
        /// <param name="calendar"></param>
        /// <param name="otherCal"></param>
        /// <returns></returns>
        public static DateTime SpotDate(this FxPair fxPair, DateTime valDate)
        {
            var d = valDate.AddPeriod(RollType.F, fxPair.PrimaryCalendar, fxPair.SpotLag);

            d = d.IfHolidayRollForward(fxPair.SecondaryCalendar);
            return(d);
        }
Exemple #8
0
        /// <summary>
        /// Returns spot date for a given val date
        /// e.g. for USD/ZAR, calendar would be for ZAR and otherCal would be for USD
        /// </summary>
        /// <param name="valDate"></param>
        /// <param name="spotLag"></param>
        /// <param name="calendar"></param>
        /// <param name="otherCal"></param>
        /// <returns></returns>
        public static DateTime SpotDate(this DateTime valDate, Frequency spotLag, Calendar calendar, Calendar otherCal)
        {
            var d = valDate.AddPeriod(RollType.F, calendar, spotLag);

            d = d.IfHolidayRollForward(otherCal);
            return(d);
        }
Exemple #9
0
        private void FeedPrevious(DateTime dateTime)
        {
            DateTime previous = dateTime.AddPeriod(Period, PeriodCount, -1);

            if (_begin >= dateTime)
            {
                return;
            }

            if (_list.ContainsKey(previous))
            {
                return;
            }

            while (!_list.ContainsKey(previous))
            {
                previous = previous.AddPeriod(Period, PeriodCount, -1);
            }

            Candle lastCandle = _list[previous];

            foreach (DateTime date in previous.GetPeriods(dateTime, Period, PeriodCount))
            {
                if (!_list.ContainsKey(date))
                {
                    _list[date] = Candle.CreateZeroCandle(lastCandle, date);
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Calculates the next payment date for this instance.
        /// </summary>
        /// <param name="fromDate"></param>
        /// <returns>The next date for payment or null if there are no more payments</returns>
        public DateTime?NextDue(DateTime fromDate)
        {
            // Have payments started?
            if (fromDate < this.StartDate)
            {
                return(this.StartDate);
            }
            // Have payments finished?
            if (fromDate > this.EndDate)
            {
                return(null);
            }

            // Initialise to last payment
            DateTime payDate = (DateTime)this.LastDue(fromDate);

            // Calculate next date after fromDate
            payDate = payDate.AddPeriod(this.Frequency, this.Period);
            if (payDate > this.EndDate)
            {
                return(this.EndDate);
            }
            else
            {
                return(payDate);
            }
        }
        private void AddedCandle(object sender, Candle addedCandle)
        {
            DateTime eventTime = addedCandle.DateTime;
            DateTime startTime = eventTime.AddPeriod(_collection.Period, _collection.PeriodCount, -_periodCount);

            var candles = _collection.GetCandles(startTime, eventTime);

            if (candles.Count() < _periodCount)
            {
                return;
            }

            Candle startCandle = candles.First();

            decimal longPip  = candles.Max(c => c.Close) - startCandle.Open;
            decimal shortPip = startCandle.Open - candles.Min(c => c.Close);

            longPip  = longPip < 0 ? 0 : longPip * 10000;
            shortPip = shortPip < 0 ? 0 : shortPip * 10000;

            _futurPip[startTime] = new PipWin()
            {
                Short = shortPip,
                Long  = longPip
            };
        }
Exemple #12
0
        public IrSwap(DateTime startDate, Frequency swapTenor, FloatRateIndex rateIndex, double parRate,
                      SwapPayReceiveType swapType, string forecastCurve, string discountCurve)
        {
            SwapTenor      = swapTenor;
            ResetFrequency = rateIndex.ResetTenor;
            StartDate      = startDate;
            EndDate        = StartDate.AddPeriod(rateIndex.RollConvention, rateIndex.HolidayCalendars, SwapTenor);
            ParRate        = parRate;
            BasisFloat     = rateIndex.DayCountBasis;
            BasisFixed     = rateIndex.DayCountBasisFixed;
            SwapType       = swapType;

            FixedLeg = new GenericSwapLeg(StartDate, swapTenor, rateIndex.HolidayCalendars, rateIndex.Currency,
                                          ResetFrequency, BasisFixed)
            {
                FixedRateOrMargin = (decimal)parRate,
                LegType           = SwapLegType.Fixed,
                Nominal           = 1e6M * (swapType == SwapPayReceiveType.Payer ? -1.0M : 1.0M)
            };
            FloatLeg = new GenericSwapLeg(StartDate, swapTenor, rateIndex.HolidayCalendars, rateIndex.Currency,
                                          ResetFrequency, BasisFloat)
            {
                FixedRateOrMargin = 0.0M,
                LegType           = SwapLegType.Float,
                Nominal           = 1e6M * (swapType == SwapPayReceiveType.Payer ? 1.0M : -1.0M)
            };
            FlowScheduleFixed = FixedLeg.GenerateSchedule();
            FlowScheduleFloat = FloatLeg.GenerateSchedule();

            ResetDates = FlowScheduleFloat.Flows.Select(x => x.FixingDateStart).ToArray();

            ForecastCurve = forecastCurve;
            DiscountCurve = discountCurve;
        }
Exemple #13
0
        public void LME3mRule()
        {
            var calendar = new Calendar();

            calendar.DaysToAlwaysExclude.Add(DayOfWeek.Saturday);
            calendar.DaysToAlwaysExclude.Add(DayOfWeek.Sunday);

            var date      = new DateTime(2017, 01, 30);
            var lme3mDate = date.AddPeriod(RollType.LME, calendar, new Frequency("3m"));

            Assert.Equal(new DateTime(2017, 04, 28), lme3mDate);

            //easter 2017
            calendar.DaysToExclude.Add(new DateTime(2017, 04, 14));
            calendar.DaysToExclude.Add(new DateTime(2017, 04, 17));

            date      = new DateTime(2017, 01, 14);
            lme3mDate = date.AddPeriod(RollType.LME, calendar, new Frequency("3m"));
            Assert.Equal(new DateTime(2017, 04, 13), lme3mDate);

            date      = new DateTime(2017, 01, 15);
            lme3mDate = date.AddPeriod(RollType.LME, calendar, new Frequency("3m"));
            Assert.Equal(new DateTime(2017, 04, 13), lme3mDate);

            date      = new DateTime(2017, 01, 16);
            lme3mDate = date.AddPeriod(RollType.LME, calendar, new Frequency("3m"));
            Assert.Equal(new DateTime(2017, 04, 18), lme3mDate);
        }
Exemple #14
0
        public ForwardRateAgreement(DateTime startDate, double parRate, FloatRateIndex rateIndex, SwapPayReceiveType payRec, FraDiscountingType fraType, string forecastCurve, string discountCurve)
        {
            StartDate = startDate;
            ResetDate = StartDate.AddPeriod(RollType.P, rateIndex.HolidayCalendars, rateIndex.FixingOffset);
            EndDate   = new TenorDateRelative(rateIndex.ResetTenor);
            RateIndex = rateIndex;
            ParRate   = parRate;
            Basis     = rateIndex.DayCountBasis;
            PayRec    = payRec;

            FraLeg = new GenericSwapLeg(StartDate, EndDate.Date(StartDate, rateIndex.RollConvention, rateIndex.HolidayCalendars), rateIndex.HolidayCalendars, rateIndex.Currency, rateIndex.ResetTenor, Basis)
            {
                FixedRateOrMargin = (decimal)ParRate
            };
            FlowScheduleFra = FraLeg.GenerateSchedule();

            FraLeg.FixedRateOrMargin            = (decimal)ParRate;
            FraLeg.LegType                      = SwapLegType.Fra;
            FlowScheduleFra.Flows[0].SettleDate = StartDate;
            ForecastCurve = forecastCurve;
            DiscountCurve = discountCurve;

            FraType    = fraType;
            PillarDate = FlowScheduleFra.Flows[0].AccrualPeriodEnd;
        }
        public static double CalculateAnnuity(
            DateTime repaymentPeriodStartDate,
            DateTime firstInstallmentDate,
            int numberOfInstallments,
            int installmentFrequencyPeriod,
            SimpleUnitOfTime installmentFrequencyUnitOfTime,
            double ratePercentage,
            SimpleUnitOfTime rateUnitOfTime,
            bool isCompound,
            CalendarBasisKind calendarBasis,
            double principalAmount,
            bool adjustFirstInstallment = false)
        {
            DateTime d2 = firstInstallmentDate.AddPeriod(installmentFrequencyPeriod * (numberOfInstallments - 1), installmentFrequencyUnitOfTime);

            double   dummyAnnuity = 100;
            double   outstanding  = 0;
            double   basis        = 0;
            double   interest     = 0;
            DateTime d1;

            while (d2 > firstInstallmentDate)
            {
                d1          = d2.AddPeriod(-installmentFrequencyPeriod, installmentFrequencyUnitOfTime);
                basis       = outstanding + dummyAnnuity;
                interest    = InterestCalculation.CalculateInterest(d2, d1, d1, ratePercentage, rateUnitOfTime.CharLiteral(), isCompound, calendarBasis, basis).Sum(it => it.Interest);
                outstanding = basis + interest;
                d2          = d1;
            }

            d1 = repaymentPeriodStartDate;

            if (adjustFirstInstallment)
            {
                var prevDate = firstInstallmentDate.AddPeriod(-installmentFrequencyPeriod, installmentFrequencyUnitOfTime);
                if (prevDate < repaymentPeriodStartDate)
                {
                    d1 = prevDate;
                }
            }
            basis       = outstanding + dummyAnnuity;
            interest    = InterestCalculation.CalculateInterest(d2, d1, d1, ratePercentage, rateUnitOfTime.CharLiteral(), isCompound, calendarBasis, basis).Sum(it => it.Interest);
            outstanding = basis + interest;

            return(principalAmount / outstanding * dummyAnnuity);
        }
Exemple #16
0
 public FXUnderlying(Frequency spotLag, Calendar holidays, DateTime originDate, double spot, ICurve domesticCurve, ICurve foreignCurve)
 {
     SpotLag       = spotLag;
     Spot          = spot;
     DomesticCurve = domesticCurve;
     ForeignCurve  = foreignCurve;
     Holidays      = holidays;
     OriginDate    = originDate;
     SpotDate      = OriginDate.AddPeriod(RollType.F, Holidays, SpotLag);
 }
Exemple #17
0
        public static Dictionary <DateTime, double> Downsample(Dictionary <DateTime, double> curvePoints, DateTime valDate, Calendar calendar)
        {
            var tenors  = new[] { "1b", "1w", "2w", "3w", "1m", "2m", "3m", "4m", "5m", "6m", "9m", "12m", "15m", "18m", "24m", "30m", "36m", "42m", "48m", "54m", "60m" };
            var dates   = tenors.Select(t => valDate.AddPeriod(t.EndsWith("m") ? RollType.MF : RollType.F, calendar, new Frequency(t)));
            var p       = curvePoints.Keys.OrderBy(x => x).ToList();
            var ixs     = dates.Select(d => p.BinarySearch(d)).Select(x => x < 0 ? ~x : x).Where(x => x < p.Count()).Distinct().ToArray();
            var smaller = ixs.ToDictionary(x => p[x], x => curvePoints[p[x]]);

            return(smaller);
        }
Exemple #18
0
        public double GetVolForStrikeAndDate(string name, DateTime expiry, double strike)
        {
            var surface = GetVolSurface(name);
            var curve   = GetPriceCurve(name);
            var fwd     = surface.OverrideSpotLag == null?
                          curve.GetPriceForFixingDate(expiry) :
                              curve.GetPriceForDate(expiry.AddPeriod(RollType.F, curve.SpotCalendar, surface.OverrideSpotLag));

            var vol = surface.GetVolForAbsoluteStrike(strike, expiry, fwd);

            return(vol);
        }
Exemple #19
0
        public XccyBasisSwap(DateTime startDate, Frequency swapTenor, double parSpread, bool spreadOnPayLeg, FloatRateIndex payIndex, FloatRateIndex recIndex, ExchangeType notionalExchange, MTMSwapType mtmSwapType, string forecastCurvePay, string forecastCurveRec, string discountCurvePay, string discountCurveRec)
        {
            SwapTenor        = swapTenor;
            NotionalExchange = notionalExchange;
            MtmSwapType      = mtmSwapType;
            RateIndexPay     = payIndex;
            RateIndexRec     = recIndex;

            ResetFrequencyRec = recIndex.ResetTenor;
            ResetFrequencyPay = payIndex.ResetTenor;

            StartDate = startDate;
            EndDate   = StartDate.AddPeriod(payIndex.RollConvention, payIndex.HolidayCalendars, SwapTenor);

            ParSpreadPay = spreadOnPayLeg ? parSpread : 0.0;
            ParSpreadRec = spreadOnPayLeg ? 0.0 : parSpread;
            BasisPay     = payIndex.DayCountBasis;
            BasisRec     = recIndex.DayCountBasis;

            CcyPay = payIndex.Currency;
            CcyRec = recIndex.Currency;

            PayLeg = new GenericSwapLeg(StartDate, swapTenor, payIndex.HolidayCalendars, payIndex.Currency, ResetFrequencyPay, BasisPay)
            {
                FixedRateOrMargin = (decimal)ParSpreadPay,
                NotionalExchange  = NotionalExchange,
                Direction         = SwapPayReceiveType.Payer,
                LegType           = SwapLegType.Float
            };
            RecLeg = new GenericSwapLeg(StartDate, swapTenor, recIndex.HolidayCalendars, recIndex.Currency, ResetFrequencyRec, BasisRec)
            {
                FixedRateOrMargin = (decimal)ParSpreadRec,
                NotionalExchange  = NotionalExchange
            };
            PayLeg.Direction = SwapPayReceiveType.Receiver;
            RecLeg.LegType   = SwapLegType.Float;


            FlowSchedulePay = PayLeg.GenerateSchedule();
            FlowScheduleRec = RecLeg.GenerateSchedule();

            ResetDates = FlowSchedulePay.Flows.Select(x => x.FixingDateStart)
                         .Union(FlowScheduleRec.Flows.Select(y => y.FixingDateStart))
                         .Distinct()
                         .OrderBy(x => x)
                         .ToArray();

            ForecastCurvePay = forecastCurvePay;
            ForecastCurveRec = forecastCurveRec;
            DiscountCurvePay = discountCurvePay;
            DiscountCurveRec = discountCurveRec;
        }
Exemple #20
0
        public void TSMC_PathsGenerated()
        {
            var origin = new DateTime(2019, 06, 28);
            var engine = new PathEngine(2.IntPow(IsCoverageOnly ? 6 : 17));

            engine.AddPathProcess(new Random.MersenneTwister.MersenneTwister64()
            {
                UseNormalInverse = true,
                UseAnthithetic   = true
            });

            var tenorsStr = new[] { "1m", "2m", "3m", "6m", "9m", "1y" };
            var tenors    = tenorsStr.Select(x => new Frequency(x));
            var expiries  = tenors.Select(t => origin.AddPeriod(RollType.F, new Calendar(), t)).ToArray();
            var deltaKs   = new[] { 0.1, 0.25, 0.5, 0.75, 0.9 };
            var smileVols = new[] { 0.32, 0.3, 0.29, 0.3, 0.32 };
            var vols      = Enumerable.Repeat(smileVols, expiries.Length).ToArray();

            var volSurface = new GridVolSurface(origin, deltaKs, expiries, vols,
                                                StrikeType.ForwardDelta, Interpolator1DType.GaussianKernel,
                                                Interpolator1DType.LinearInVariance, DayCountBasis.Act365F);

            var fwdCurve = new Func <double, double>(t => { return(900 + 100 * t); });
            var asset    = new TurboSkewSingleAsset
                           (
                startDate: origin,
                expiryDate: origin.AddYears(1),
                volSurface: volSurface,
                forwardCurve: fwdCurve,
                nTimeSteps: 1,
                name: "TestAsset"
                           );

            engine.AddPathProcess(asset);
            var payoff  = new EuropeanPut("TestAsset", 900, origin.AddYears(1));
            var payoff2 = new EuropeanCall("TestAsset", 0, origin.AddYears(1));

            engine.AddPathProcess(payoff);
            engine.AddPathProcess(payoff2);
            engine.SetupFeatures();
            engine.RunProcess();
            var pv       = payoff.AverageResult;
            var blackVol = volSurface.GetVolForAbsoluteStrike(900, origin.AddYears(1), fwdCurve(1.0));
            var blackPv  = BlackFunctions.BlackPV(1000, 900, 0, 1, blackVol, OptionType.P);

            if (!IsCoverageOnly)
            {
                Assert.Equal(blackPv, pv, 0);
                var fwd = payoff2.AverageResult;
                Assert.True(System.Math.Abs(fwdCurve(1) / fwd - 1.0) < 0.002);
            }
        }
Exemple #21
0
        public static object GetLME3mDate(
            [ExcelArgument(Description = "Value date")] DateTime ValueDate)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                ContainerStores.
                SessionContainer.
                GetService <ICalendarProvider>().
                Collection.
                TryGetCalendar("LON+NYC", out var cal);

                return ValueDate.AddPeriod(RollType.LME_Nearest, cal, new Frequency(3, DatePeriodType.M));
            }));
        }
Exemple #22
0
        public IrBasisSwap(DateTime startDate, Frequency swapTenor, double parSpread, bool spreadOnPayLeg, FloatRateIndex payIndex, FloatRateIndex recIndex, string forecastCurvePay, string forecastCurveRec, string discountCurve, decimal?notional = null) : base()
        {
            SwapTenor = swapTenor;

            ResetFrequencyRec = recIndex.ResetTenor;
            ResetFrequencyPay = payIndex.ResetTenor;

            PayIndex = payIndex;
            RecIndex = recIndex;

            StartDate = startDate;
            EndDate   = StartDate.AddPeriod(payIndex.RollConvention, payIndex.HolidayCalendars, SwapTenor);

            ParSpreadPay = spreadOnPayLeg ? parSpread : 0.0;
            ParSpreadRec = spreadOnPayLeg ? 0.0 : parSpread;
            BasisPay     = payIndex.DayCountBasis;
            BasisRec     = recIndex.DayCountBasis;
            Notional     = (double)(notional ?? 1e6M);

            PayLeg = new GenericSwapLeg(StartDate, swapTenor, payIndex.HolidayCalendars, payIndex.Currency, ResetFrequencyPay, BasisPay)
            {
                FixedRateOrMargin = (decimal)ParSpreadPay,
                LegType           = SwapLegType.Float,
                Nominal           = -(notional ?? 1e6M),
                AccrualDCB        = payIndex.DayCountBasis
            };

            RecLeg = new GenericSwapLeg(StartDate, swapTenor, recIndex.HolidayCalendars, recIndex.Currency, ResetFrequencyRec, BasisRec)
            {
                FixedRateOrMargin = (decimal)ParSpreadRec,
                LegType           = SwapLegType.Float,
                Nominal           = notional ?? 1e6M,
                AccrualDCB        = recIndex.DayCountBasis
            };


            FlowSchedulePay = PayLeg.GenerateSchedule();
            FlowScheduleRec = RecLeg.GenerateSchedule();

            ResetDates = FlowSchedulePay.Flows.Select(x => x.FixingDateStart)
                         .Union(FlowScheduleRec.Flows.Select(y => y.FixingDateStart))
                         .Distinct()
                         .OrderBy(x => x)
                         .ToArray();

            ForecastCurvePay = forecastCurvePay;
            ForecastCurveRec = forecastCurveRec;
            DiscountCurve    = discountCurve;
        }
        public void Finish(IFeatureCollection collection)
        {
            var dims = collection.GetFeature <IPathMappingFeature>();

            _assetIndex = dims.GetDimension(_assetName);

            if (!string.IsNullOrEmpty(_fxName))
            {
                _fxIndex = dims.GetDimension(_fxName);
            }

            var dates = collection.GetFeature <ITimeStepsFeature>();

            _dateIndexes = _avgDates
                           .Select(x => x.Select(y => dates.GetDateIndex(y)).ToArray())
                           .ToList();
            _dateIndexesPast = _avgDates
                               .Select(y => y
                                       .Where(x => x <= _decisionDate)
                                       .Select(x => dates.GetDateIndex(x))
                                       .ToArray())
                               .ToList();
            _dateIndexesFuture = _avgDates
                                 .Select(y => y
                                         .Where(x => x > _decisionDate)
                                         .Select(x => dates.GetDateIndex(x))
                                         .ToArray())
                                 .ToList();
            _decisionDateIx = dates.GetDateIndex(_decisionDate);

            _nPast   = _dateIndexesPast.Select(x => x.Length).ToArray();
            _nFuture = _dateIndexesFuture.Select(x => x.Length).ToArray();
            _nTotal  = _nPast.Select((x, ix) => x + _nFuture[ix]).ToArray();

            var engine = collection.GetFeature <IEngineFeature>();

            _results = new Vector <double> [engine.NumberOfPaths / Vector <double> .Count];

            if (VanillaModel != null)
            {
                var curve            = VanillaModel.GetPriceCurve(_assetName);
                var decisionSpotDate = _decisionDate.AddPeriod(RollType.F, curve.SpotCalendar, curve.SpotLag);
                _expiryToSettleCarry = curve.GetPriceForDate(_payDate) / curve.GetPriceForDate(decisionSpotDate);
            }

            _isComplete = true;
        }
Exemple #24
0
        internal void InitializeEvaluation(ITransformer transformer)
        {
            _evaluation = new Dictionary <DateTime, float>();
            DateTime from = _featurables.Min(c => c.Begin);
            //to = _featurables.Max(c => c.End);
            Period period      = Period.S;
            int    periodCount = 5;

            List <Dictionary <string, float> > features = new List <Dictionary <string, float> >();

            for (DateTime date = from; date < DateTime.Now; date = date.AddPeriod(period, periodCount))
            {
                if (_featurables.All(c => c.HasFeatures(date)))
                {
                    Dictionary <string, float> feature = new Dictionary <string, float>();
                    var featuresDictionnary            = GetFeatures(date);

                    if (featuresDictionnary == null)
                    {
                        continue;
                    }

                    foreach (var item in featuresDictionnary)
                    {
                        feature.Add(item.Key, item.Value);
                    }
                    feature["Label"] = 0;
                    features.Add(feature);
                    _evaluation[date] = 0;
                }
            }

            IDataView data   = new FloatsDataView(features);
            IDataView result = transformer.Transform(data);

            float[] scoreColumn = result.GetColumn <float>("Score").ToArray();

            int iterator = 0;

            for (DateTime date = from; date < DateTime.Now; date = date.AddPeriod(period, periodCount))
            {
                if (_evaluation.ContainsKey(date))
                {
                    _evaluation[date] = scoreColumn[iterator++];
                }
            }
        }
Exemple #25
0
        public static object NextLMECurveDate(
            [ExcelArgument(Description = "Previous date")] DateTime PrevDate,
            [ExcelArgument(Description = "3m date")] DateTime ThreeMonthDate,
            [ExcelArgument(Description = "Whether all daily expiries are required")] bool DailyExpiries)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                ContainerStores.
                SessionContainer.
                GetService <ICalendarProvider>().
                Collection.
                TryGetCalendar("LON+NYC", out var cal);

                if (DailyExpiries)
                {
                    if (PrevDate < ThreeMonthDate)
                    {
                        return PrevDate.AddPeriod(RollType.F, cal, new Frequency(1, DatePeriodType.B));
                    }

                    if (PrevDate < ThreeMonthDate.AddMonths(3))
                    {
                        return PrevDate.GetNextWeekday(DayOfWeek.Wednesday).IfHolidayRollForward(cal);
                    }

                    if (PrevDate < PrevDate.ThirdWednesday())
                    {
                        return PrevDate.ThirdWednesday();
                    }

                    return PrevDate.AddMonths(1).ThirdWednesday();
                }
                else
                {
                    var next3w = (PrevDate < PrevDate.ThirdWednesday()) ?
                                 PrevDate.ThirdWednesday() :
                                 PrevDate.AddMonths(1).ThirdWednesday();

                    if (PrevDate < ThreeMonthDate && next3w > ThreeMonthDate)
                    {
                        return ThreeMonthDate;
                    }

                    return next3w;
                }
            }));
        }
Exemple #26
0
        public static object QDates_AddPeriod(
            [ExcelArgument(Description = "Starting date")] DateTime StartDate,
            [ExcelArgument(Description = "Period specified as a string e.g. 1w")] string Period,
            [ExcelArgument(Description = "Roll method")] string RollMethod,
            [ExcelArgument(Description = "Calendar(s) to check against")] string Calendar)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                if (!ValidateCalendarAndRoll(RollMethod, Calendar, out var rollMethod, out var cal, out var errorMessage))
                {
                    return errorMessage;
                }

                if (!Frequency.TryParse(Period, out var period))
                {
                    return $"Could not parse period {Period}";
                }

                return StartDate.AddPeriod(rollMethod, cal, period);
            }));
Exemple #27
0
        public DateTime GetExpiry()
        {
            var baseYear = (int)Math.Floor(YearBeforeWhich2DigitDatesAreUsed / 10.0) * 10;
            var monthNum = s_futureMonths.ToList().IndexOf(MonthCode) + 1;

            var dayOfMonthToStart = _settings.ExpiryGen.DayOfMonthToStart;

            if (_settings.ExpiryGen.DayOfMonthToStart == 0 && !string.IsNullOrWhiteSpace(_settings.ExpiryGen.DayOfMonthToStartOther))
            {
                switch (_settings.ExpiryGen.DayOfMonthToStartOther)
                {
                case "WED3":
                    var dateInMonth = new DateTime(YearNumber, monthNum, 1);
                    dayOfMonthToStart = dateInMonth.NthSpecificWeekDay(DayOfWeek.Wednesday, 3).Day;
                    break;

                case "LASTFRI":
                    var dateInMonth1 = new DateTime(YearNumber, monthNum, 1);
                    dayOfMonthToStart = dateInMonth1.NthLastSpecificWeekDay(DayOfWeek.Friday, 1)
                                        .IfHolidayRollBack(_settings.RollGen.CalendarObject)
                                        .Day;
                    break;

                default:
                    throw new Exception($"Dont know how to handle date code {_settings.ExpiryGen.DayOfMonthToStartOther}");
                }
            }
            var d = new DateTime(YearNumber, monthNum, dayOfMonthToStart);

            d = d.AddMonths(_settings.ExpiryGen.MonthModifier);
            var parts = _settings.ExpiryGen.DateOffsetModifier.Split(';');

            foreach (var part in parts)
            {
                d = d.AddPeriod(RollType.P, _settings.ExpiryGen.CalendarObject, new Frequency(part));
            }

            return(d);
        }
        public static object QDates_AddPeriod(
            [ExcelArgument(Description = "Starting date")] DateTime StartDate,
            [ExcelArgument(Description = "Period specified as a string e.g. 1w")] string Period,
            [ExcelArgument(Description = "Roll method")] string RollMethod,
            [ExcelArgument(Description = "Calendar(s) to check against")] string Calendar)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                if (!ContainerStores.SessionContainer.GetService <ICalendarProvider>().Collection.TryGetCalendar(Calendar, out Calendar cal))
                {
                    return $"Calendar {Calendar} not found in cache";
                }

                if (!Enum.TryParse(RollMethod, out RollType rollMethod))
                {
                    return $"Unknown roll method {RollMethod}";
                }

                Frequency period = new Frequency(Period);

                return StartDate.AddPeriod(rollMethod, cal, period);
            }));
        }
Exemple #29
0
        public static object QDates_AddPeriod(
            [ExcelArgument(Description = "Starting date")] DateTime StartDate,
            [ExcelArgument(Description = "Period specified as a string e.g. 1w")] string Period,
            [ExcelArgument(Description = "Roll method, default following")] object RollMethod,
            [ExcelArgument(Description = "Calendar(s) to check against, default Weekends")] object Calendar)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                var _rollMethod = RollMethod.OptionalExcel("F");
                var _calendar = Calendar.OptionalExcel("Weekends");

                if (!ValidateCalendarAndRoll(_rollMethod, _calendar, out var rollMethod, out var cal, out var errorMessage))
                {
                    return errorMessage;
                }

                if (!Frequency.TryParse(Period, out var period))
                {
                    return $"Could not parse period {Period}";
                }

                return StartDate.AddPeriod(rollMethod, cal, period);
            }));
Exemple #30
0
        protected override void ReceiveCandles(Candle[] candles, DateTime dateTime)
        {
            int beginIdx = 0;
            int count    = candles.Length;

            double[] k = new double[candles.Length];
            double[] d = new double[candles.Length];

            Core.Stoch(0, candles.Length - 1,
                       candles.Select(c => (float)c.High).ToArray(),
                       candles.Select(c => (float)c.Low).ToArray(),
                       candles.Select(c => (float)c.Close).ToArray(),
                       5, 3, Core.MAType.Sma, 3, Core.MAType.Sma, out beginIdx, out count, k, d);

            _statistics[dateTime] = new Stochastic()
            {
                K = k[0],
                D = d[0]
            };

            if (_statistics.Count() >= candles.Length)
            {
                for (int i = 0; i < candles.Length; i++)
                {
                    dateTime = dateTime.AddPeriod(Period, PeriodCount, -1);
                    if (!_statistics.ContainsKey(dateTime))
                    {
                        _statistics[dateTime] = new Stochastic()
                        {
                            K = k[i],
                            D = d[i]
                        };
                    }
                }
            }
        }