public FRACurveInstrument(Tenor startTenor, Tenor endTenor, FloatRateIndex floatRateIndex, double simpleRate)
 {
     _startTenor     = startTenor;
     _endTenor       = endTenor;
     _floatRateIndex = floatRateIndex;
     _simpleRate     = simpleRate;
     _floatingRateSourceDescription = new FloatingRateSourceDescription(floatRateIndex);
 }
 /// <summary>
 /// Will use the discount factors to obtain the forward rates after the curve's anchor date and the fixing curve before
 /// that date.
 /// </summary>
 /// <param name="discountCurve"></param>
 /// <param name="index"></param>
 /// <param name="fixingCurve"></param>
 public ForecastCurveFromDiscount(IDiscountingSource discountCurve, FloatRateIndex index,
                                  IFloatingRateSource fixingCurve)
 {
     _discountCurve = discountCurve;
     _index         = index;
     _fixingCurve   = fixingCurve;
     _name          = new FloatingRateSourceDescription(index).Name;
 }
Esempio n. 3
0
        public void BasicRiskMatrixFacts()
        {
            var model = GenerateTestData();
            var zar   = TestProviderHelper.CurrencyProvider.GetCurrency("ZAR");
            var usd   = TestProviderHelper.CurrencyProvider.GetCurrency("USD");
            var ix    = new FloatRateIndex
            {
                Currency           = usd,
                DayCountBasis      = DayCountBasis.Act365F,
                DayCountBasisFixed = DayCountBasis.Act365F,
                FixingOffset       = 0.Bd(),
                ResetTenor         = 3.Months(),
                ResetTenorFixed    = 3.Months(),
                RollConvention     = RollType.F
            };

            var f1 = new STIRFuture
            {
                ContractSize  = 1e6,
                Currency      = usd,
                DCF           = 0.25,
                Expiry        = _originDate.AddDays(1),
                Position      = 1.0,
                Index         = ix,
                ForecastCurve = "DISCO-USD",
                SolveCurve    = "DISCO-USD",
                TradeId       = "f1",
                Price         = 95,
                PillarDate    = _originDate.AddDays(90)
            };

            var f2 = new STIRFuture
            {
                ContractSize  = 1e6,
                Currency      = usd,
                DCF           = 0.25,
                Expiry        = _originDate.AddDays(90),
                Position      = 1.0,
                Index         = ix,
                ForecastCurve = "DISCO-USD",
                SolveCurve    = "DISCO-USD",
                TradeId       = "f2",
                Price         = 95,
                PillarDate    = _originDate.AddDays(180),
            };
            var fic = new FundingInstrumentCollection(TestProviderHelper.CurrencyProvider)
            {
                f1,
                f2
            };

            var cube = model.BenchmarkRisk(fic, TestProviderHelper.CurrencyProvider, usd);

            var riskSum = cube.SumOfAllRows;

            Assert.Equal(-13.0, riskSum, 0);
        }
Esempio n. 4
0
        public void IrSwap()
        {
            var bd         = DateTime.Parse("2018-09-13");
            var pillars    = new[] { bd, bd.AddDays(1000) };
            var flatRate   = 0.05;
            var rates      = pillars.Select(p => flatRate).ToArray();
            var usd        = TestProviderHelper.CurrencyProvider["USD"];
            var discoCurve = new IrCurve(pillars, rates, bd, "USD.BLAH", Interpolator1DType.Linear, usd);
            var fModel     = new FundingModel(bd, new[] { discoCurve }, TestProviderHelper.CurrencyProvider, TestProviderHelper.CalendarProvider);

            CalendarProvider.Collection.TryGetCalendar("LON", out var cal);

            var ix = new FloatRateIndex
            {
                Currency           = usd,
                DayCountBasis      = DayCountBasis.ACT360,
                DayCountBasisFixed = DayCountBasis.ACT360,
                FixingOffset       = 2.Bd(),
                HolidayCalendars   = cal,
                ResetTenor         = 3.Months(),
                ResetTenorFixed    = 3.Months(),
                RollConvention     = RollType.MF
            };


            var parRate   = 0.05;
            var notional  = 100e6;
            var startDate = bd.AddPeriod(RollType.F, cal, 2.Bd());
            var maturity  = startDate.AddDays(365);
            var swp       = new IrSwap(startDate, 1.Years(), ix, parRate, SwapPayReceiveType.Pay, "USD.BLAH", "USD.BLAH")
            {
                Notional = notional, RateIndex = ix
            };

            var pv = swp.Pv(fModel, true);

            Assert.Equal(-368.89651349, pv, 8);

            swp = new IrSwap(startDate, 1.Years(), ix, parRate + 0.01, SwapPayReceiveType.Pay, "USD.BLAH", "USD.BLAH")
            {
                Notional = notional, RateIndex = ix
            };
            pv = swp.Pv(fModel, true);
            Assert.Equal(-10217.8229952, pv, 8);

            Assert.Equal(swp.EndDate, swp.LastSensitivityDate);

            var d = swp.Dependencies(null);

            Assert.Single(d);

            Assert.Equal(0.0496254169169585, swp.CalculateParRate(fModel), 10);
            Assert.Equal(0.09, (swp.SetParRate(0.09) as IrSwap).ParRate);

            Assert.Equal(1.0, swp.SupervisoryDelta(null));
            Assert.Equal(1.0, swp.MaturityBucket(startDate));
        }
Esempio n. 5
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);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Create a <see cref="FloatLeg"/>.
        /// </summary>
        /// <param name="calibrationDate"></param>
        /// <param name="tenor"></param>
        /// <param name="index"></param>
        /// <param name="fixedRate"></param>
        /// <returns></returns>
        public static FixedLeg CreateFixedLeg(Date calibrationDate, Tenor tenor, FloatRateIndex index,
                                              double fixedRate)
        {
            DateGenerators.CreateDatesNoHolidays(calibrationDate, tenor, index.Tenor, out var resetDates,
                                                 out var paymentDates, out var accrualFractions);
            var notionals = resetDates.Select(d => 1e6);
            var rates     = resetDates.Select(d => fixedRate);

            return(new FixedLeg(index.Currency, paymentDates, notionals, rates, accrualFractions));
        }
Esempio n. 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FRA"/> class.
 /// </summary>
 /// <param name="notional">The notional.</param>
 /// <param name="accrualFraction">The accrual fraction.  Used for calculating the cashflow and
 /// discounting it FRAs that pay on the reset date.</param>
 /// <param name="nearDate">The near date.</param>
 /// <param name="farDate">The far date.</param>
 /// <param name="floatIndex">The floating rate index that will referenced by the FRA.  Will also
 /// determine the currency of the cashflow.</param>
 public FRA(double notional, double accrualFraction, double rate, bool payFixed, Date nearDate,
            Date farDate, FloatRateIndex floatIndex)
 {
     _accrualFraction = accrualFraction;
     _notional        = notional;
     _rate            = rate;
     _payFixed        = payFixed;
     _nearDate        = nearDate;
     _farDate         = farDate;
     _floatIndex      = floatIndex;
 }
Esempio n. 8
0
        public void STIR()
        {
            var bd       = DateTime.Today;
            var pillars  = new[] { bd, bd.AddDays(1000) };
            var flatRate = 0.05;
            var rates    = pillars.Select(p => flatRate).ToArray();

            CalendarProvider.Collection.TryGetCalendar("LON", out var cal);
            var usd        = TestProviderHelper.CurrencyProvider["USD"];
            var discoCurve = new IrCurve(pillars, rates, bd, "USD.BLAH", Interpolator1DType.Linear, usd);
            var fModel     = new FundingModel(bd, new[] { discoCurve }, TestProviderHelper.CurrencyProvider, TestProviderHelper.CalendarProvider);
            var price      = 93.0;
            var ix         = new FloatRateIndex
            {
                Currency         = usd,
                DayCountBasis    = DayCountBasis.ACT360,
                FixingOffset     = 2.Bd(),
                HolidayCalendars = cal,
                ResetTenor       = 3.Months(),
                RollConvention   = RollType.MF
            };

            var maturity     = bd.AddDays(365);
            var accrualStart = maturity.AddPeriod(RollType.F, ix.HolidayCalendars, ix.FixingOffset);
            var accrualEnd   = accrualStart.AddPeriod(ix.RollConvention, ix.HolidayCalendars, ix.ResetTenor);
            var dcf          = maturity.CalculateYearFraction(accrualEnd, DayCountBasis.ACT360);
            var s            = new STIRFuture
            {
                Currency      = usd,
                ContractSize  = 1e6,
                Position      = 1,
                DCF           = dcf,
                Expiry        = maturity,
                ForecastCurve = "USD.BLAH",
                Price         = price,
                Index         = ix
            };

            var pv        = s.Pv(fModel, false);
            var rateEst   = discoCurve.GetForwardRate(accrualStart, accrualEnd, RateType.Linear, ix.DayCountBasis);
            var fairPrice = 100.0 - rateEst * 100;

            var expectedPv = (price - fairPrice) * 1e6 * dcf / 100.0;

            Assert.Equal(expectedPv, pv, 8);

            var ss = s.Sensitivities(fModel);

            Assert.True(ss.Count == 1 && ss.Keys.Single() == "USD.BLAH");
            Assert.True(ss["USD.BLAH"].Count == 2 && ss["USD.BLAH"].Keys.Contains(accrualStart) && ss["USD.BLAH"].Keys.Contains(accrualEnd));

            Assert.Empty(s.Dependencies(null));
        }
Esempio n. 9
0
        /// <summary>
        /// Create a <see cref="FloatLeg"/>.
        /// </summary>
        /// <param name="calibrationDate"></param>
        /// <param name="tenor"></param>
        /// <param name="index"></param>
        /// <param name="spread"></param>
        /// <returns></returns>
        public static FloatLeg CreateFloatLeg(Date calibrationDate, Tenor tenor, FloatRateIndex index,
                                              double spread)
        {
            DateGenerators.CreateDatesNoHolidays(calibrationDate, tenor, index.Tenor, out var resetDates,
                                                 out var paymentDates, out var accrualFractions);
            var notionals       = resetDates.Select(d => 1e6);
            var floatingIndices = resetDates.Select(d => index);
            var spreads         = resetDates.Select(d => spread);

            return(new FloatLeg(index.Currency, paymentDates, notionals, resetDates, floatingIndices, spreads,
                                accrualFractions));
        }
Esempio n. 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FRA"/> class.
 /// </summary>
 /// <param name="notional">The notional.</param>
 /// <param name="accrualFraction">The accrual fraction.  Used for calculating the cashflow and
 /// discounting it FRAs that pay on the reset date.</param>
 /// <param name="nearDate">The near date.</param>
 /// <param name="farDate">The far date.</param>
 /// <param name="floatIndex">The floating rate index that will referenced by the FRA.  Will also
 /// determine the currency of the cashflow.</param>
 public FRA(double notional, double accrualFraction, double rate, bool payFixed, Date nearDate,
            Date farDate, FloatRateIndex floatIndex)
 {
     this.accrualFraction = accrualFraction;
     this.notional        = notional;
     this.rate            = rate;
     this.payFixed        = payFixed;
     this.nearDate        = nearDate;
     this.farDate         = farDate;
     this.floatIndex      = floatIndex;
     ccy = floatIndex.Currency;
     Init();
 }
Esempio n. 11
0
        public void TestInflationLinkedSwap()
        {
            //Testing the zero-coupon inflation swap
            //Parameterise test inputs below
            var payFixed  = -1;
            var startDate = new Date(2005, 8, 31);
            var nominal   = (double)5000000;
            var tenor     = Tenor.FromYears(2);
            var fixedRate = 0.036;
            var ccy       = TestHelpers.ZAR;
            var index     = new FloatRateIndex("ZAR.JIBAR.3M", ccy, "JIBAR", Tenor.FromMonths(3));
            var spread    = 0.0;

            Date[] cpiDates =
            { new Date(2005, 3, 1), new Date(2005,  4, 1), new Date(2005,  5, 1), new Date(2005,  6, 1), new Date(2005, 7, 1), new Date(2005, 8, 1),
              new Date(2005, 9, 1), new Date(2005, 10, 1), new Date(2005, 11, 1), new Date(2005, 12, 1), new Date(2006, 1, 1), new Date(2006, 2, 1),
              new Date(2006, 3, 1), new Date(2006,  4, 1), new Date(2006,  5, 1), new Date(2006,  6, 1), new Date(2006, 7, 1), new Date(2006, 8, 1),
              new Date(2006, 9, 1), new Date(2006, 10, 1), new Date(2006, 11, 1), new Date(2006, 12, 1), new Date(2007, 1, 1), new Date(2007, 2, 1),
              new Date(2007, 3, 1), new Date(2007,  4, 1), new Date(2007,  5, 1), new Date(2007,  6, 1), new Date(2007, 7, 1), new Date(2007, 8, 1),
              new Date(2007, 9, 1), new Date(2007, 10,              1)
              ,              };

            double[] cpiRates =
            {
                126.90, 127.60, 127.60, 127.40, 128.50,  129.0, 129.50, 129.60, 129.50, 129.50, 130.40, 130.50, 131.20, 131.80, 132.60, 133.60, 134.90,
                136.0,  136.30, 136.60, 136.50,  137.0, 138.20, 139.20,  138.0,  141.0, 141.80,  143.0, 144.40, 145.10, 146.10, 147.40
            };

            var zaCalendar = new Calendar("Test");

            Date[] curveDates =
            {
                new Date(2005, 8, 31), new Date(2005, 11, 30), new Date(2006, 2, 28), new Date(2006, 5, 31), new Date(2006, 8, 31), new Date(2006, 11, 30),
                new Date(2007, 2, 28), new Date(2007,  5, 31)
            };

            double[] curveRates = { 0.07004, 0.07164, 0.07092, 0.07079, 0.08224, 0.08918, 0.09075, 0.09354 };

            //Create curve used to determine swap cash flows
            IFloatingRateSource forecastCurve = new ForecastCurve(startDate, index, curveDates, curveRates);

            //Create instance of an inflation swap
            var inflationSwap = InflationLinkedSwapEx.CreateInflationLinkedSwap(payFixed, startDate, nominal, tenor, fixedRate, index, spread, zaCalendar, ccy);

            //Get results
            var results = inflationSwap.InflationLinkedSwapMeasures(cpiDates, cpiRates, forecastCurve);

            Assert.AreEqual(5856959.45, Math.Round((double)results.GetScalar(InflationLinkedSwapEx.Keys.FloatingLegCashFlows), 2), 1e-8);
            Assert.AreEqual(-5966334.90, Math.Round((double)results.GetScalar(InflationLinkedSwapEx.Keys.FixedLegCashFlows), 2), 1e-8);
            Assert.AreEqual(-109375.45, Math.Round((double)results.GetScalar(InflationLinkedSwapEx.Keys.NetCashFlows), 2), 1e-8);
        }
Esempio n. 12
0
        public static object CreateRateIndex(
            [ExcelArgument(Description = "Index name")] string IndexName,
            [ExcelArgument(Description = "Currency")] string Currency,
            [ExcelArgument(Description = "Rate forecast tenor")] string ForecastTenor,
            [ExcelArgument(Description = "Day count basis, float leg")] string DaycountBasisFloat,
            [ExcelArgument(Description = "Day count basis, fixed leg")] string DaycountBasisFixed,
            [ExcelArgument(Description = "Fixed leg reset tenor")] string FixedTenor,
            [ExcelArgument(Description = "Holiday calendars")] string HolidayCalendars,
            [ExcelArgument(Description = "Fixing offset, e.g. 2b")] string FixingOffset,
            [ExcelArgument(Description = "Roll convention")] string RollConvention)
        {
            return(ExcelHelper.Execute(_logger, () =>
            {
                if (!Enum.TryParse(DaycountBasisFixed, out DayCountBasis dFixed))
                {
                    return $"Could not parse fixed daycount - {DaycountBasisFixed}";
                }
                if (!Enum.TryParse(DaycountBasisFloat, out DayCountBasis dFloat))
                {
                    return $"Could not parse float daycount - {DaycountBasisFloat}";
                }
                if (!Enum.TryParse(RollConvention, out RollType rConv))
                {
                    return $"Could not parse roll convention - {RollConvention}";
                }

                var floatTenor = new Frequency(ForecastTenor);
                var fixedTenor = new Frequency(FixedTenor);
                var fixOffset = new Frequency(FixingOffset);

                if (!ContainerStores.SessionContainer.GetService <ICalendarProvider>().Collection.TryGetCalendar(HolidayCalendars, out var cal))
                {
                    _logger?.LogInformation("Calendar {HolidayCalendars} not found in cache", HolidayCalendars);
                    return $"Calendar {HolidayCalendars} not found in cache";
                }

                var rIndex = new FloatRateIndex
                {
                    Currency = ContainerStores.GlobalContainer.GetRequiredService <ICurrencyProvider>()[Currency],
                    RollConvention = rConv,
                    FixingOffset = fixOffset,
                    ResetTenor = floatTenor,
                    ResetTenorFixed = fixedTenor,
                    HolidayCalendars = cal,
                    DayCountBasis = dFloat,
                    DayCountBasisFixed = dFixed
                };

                return ExcelHelper.PushToCache(rIndex, IndexName);
            }));
        }
Esempio n. 13
0
 /// <summary>
 /// Explicit constructor for IRSwap.  When possible use one of the static constructors.
 /// </summary>
 /// <param name="payFixed"></param>
 /// <param name="indexDates"></param>
 /// <param name="payDates"></param>
 /// <param name="index"></param>
 /// <param name="spreads"></param>
 /// <param name="accrualFractions"></param>
 /// <param name="notionals"></param>
 /// <param name="fixedRate"></param>
 /// <param name="ccy"></param>
 public IRSwap(double payFixed, Date[] indexDates, Date[] payDates, FloatRateIndex index, double[] spreads,
               double[] accrualFractions,
               double[] notionals, double fixedRate, Currency ccy)
 {
     _payFixed         = payFixed;
     _indexDates       = indexDates;
     _paymentDates     = payDates;
     _index            = index;
     _spreads          = spreads;
     _accrualFractions = accrualFractions;
     _notionals        = notionals;
     _fixedRate        = fixedRate;
     _ccy = ccy;
 }
Esempio n. 14
0
 public AssetSwap(double _payFixed, FloatRateIndex _index, BesaJseBond besaJseBond, List <Date> _indexDates, List <Date> _payDatesFloating,
                  List <Date> _payDatesFixed, double _spread, List <double> _accrualFractions, Calendar _zaCalendar, Currency _ccy)
 {
     payFixed             = _payFixed;
     index                = _index;
     underlyingBond       = besaJseBond;
     indexDates           = _indexDates;
     paymentDatesFloating = _payDatesFloating;
     paymentDatesFixed    = _payDatesFixed;
     spread               = _spread;
     accrualFractions     = _accrualFractions;
     zaCalendar           = _zaCalendar;
     ccy = _ccy;
 }
Esempio n. 15
0
 public static LoanFloatingRate CreateLoanFloatingRate(
     [ExcelArgument(Description = "The currency of the cashflows.")]
     Currency currency,
     [ExcelArgument(Description =
                        "The dates on which the loan balances are known.  All dates other than the first one will be assumed to also be cashflow dates.")]
     Date[] balanceDates,
     [ExcelArgument(Description = "The notionals on which the payments are based.")]
     double[] balanceAmounts,
     [ExcelArgument(Description = "The reference index on which the floating flows are based.")]
     FloatRateIndex floatingIndex,
     [ExcelArgument(Description = "The spread that will be added to the floating index.")]
     double floatingSpread)
 {
     return(LoanFloatingRate.CreateSimple(balanceDates, balanceAmounts, floatingIndex, floatingSpread, currency));
 }
Esempio n. 16
0
 public static IRSwap CreateZARSwap([ExcelArgument(Description = "First reset date of the swap")]
                                    Date startDate,
                                    [ExcelArgument(Description = "Tenor of swap, must be a whole number of years.  Example '5Y'.")]
                                    Tenor tenor,
                                    [ExcelArgument(Description = "The fixed rate paid or received")]
                                    double rate,
                                    [ExcelArgument(Description = "Is the fixed rate paid? Enter 'TRUE' for yes.")]
                                    bool payFixed,
                                    [ExcelArgument(Description = "Flat notional for all dates.")]
                                    double notional,
                                    [QuantSAExcelArgument(Description = "The float rate index of the swap.", Default = "DEFAULT")]
                                    FloatRateIndex jibar)
 {
     return(SwapFactory.CreateZARSwap(rate, payFixed, notional, startDate, tenor, jibar));
 }
Esempio n. 17
0
 public InflationLinkedSwap(double _payFixed, Date _startDate, double _nominal, Tenor _tenor, double _fixedRate, FloatRateIndex _index, Date[] _indexDates, Date[] _payDatesFloating,
                            double _spread, double[] _accrualFractions, Calendar _zaCalendar, Currency _ccy)
 {
     payFixed             = _payFixed;
     startDate            = _startDate;
     nominal              = _nominal;
     tenor                = _tenor;
     fixedRate            = _fixedRate;
     index                = _index;
     indexDates           = _indexDates;
     paymentDatesFloating = _payDatesFloating;
     spread               = _spread;
     accrualFractions     = _accrualFractions;
     zaCalendar           = _zaCalendar;
     ccy = _ccy;
 }
Esempio n. 18
0
 public static FRA CreateZARFRA([ExcelArgument(Description =
                                                   "The trade date of the FRA.  The near and far dates will be calculated from this.")]
                                Date tradeDate,
                                [ExcelArgument(Description = "The notional of the FRA in rands.")]
                                double notional,
                                [ExcelArgument(Description = "The fixed rate paid or received.")]
                                double rate,
                                [ExcelArgument(Description = "The FRA code, e.g. '3x6'.")]
                                string fraCode,
                                [ExcelArgument(Description = "Is the fixed rate paid? Enter 'TRUE' for yes.")]
                                bool payFixed,
                                [QuantSAExcelArgument(Description = "The float rate index of the FRA.", Default = "ZAR.JIBAR.3M")]
                                FloatRateIndex jibar)
 {
     // TODO: JT: Get a preferred calendar from the float rate index
     return(FRA.CreateZARFra(tradeDate, notional, rate, fraCode, payFixed, new Calendar("ZA"), jibar));
 }
Esempio n. 19
0
        public static HullWhite1F CreateHWModelDemo(
            [ExcelArgument(Description = "The constant rate of mean reversion.")]
            double meanReversion,
            [ExcelArgument(Description =
                               "The constant short rate volatility.  Note that this is a Gaussian vol and will in general be lower than the vol that would be used in Black.")]
            double flatVol,
            [ExcelArgument(Description = "The curve to which zero coupon bond prices will be calibrated.")]
            IDiscountingSource baseCurve,
            [ExcelArgument(Description =
                               "The indices that should be forecast with this same curve.  No spreads are added.")]
            FloatRateIndex forecastIndices)
        {
            var anchorDate    = baseCurve.GetAnchorDate();
            var flatCurveRate = -Math.Log(baseCurve.GetDF(anchorDate.AddTenor(Tenor.FromYears(1))));
            var model         = new HullWhite1F(baseCurve.GetCurrency(), meanReversion, flatVol, flatCurveRate, flatCurveRate,
                                                new[] { forecastIndices });

            return(model);
        }
Esempio n. 20
0
        public void CanStripCurve_FedFunds()
        {
            var i = new FloatRateIndex()
            {
                Currency         = TestProviderHelper.CurrencyProvider.GetCurrency("USD"),
                DayCountBasis    = DayCountBasis.Act360,
                FixingOffset     = 0.Bd(),
                HolidayCalendars = TestProviderHelper.CalendarProvider.Collection["NYC+LON"],
                ResetTenor       = 1.Months(),
                RollConvention   = RollType.MF
            };
            var indices = new Dictionary <string, FloatRateIndex> {
                { "FF", i }
            };
            var curves = new Dictionary <string, string> {
                { "FF", "USD.OIS.1B" }
            };
            var curve = CMEModelBuilder.GetCurveForCode("41", FilenameCBOT, "FF", "USD.OIS.1B", indices, curves, TestProviderHelper.FutureSettingsProvider, TestProviderHelper.CurrencyProvider, TestProviderHelper.CalendarProvider);

            Assert.Equal(1.0, curve.GetDf(new DateTime(2020, 12, 18), new DateTime(2020, 12, 18)));
        }
Esempio n. 21
0
        public static FloatLeg CreateFloatLeg([ExcelArgument(Description = "The currency of the cashflows. (Currency)")]
                                              Currency currency,
                                              [ExcelArgument(Description = "A string describing the floating index.")]
                                              FloatRateIndex floatingIndex,
                                              [ExcelArgument(Description = "The dates on which the floating indices reset.")]
                                              Date[] resetDates,
                                              [ExcelArgument(Description = "The dates on which the payments are made.")]
                                              Date[] paymentDates,
                                              [ExcelArgument(Description = "The notionals on which the payments are based.")]
                                              double[] notionals,
                                              [ExcelArgument(Description =
                                                                 "The spreads that apply to the simple floating rates on each of the payment dates.")]
                                              double[] spreads,
                                              [ExcelArgument(Description =
                                                                 "The accrual fraction to be used in calculating the fixed flow.  Will depend on the daycount convention agreed in the contract.")]
                                              double[] accrualFractions)
        {
            var floatingIndices = Enumerable.Range(1, resetDates.Length).Select(i => floatingIndex).ToArray();

            return(new FloatLeg(currency, paymentDates, notionals, resetDates, floatingIndices, spreads,
                                accrualFractions));
        }
Esempio n. 22
0
 public static BermudanSwaption CreateZARBermudanSwaption(
     [ExcelArgument(Description =
                        "The exercise dates.  The dates on which the person who is long optionality can exercise.")]
     Date[] exerciseDates,
     [ExcelArgument(Description = "if set to TRUE then the person valuing this product owns the optionality.")]
     bool longOptionality,
     [ExcelArgument(Description = "First reset date of the underlying swap.")]
     Date startDate,
     [ExcelArgument(Description = "Tenor of underlying swap, must be a whole number of years.  Example '5Y'.")]
     Tenor tenor,
     [ExcelArgument(Description = "The fixed rate paid or received on the underlying swap.")]
     double rate,
     [ExcelArgument(Description = "Is the fixed rate paid? Enter 'TRUE' for yes.")]
     bool payFixed,
     [ExcelArgument(Description = "Flat notional for all dates.")]
     double notional,
     [QuantSAExcelArgument(Description = "Flat notional for all dates.", Default = "DEFAULT")]
     FloatRateIndex jibar)
 {
     return(SwapFactory.CreateZARBermudanSwaption(exerciseDates, longOptionality, rate, payFixed, notional,
                                                  startDate, tenor, jibar));
 }
Esempio n. 23
0
        /// <summary>
        /// Creates a FRA according to South African conventions.
        /// </summary>
        /// <param name="tradeDate">The trade date.</param>
        /// <param name="notional">The notional used in calculating the cashflow.</param>
        /// <param name="rate">The fixed rate paid or received on the fra.</param>
        /// <param name="fraCode">The fra code, eg '3x6'.</param>
        /// <param name="payFixed">if set to <c>true</c> the fixed rate is paid..</param>
        /// <param name="zaCalendar">The za calendar.</param>
        /// <param name="jibar"></param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">
        /// </exception>
        public static FRA CreateZARFra(Date tradeDate, double notional, double rate, string fraCode, bool payFixed,
                                       Calendar zaCalendar, FloatRateIndex jibar)
        {
            var parts = fraCode.ToLower().Trim().Split('x');

            if (parts.Length != 2)
            {
                throw new ArgumentException(
                          fraCode +
                          " is not of the required form.  FRA code must be of the form 'mxn' for integer m and n, example: '3x6'");
            }
            var near = 0;
            var far  = 0;

            if (!int.TryParse(parts[0], out near))
            {
                throw new ArgumentException(
                          fraCode +
                          " is not of the required form.  FRA code must be of the form 'mxn' for integer m and n, example: '3x6'");
            }
            if (!int.TryParse(parts[1], out far))
            {
                throw new ArgumentException(
                          fraCode +
                          " is not of the required form.  FRA code must be of the form 'mxn' for integer m and n, example: '3x6'");
            }
            if (far - near != 3)
            {
                throw new ArgumentException(
                          fraCode + " is not of the required form.  The near and far number of months must differ by 3.");
            }
            var mf              = BusinessDayStore.ModifiedFollowing;
            var nearDate        = mf.Adjust(tradeDate.AddMonths(near), zaCalendar);
            var farDate         = mf.Adjust(tradeDate.AddMonths(far), zaCalendar);
            var accrualFraction = DayCountStore.Actual365Fixed.YearFraction(nearDate, farDate);

            return(new FRA(notional, accrualFraction, rate, payFixed, nearDate, farDate, jibar));
        }
Esempio n. 24
0
        public void CanStripCurve_ZarBasis()
        {
            var i = new FloatRateIndex()
            {
                Currency         = TestProviderHelper.CurrencyProvider.GetCurrency("USD"),
                DayCountBasis    = DayCountBasis.Act360,
                FixingOffset     = 2.Bd(),
                HolidayCalendars = TestProviderHelper.CalendarProvider.Collection["NYC+LON"],
                ResetTenor       = 3.Months(),
                RollConvention   = RollType.MF
            };
            var indices = new Dictionary <string, FloatRateIndex> {
                { "ED", i }
            };
            var curves = new Dictionary <string, string> {
                { "ED", "USD.LIBOR.3M" }
            };
            var usdCurve = CMEModelBuilder.GetCurveForCode("ED", FilenameCME, "ED", "USD.LIBOR.3M", indices, curves, TestProviderHelper.FutureSettingsProvider, TestProviderHelper.CurrencyProvider, TestProviderHelper.CalendarProvider);
            var zar      = TestProviderHelper.CurrencyProvider.GetCurrency("ZAR");
            var zarCurve = CMEModelBuilder.StripFxBasisCurve(FilenameCMEFwdsXml, "USDZAR", zar, "ZAR.BASIS", new DateTime(2020, 06, 18), usdCurve);

            Assert.Equal(1.0, zarCurve.GetDf(new DateTime(2020, 12, 18), new DateTime(2020, 12, 18)));
        }
Esempio n. 25
0
 public static IFloatingRateSource CreateRateForecastCurve(
     [QuantSAExcelArgument(Description = "The anchor date of the curve.")]
     Date anchorDate,
     [ExcelArgument(Description = "The dates at which the rates apply.")]
     Date[] dates,
     [ExcelArgument(Description = "The rates.")]
     double[] rates,
     [QuantSAExcelArgument(Description = "The index that this curve forecasts.", Default = "ZAR.JIBAR.3M")]
     FloatRateIndex floatRateIndex)
 {
     for (var i = 1; i < dates.Length; i++)
     {
         if (dates[i].value <= dates[i - 1].value)
         {
             throw new ArgumentException($"{nameof(dates)} must be strictly increasing");
         }
     }
     if (dates.Length != rates.Length)
     {
         throw new ArgumentException($"{nameof(dates)} and {nameof(rates)} must be the same length");
     }
     return(new ForecastCurve(anchorDate, floatRateIndex, dates, rates));
 }
Esempio n. 26
0
        public void FuturesStripWithConvexity()
        {
            var volatility = 0.03;

            var startDate   = new DateTime(2017, 01, 17);
            var nContracts  = 24;
            var currentDate = startDate.GetNextImmDate();
            var expiries    = new DateTime[nContracts];
            var pillars     = new DateTime[nContracts];
            var instruments = new IFundingInstrument[nContracts];

            var nyc    = TestProviderHelper.CalendarProvider.Collection["NYC"];
            var lon    = TestProviderHelper.CalendarProvider.Collection["LON"];
            var ccyUsd = TestProviderHelper.CurrencyProvider["USD"];

            var usd3m = new FloatRateIndex()
            {
                Currency           = ccyUsd,
                DayCountBasis      = DayCountBasis.Act_360,
                DayCountBasisFixed = DayCountBasis.Act_360,
                ResetTenor         = 3.Months(),
                FixingOffset       = 2.Bd(),
                HolidayCalendars   = nyc,
                RollConvention     = RollType.MF
            };

            for (var i = 0; i < nContracts; i++)
            {
                var wed3rd = currentDate.ThirdWednesday();
                expiries[i]    = wed3rd.SubtractPeriod(RollType.P, lon, 2.Bd());
                pillars[i]     = wed3rd.AddPeriod(usd3m.RollConvention, usd3m.HolidayCalendars, usd3m.ResetTenor);
                instruments[i] = new STIRFuture()
                {
                    Currency            = ccyUsd,
                    ContractSize        = 1e6,
                    ConvexityAdjustment = FuturesConvexityUtils.CalculateConvexityAdjustment(startDate, expiries[i], pillars[i], volatility),
                    DCF           = 0.25,
                    Expiry        = expiries[i],
                    ForecastCurve = "USD.LIBOR.3M",
                    Index         = usd3m,
                    Position      = 1.0,
                    Price         = 99.50,
                    SolveCurve    = "USD.LIBOR.3M"
                };

                currentDate = currentDate.AddMonths(3);
            }

            var fic = new FundingInstrumentCollection(TestProviderHelper.CurrencyProvider);

            fic.AddRange(instruments);

            var curve = new IrCurve(pillars, new double[nContracts], startDate, "USD.LIBOR.3M", Interpolator1DType.LinearFlatExtrap, ccyUsd);
            var model = new FundingModel(startDate, new[] { curve }, TestProviderHelper.CurrencyProvider, TestProviderHelper.CalendarProvider);

            var s = new Calibrators.NewtonRaphsonMultiCurveSolver()
            {
                Tollerance = IsCoverageOnly ? 1 : 0.00000001
            };

            s.Solve(model, fic);

            if (!IsCoverageOnly)
            {
                for (var i = 0; i < nContracts; i++)
                {
                    var resultPV = instruments[i].Pv(model, false);
                    Assert.Equal(0, resultPV, 6);
                }
            }
        }
        /// <summary>
        /// Create a floating rate loan from a loan profile.  The first date in the profile is the disbursment date and
        /// the last date is the final repayment date.  Interest will due on all but the first profile date.
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="balanceDates">
        /// A date must be given for each interest date and this original disbursement date
        /// even if the balances remain constant.
        /// </param>
        /// <returns></returns>
        public static LoanFloatingRate CreateSimple(Date[] balanceDates, double[] balances, FloatRateIndex index,
                                                    double spread, Currency ccy)
        {
            var loan = new LoanFloatingRate();

            loan.valueDate      = null;
            loan.ccy            = ccy;
            loan._spread        = spread;
            loan._notionalFlows = new List <Cashflow>();
            loan._notionalFlows.Add(new Cashflow(balanceDates[0], -balances[0], ccy));

            // Set the details for the FloatLeg
            loan.paymentDates     = new Date[balanceDates.Length - 1];
            loan.resetDates       = new Date[balanceDates.Length - 1];
            loan.floatingIndices  = new FloatRateIndex[balanceDates.Length - 1];
            loan.spreads          = new double[balanceDates.Length - 1];
            loan.notionals        = new double[balanceDates.Length - 1];
            loan.accrualFractions = new double[balanceDates.Length - 1];

            for (var i = 1; i < balances.Length; i++)
            {
                loan.paymentDates[i - 1]     = balanceDates[i];
                loan.resetDates[i - 1]       = balanceDates[i - 1];
                loan.floatingIndices[i - 1]  = index;
                loan.spreads[i - 1]          = spread;
                loan.notionals[i - 1]        = balances[i - 1];
                loan.accrualFractions[i - 1] = (balanceDates[i] - balanceDates[i - 1]) / 365.0;

                var notionalFlow = balances[i - 1] - balances[i];
                loan._notionalFlows.Add(new Cashflow(balanceDates[i], notionalFlow, ccy));
            }

            loan.Type   = "LoanFloatingRate";
            loan._index = index;
            return(loan);
        }
Esempio n. 28
0
        /// <summary>
        /// Creates Bermudan swaption with a simple ZAR swap as underlying, the ZAR swap is the same as that created by:
        ///  <see cref="CreateZARSwap"/>.
        /// </summary>
        /// <param name="exerciseDates">The exercise dates.  The dates on which the person who is long optionality can exercise.</param>
        /// <param name="longOptionality">if set to <c>true</c> then the person valuing this product owns the optionality.</param>
        /// <param name="rate">The fixed rate on the underlying swap.</param>
        /// <param name="payFixed">if set to <c>true</c> then the underlying swap has the person valuing the product paying fixed after exercise.</param>
        /// <param name="notional">The constant notional in ZAR on the underlying swap.</param>
        /// <param name="startDate">The start date of the underlying swap.</param>
        /// <param name="tenor">The tenor of the underlying swap.</param>
        /// <param name="floatRateIndex"></param>
        /// <returns></returns>
        public static BermudanSwaption CreateZARBermudanSwaption(Date[] exerciseDates, bool longOptionality,
                                                                 double rate,
                                                                 bool payFixed, double notional, Date startDate, Tenor tenor, FloatRateIndex floatRateIndex)
        {
            var swap     = CreateZARSwap(rate, payFixed, notional, startDate, tenor, floatRateIndex);
            var swaption = new BermudanSwaption(swap, exerciseDates.ToList(), longOptionality);

            return(swaption);
        }
Esempio n. 29
0
        private FloatLeg CreateFloatingLeg(Currency ccy, Date startDate, double notional, FloatRateIndex index,
                                           int tenorYears)
        {
            var quarters         = tenorYears * 4;
            var paymentDates     = Enumerable.Range(1, quarters).Select(i => startDate.AddMonths(3 * i)).ToArray();
            var resetDates       = Enumerable.Range(0, quarters).Select(i => startDate.AddMonths(3 * i)).ToArray();
            var notionals        = Vector.Ones(quarters).Multiply(notional);
            var spreads          = Vector.Zeros(quarters);
            var accrualFractions = Vector.Ones(quarters).Multiply(0.25);
            var floatingIndices  = Enumerable.Range(1, quarters).Select(i => index).ToArray();
            var leg = new FloatLeg(ccy, paymentDates, notionals, resetDates, floatingIndices, spreads,
                                   accrualFractions);

            return(leg);
        }
 /// <summary>
 /// An Ibor curve that can be used for discounting.
 /// </summary>
 /// <param name="currency"></param>
 /// <param name="iborIndex"></param>
 public DiscountingSourceDescription(Currency currency, FloatRateIndex iborIndex)
 {
     _currency  = currency;
     _iborIndex = iborIndex;
 }