Beispiel #1
0
 private void ok5_Click(object sender, EventArgs e)
 {
     InterestRate inte = new InterestRate();
     inte.Tenor = Convert.ToDouble(tenor5.Value);
     inte.Rate = Convert.ToDouble(rate5.Value);
     portfolio.InterestRates.Add(inte);
     portfolio.SaveChanges();
     MessageBox.Show("Data added successfully", "Notice");
     this.Close();
 }
Beispiel #2
0
        public static double duration(Bond bond, InterestRate yield, Duration.Type type)
        {
            double ret = NQuantLibcPINVOKE.BondFunctions_duration__SWIG_1(Bond.getCPtr(bond), InterestRate.getCPtr(yield), (int)type);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Beispiel #3
0
        public void testSettings()
        {
            // Testing cash-flow settings...
            using (SavedSettings backup = new SavedSettings())
            {
                Date today = Date.Today;
                Settings.setEvaluationDate(today);

                // cash flows at T+0, T+1, T+2
                List <CashFlow> leg = new List <CashFlow>();

                for (int i = 0; i < 3; ++i)
                {
                    leg.Add(new SimpleCashFlow(1.0, today + i));
                }

                // case 1: don't include reference-date payments, no override at
                //         today's date

                Settings.includeReferenceDateEvents = false;
                Settings.includeTodaysCashFlows     = null;

                CHECK_INCLUSION(0, 0, false, leg, today);
                CHECK_INCLUSION(0, 1, false, leg, today);

                CHECK_INCLUSION(1, 0, true, leg, today);
                CHECK_INCLUSION(1, 1, false, leg, today);
                CHECK_INCLUSION(1, 2, false, leg, today);

                CHECK_INCLUSION(2, 1, true, leg, today);
                CHECK_INCLUSION(2, 2, false, leg, today);
                CHECK_INCLUSION(2, 3, false, leg, today);

                // case 2: same, but with explicit setting at today's date

                Settings.includeReferenceDateEvents = false;
                Settings.includeTodaysCashFlows     = false;

                CHECK_INCLUSION(0, 0, false, leg, today);
                CHECK_INCLUSION(0, 1, false, leg, today);

                CHECK_INCLUSION(1, 0, true, leg, today);
                CHECK_INCLUSION(1, 1, false, leg, today);
                CHECK_INCLUSION(1, 2, false, leg, today);

                CHECK_INCLUSION(2, 1, true, leg, today);
                CHECK_INCLUSION(2, 2, false, leg, today);
                CHECK_INCLUSION(2, 3, false, leg, today);

                // case 3: do include reference-date payments, no override at
                //         today's date

                Settings.includeReferenceDateEvents = true;
                Settings.includeTodaysCashFlows     = null;

                CHECK_INCLUSION(0, 0, true, leg, today);
                CHECK_INCLUSION(0, 1, false, leg, today);

                CHECK_INCLUSION(1, 0, true, leg, today);
                CHECK_INCLUSION(1, 1, true, leg, today);
                CHECK_INCLUSION(1, 2, false, leg, today);

                CHECK_INCLUSION(2, 1, true, leg, today);
                CHECK_INCLUSION(2, 2, true, leg, today);
                CHECK_INCLUSION(2, 3, false, leg, today);

                // case 4: do include reference-date payments, explicit (and same)
                //         setting at today's date

                Settings.includeReferenceDateEvents = true;
                Settings.includeTodaysCashFlows     = true;

                CHECK_INCLUSION(0, 0, true, leg, today);
                CHECK_INCLUSION(0, 1, false, leg, today);

                CHECK_INCLUSION(1, 0, true, leg, today);
                CHECK_INCLUSION(1, 1, true, leg, today);
                CHECK_INCLUSION(1, 2, false, leg, today);

                CHECK_INCLUSION(2, 1, true, leg, today);
                CHECK_INCLUSION(2, 2, true, leg, today);
                CHECK_INCLUSION(2, 3, false, leg, today);

                // case 5: do include reference-date payments, override at
                //         today's date

                Settings.includeReferenceDateEvents = true;
                Settings.includeTodaysCashFlows     = false;

                CHECK_INCLUSION(0, 0, false, leg, today);
                CHECK_INCLUSION(0, 1, false, leg, today);

                CHECK_INCLUSION(1, 0, true, leg, today);
                CHECK_INCLUSION(1, 1, true, leg, today);
                CHECK_INCLUSION(1, 2, false, leg, today);

                CHECK_INCLUSION(2, 1, true, leg, today);
                CHECK_INCLUSION(2, 2, true, leg, today);
                CHECK_INCLUSION(2, 3, false, leg, today);

                // no discount to make calculations easier
                InterestRate no_discount = new InterestRate(0.0, new Actual365Fixed(), Compounding.Continuous, Frequency.Annual);

                // no override
                Settings.includeTodaysCashFlows = null;

                CHECK_NPV(false, 2.0, no_discount, leg, today);
                CHECK_NPV(true, 3.0, no_discount, leg, today);

                // override
                Settings.includeTodaysCashFlows = false;

                CHECK_NPV(false, 2.0, no_discount, leg, today);
                CHECK_NPV(true, 2.0, no_discount, leg, today);
            }
        }
        private void testdata4()
        {
            InterestRate inte = new InterestRate();
            inte.Rate = 0.02;
            inte.Tenor = 0.25;
            portfolio.InterestRates.Add(inte);
            portfolio.SaveChanges();

            InterestRate inte2 = new InterestRate();
            inte2.Rate = 0.03;
            inte2.Tenor = 0.5;
            portfolio.InterestRates.Add(inte2);
            portfolio.SaveChanges();

            InterestRate inte3 = new InterestRate();
            inte3.Rate = 0.05;
            inte3.Tenor = 1;
            portfolio.InterestRates.Add(inte3);
            portfolio.SaveChanges();

            InterestRate inte4 = new InterestRate();
            inte4.Rate = 0.08;
            inte4.Tenor = 2;
            portfolio.InterestRates.Add(inte4);
            portfolio.SaveChanges();

            InterestRate inte5 = new InterestRate();
            inte5.Rate = 0.11;
            inte5.Tenor = 5;
            portfolio.InterestRates.Add(inte5);
            portfolio.SaveChanges();
        }
Beispiel #5
0
 public static double basisPointValue(Bond bond, InterestRate yield, Date settlementDate) {
   double ret = NQuantLibcPINVOKE.BondFunctions_basisPointValue__SWIG_0(Bond.getCPtr(bond), InterestRate.getCPtr(yield), Date.getCPtr(settlementDate));
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
        public void loadPrime(String primeFilename)
        {
            var csv = new ReadCSV(primeFilename, true, CSVFormat.English);

            while (csv.Next())
            {
                var date = csv.GetDate("date");
                double rate = csv.GetDouble("prime");
                var ir = new InterestRate(date, rate);
                rates.Add(ir);
            }

            csv.Close();
            rates.Sort();
        }
Beispiel #7
0
 public static double duration(Leg arg0, InterestRate arg1, Duration.Type type, bool includeSettlementDateFlows) {
   double ret = NQuantLibcPINVOKE.CashFlows_duration__SWIG_1(Leg.getCPtr(arg0), InterestRate.getCPtr(arg1), (int)type, includeSettlementDateFlows);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #8
0
        public void testConversions()
        {
            InterestRateData[] cases =
            {
                // data from "Option Pricing Formulas", Haug, pag.181-182
                // Rate,Compounding,        Frequency,   Time, Compounding2,      Frequency2,  Rate2, precision
                new InterestRateData(0.0800, Compounding.Compounded,           Frequency.Quarterly,            1.00, Compounding.Continuous,           Frequency.Annual,           0.0792, 4),
                new InterestRateData(0.1200, Compounding.Continuous,           Frequency.Annual,               1.00, Compounding.Compounded,           Frequency.Annual,           0.1275, 4),
                new InterestRateData(0.0800, Compounding.Compounded,           Frequency.Quarterly,            1.00, Compounding.Compounded,           Frequency.Annual,           0.0824, 4),
                new InterestRateData(0.0700, Compounding.Compounded,           Frequency.Quarterly,            1.00, Compounding.Compounded,           Frequency.Semiannual,       0.0706, 4),
                // undocumented, but reasonable :)
                new InterestRateData(0.0100, Compounding.Compounded,           Frequency.Annual,               1.00, Compounding.Simple,               Frequency.Annual,           0.0100, 4),
                new InterestRateData(0.0200, Compounding.Simple,               Frequency.Annual,               1.00, Compounding.Compounded,           Frequency.Annual,           0.0200, 4),
                new InterestRateData(0.0300, Compounding.Compounded,           Frequency.Semiannual,           0.50, Compounding.Simple,               Frequency.Annual,           0.0300, 4),
                new InterestRateData(0.0400, Compounding.Simple,               Frequency.Annual,               0.50, Compounding.Compounded,           Frequency.Semiannual,       0.0400, 4),
                new InterestRateData(0.0500, Compounding.Compounded,           Frequency.EveryFourthMonth,  1.0 / 3, Compounding.Simple,               Frequency.Annual,           0.0500, 4),
                new InterestRateData(0.0600, Compounding.Simple,               Frequency.Annual,            1.0 / 3, Compounding.Compounded,           Frequency.EveryFourthMonth, 0.0600, 4),
                new InterestRateData(0.0500, Compounding.Compounded,           Frequency.Quarterly,            0.25, Compounding.Simple,               Frequency.Annual,           0.0500, 4),
                new InterestRateData(0.0600, Compounding.Simple,               Frequency.Annual,               0.25, Compounding.Compounded,           Frequency.Quarterly,        0.0600, 4),
                new InterestRateData(0.0700, Compounding.Compounded,           Frequency.Bimonthly,         1.0 / 6, Compounding.Simple,               Frequency.Annual,           0.0700, 4),
                new InterestRateData(0.0800, Compounding.Simple,               Frequency.Annual,            1.0 / 6, Compounding.Compounded,           Frequency.Bimonthly,        0.0800, 4),
                new InterestRateData(0.0900, Compounding.Compounded,           Frequency.Monthly,          1.0 / 12, Compounding.Simple,               Frequency.Annual,           0.0900, 4),
                new InterestRateData(0.1000, Compounding.Simple,               Frequency.Annual,           1.0 / 12, Compounding.Compounded,           Frequency.Monthly,          0.1000, 4),

                new InterestRateData(0.0300, Compounding.SimpleThenCompounded, Frequency.Semiannual,           0.25, Compounding.Simple,               Frequency.Annual,           0.0300, 4),
                new InterestRateData(0.0300, Compounding.SimpleThenCompounded, Frequency.Semiannual,           0.25, Compounding.Simple,               Frequency.Semiannual,       0.0300, 4),
                new InterestRateData(0.0300, Compounding.SimpleThenCompounded, Frequency.Semiannual,           0.25, Compounding.Simple,               Frequency.Quarterly,        0.0300, 4),
                new InterestRateData(0.0300, Compounding.SimpleThenCompounded, Frequency.Semiannual,           0.50, Compounding.Simple,               Frequency.Annual,           0.0300, 4),
                new InterestRateData(0.0300, Compounding.SimpleThenCompounded, Frequency.Semiannual,           0.50, Compounding.Simple,               Frequency.Semiannual,       0.0300, 4),
                new InterestRateData(0.0300, Compounding.SimpleThenCompounded, Frequency.Semiannual,           0.75, Compounding.Compounded,           Frequency.Semiannual,       0.0300, 4),

                new InterestRateData(0.0400, Compounding.Simple,               Frequency.Semiannual,           0.25, Compounding.SimpleThenCompounded, Frequency.Quarterly,        0.0400, 4),
                new InterestRateData(0.0400, Compounding.Simple,               Frequency.Semiannual,           0.25, Compounding.SimpleThenCompounded, Frequency.Semiannual,       0.0400, 4),
                new InterestRateData(0.0400, Compounding.Simple,               Frequency.Semiannual,           0.25, Compounding.SimpleThenCompounded, Frequency.Annual,           0.0400, 4),

                new InterestRateData(0.0400, Compounding.Compounded,           Frequency.Quarterly,            0.50, Compounding.SimpleThenCompounded, Frequency.Quarterly,        0.0400, 4),
                new InterestRateData(0.0400, Compounding.Simple,               Frequency.Semiannual,           0.50, Compounding.SimpleThenCompounded, Frequency.Semiannual,       0.0400, 4),
                new InterestRateData(0.0400, Compounding.Simple,               Frequency.Semiannual,           0.50, Compounding.SimpleThenCompounded, Frequency.Annual,           0.0400, 4),

                new InterestRateData(0.0400, Compounding.Compounded,           Frequency.Quarterly,            0.75, Compounding.SimpleThenCompounded, Frequency.Quarterly,        0.0400, 4),
                new InterestRateData(0.0400, Compounding.Compounded,           Frequency.Semiannual,           0.75, Compounding.SimpleThenCompounded, Frequency.Semiannual,       0.0400, 4),
                new InterestRateData(0.0400, Compounding.Simple,               Frequency.Semiannual,           0.75, Compounding.SimpleThenCompounded, Frequency.Annual,           0.0400, 4)
            };

            Rounding     roundingPrecision;
            double       r3;
            double       r2;
            Date         d1 = Date.Today;
            Date         d2;
            InterestRate ir;
            InterestRate ir2;
            InterestRate ir3;
            InterestRate expectedIR;
            double       compoundf;
            double       error;
            double       disc;

            for (int i = 0; i < cases.Length - 1; i++)
            {
                ir = new InterestRate(cases[i].r, new Actual360(), cases[i].comp, cases[i].freq);
                d2 = d1 + new Period((int)(360 * cases[i].t + 0.5), TimeUnit.Days);
                roundingPrecision = new Rounding(cases[i].precision);

                // check that the compound factor is the inverse of the discount factor
                compoundf = ir.compoundFactor(d1, d2);
                disc      = ir.discountFactor(d1, d2);
                error     = Math.Abs(disc - 1.0 / compoundf);
                if (error > 1e-15)
                {
                    QAssert.Fail(ir + "  1.0/compound_factor: " + 1.0 / compoundf);
                }

                // check that the equivalent InterestRate with *same* daycounter,
                // compounding, and frequency is the *same* InterestRate
                //ir2 = ir.equivalentRate(d1, d2, ir.dayCounter(), ir.compounding(), ir.frequency());
                ir2   = ir.equivalentRate(ir.dayCounter(), ir.compounding(), ir.frequency(), d1, d2);
                error = Math.Abs(ir.rate() - ir2.rate());
                if (error > 1e-15)
                {
                    QAssert.Fail("original interest rate: " + ir + " equivalent interest rate: " + ir2 + " rate error: " + error);
                }
                if (ir.dayCounter() != ir2.dayCounter())
                {
                    QAssert.Fail("day counter error original interest rate: " + ir + " equivalent interest rate: " + ir2);
                }
                if (ir.compounding() != ir2.compounding())
                {
                    QAssert.Fail("compounding error original interest rate: " + ir + " equivalent interest rate: " + ir2);
                }
                if (ir.frequency() != ir2.frequency())
                {
                    QAssert.Fail("frequency error original interest rate: " + ir + " equivalent interest rate: " + ir2);
                }

                // check that the equivalent rate with *same* daycounter,
                // compounding, and frequency is the *same* rate
                //r2 = ir.equivalentRate(d1, d2, ir.dayCounter(), ir.compounding(), ir.frequency()).rate();
                r2    = ir.equivalentRate(ir.dayCounter(), ir.compounding(), ir.frequency(), d1, d2).value();
                error = Math.Abs(ir.rate() - r2);
                if (error > 1e-15)
                {
                    QAssert.Fail("original rate: " + ir + " equivalent rate: " + r2 + " error: " + error);
                }

                // check that the equivalent InterestRate with *different*
                // compounding, and frequency is the *expected* InterestRate
                //ir3 = ir.equivalentRate(d1, d2, ir.dayCounter(), cases[i].comp2, cases[i].freq2);
                ir3        = ir.equivalentRate(ir.dayCounter(), cases[i].comp2, cases[i].freq2, d1, d2);
                expectedIR = new InterestRate(cases[i].expected, ir.dayCounter(), cases[i].comp2, cases[i].freq2);
                r3         = roundingPrecision.Round(ir3.rate());
                error      = Math.Abs(r3 - expectedIR.rate());
                if (error > 1.0e-17)
                {
                    QAssert.Fail("original interest rate: " + ir + " calculated equivalent interest rate: " + ir3 + " truncated equivalent rate: " + r3 + " expected equivalent interest rate: " + expectedIR + " rate error: " + error);
                }
                if (ir3.dayCounter() != expectedIR.dayCounter())
                {
                    QAssert.Fail("day counter error original interest rate: " + ir3 + " equivalent interest rate: " + expectedIR);
                }
                if (ir3.compounding() != expectedIR.compounding())
                {
                    QAssert.Fail("compounding error original interest rate: " + ir3 + " equivalent interest rate: " + expectedIR);
                }
                if (ir3.frequency() != expectedIR.frequency())
                {
                    QAssert.Fail("frequency error original interest rate: " + ir3 + " equivalent interest rate: " + expectedIR);
                }

                // check that the equivalent rate with *different*
                // compounding, and frequency is the *expected* rate
                //r3 = ir.equivalentRate(d1, d2, ir.dayCounter(), cases[i].comp2, cases[i].freq2).rate();
                r3    = ir.equivalentRate(ir.dayCounter(), cases[i].comp2, cases[i].freq2, d1, d2).value();
                r3    = roundingPrecision.Round(r3);
                error = Math.Abs(r3 - cases[i].expected);
                if (error > 1.0e-17)
                {
                    QAssert.Fail("calculated equivalent rate: " + r3 + " expected equivalent rate: " + cases[i].expected + " error: " + error);
                }
            }
        }
        public static double duration(Leg arg0, InterestRate arg1, Duration.Type type, bool includeSettlementDateFlows)
        {
            double ret = NQuantLibcPINVOKE.CashFlows_duration__SWIG_1(Leg.getCPtr(arg0), InterestRate.getCPtr(arg1), (int)type, includeSettlementDateFlows);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Beispiel #10
0
        private void BuildDiscountCurve()
        {
            Utils.QL_REQUIRE(_curveSegments.Count <= 1, () => "More than one zero curve segment not supported yet.");
            Utils.QL_REQUIRE(_curveSegments[0].CurveSegmentType() == YieldCurveSegment.Type.Zero, () => "The curve segment is not of type Zero.");

            // Fill a vector of zero quotes.
            List <ZeroQuote>        zeroQuotes       = new List <ZeroQuote>();
            DirectYieldCurveSegment zeroCurveSegment = _curveSegments[0] as DirectYieldCurveSegment;

            List <string> zeroQuoteIDs = zeroCurveSegment.Quotes();

            for (int i = 0; i < zeroQuoteIDs.Count; ++i)
            {
                MarketDatum marketQuote = _loader.Get(zeroQuoteIDs[i], _asofDate);
                if (marketQuote != null)
                {
                    Utils.QL_REQUIRE(marketQuote.GetInstrumentType() == MarketDatum.InstrumentType.ZERO, () => "Market quote not of type zero.");
                    ZeroQuote zeroQuote = marketQuote as ZeroQuote;
                    zeroQuotes.Add(zeroQuote);
                }
                else
                {
                    Utils.QL_FAIL("Could not find quote for ID " + zeroQuoteIDs[i] + " with as of date " + _asofDate + ".");
                }
            }

            // Create the (date, zero) pairs.
            Dictionary <Date, double> data = new Dictionary <Date, double>();
            Convention convention          = _conventions.Get(_curveSegments[0].ConventionsID());

            Utils.QL_REQUIRE(convention != null, () => "No conventions found with ID: " + _curveSegments[0].ConventionsID());
            Utils.QL_REQUIRE(convention.ConventionType() == Convention.Type.Zero, () => "Conventions ID does not give zero rate conventions.");
            ZeroRateConvention zeroConvention  = convention as ZeroRateConvention;
            DayCounter         quoteDayCounter = zeroConvention.DayCounter();

            for (int i = 0; i < zeroQuotes.Count; ++i)
            {
                Utils.QL_REQUIRE(quoteDayCounter == zeroQuotes[i].DayCounter(), () => "The day counter should be the same between the conventions and the quote.");

                if (!zeroQuotes[i].TenorBased())
                {
                    data[zeroQuotes[i].Date()] = zeroQuotes[i].Quote().link.value();
                }
                else
                {
                    Utils.QL_REQUIRE(zeroConvention.TenorBased(), () => "Using tenor based zero rates without tenor based zero rate conventions.");


                    Date zeroDate = _asofDate;
                    if (zeroConvention.SpotLag() > 0)
                    {
                    }

                    zeroDate       = zeroConvention.SpotCalendar().advance(zeroDate, new Period(zeroConvention.SpotLag(), TimeUnit.Days));
                    zeroDate       = zeroConvention.TenorCalendar().advance(zeroDate, zeroQuotes[i].Tenor(), zeroConvention.RollConvention(), zeroConvention.Eom());
                    data[zeroDate] = zeroQuotes[i].Quote().link.value();
                }
            }

            Utils.QL_REQUIRE(data.Count > 0, () => "No market data found for curve spec " + _curveSpec.Name() + " with as of date " + _asofDate);


            // \todo review - more flexible (flat vs. linear extrap)?
            if (data.Keys.First() > _asofDate)
            {
                double rate = data.Values.First();
                data[_asofDate] = rate;
                //LOG("Insert zero curve point at time zero for " + curveSpec_.name() + ": "+ "date " + _asofDate + ", "+"zero " + data[_asofDate]);
            }

            Utils.QL_REQUIRE(data.Count > 1, () => "The single zero rate quote provided should be associated with a date greater than as of date.");

            // First build temporary curves
            List <Date>   dates     = new List <Date>();
            List <double> zeroes    = new List <double>();
            List <double> discounts = new List <double>();

            dates.Add(data.Keys.First());
            zeroes.Add(data.Values.First());
            discounts.Add(1.0);

            Compounding zeroCompounding     = zeroConvention.Compounding();
            Frequency   zeroCompoundingFreq = zeroConvention.CompoundingFrequency();
            Dictionary <Date, double> it;

            foreach (KeyValuePair <Date, double> kvp in data)
            {
                Date   d = kvp.Key;
                double r = kvp.Value;

                dates.Add(d);
                InterestRate tempRate = new InterestRate(r, quoteDayCounter, zeroCompounding, zeroCompoundingFreq);
                double       t        = quoteDayCounter.yearFraction(_asofDate, d);
                /* Convert zero rate to continuously compounded if necessary */
                if (zeroCompounding == Compounding.Continuous)
                {
                    zeroes.Add(r);
                }
                else
                {
                    zeroes.Add(tempRate.equivalentRate(Compounding.Continuous, Frequency.Annual, t).value());
                }
                discounts.Add(tempRate.discountFactor(t));
                //LOG("Add zero curve point for " + curveSpec_.name() + ": " + dates.Last() + " " + zeroes.Last() + " / " + discounts.Last());
            }

            Utils.QL_REQUIRE(dates.Count == zeroes.Count, () => "Date and zero vectors differ in size.");
            Utils.QL_REQUIRE(dates.Count == discounts.Count, () => "Date and discount vectors differ in size.");

            // Now build curve with requested conventions
            if (_interpolationVariable == YieldCurve.InterpolationVariable.Zero)
            {
                YieldTermStructure tempCurve = Zerocurve(dates, zeroes, quoteDayCounter);
                zeroes.Clear();
                for (int i = 0; i < dates.Count; ++i)
                {
                    double zero = tempCurve.zeroRate(dates[i], _zeroDayCounter, Compounding.Continuous).value();
                    zeroes.Add(zero);
                }

                _p = Zerocurve(dates, zeroes, _zeroDayCounter);
            }
            else if (_interpolationVariable == YieldCurve.InterpolationVariable.Discount)
            {
                YieldTermStructure tempCurve = Discountcurve(dates, discounts, quoteDayCounter);
                discounts.Clear();
                for (int i = 0; i < dates.Count; ++i)
                {
                    double discount = tempCurve.discount(dates[i]);
                    discounts.Add(discount);
                }
                _p = Discountcurve(dates, discounts, _zeroDayCounter);
            }
            else
            {
                Utils.QL_FAIL("Unknown yield curve interpolation variable.");
            }
        }
 public InterestRate forwardRate(double t1, double t2, Compounding arg2, Frequency f, bool extrapolate) {
   InterestRate ret = new InterestRate(NQuantLibcPINVOKE.YieldTermStructureHandle_forwardRate__SWIG_3(swigCPtr, t1, t2, (int)arg2, (int)f, extrapolate), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #12
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(InterestRate obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
Beispiel #13
0
 public InterestRate equivalentRate(DayCounter resultDayCounter, Compounding comp, Frequency freq, Date d1, Date d2) {
   InterestRate ret = new InterestRate(NQuantLibcPINVOKE.InterestRate_equivalentRate__SWIG_3(swigCPtr, DayCounter.getCPtr(resultDayCounter), (int)comp, (int)freq, Date.getCPtr(d1), Date.getCPtr(d2)), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #14
0
        public static double yieldValueBasisPoint(Bond bond, InterestRate yield)
        {
            double ret = NQuantLibcPINVOKE.BondFunctions_yieldValueBasisPoint__SWIG_1(Bond.getCPtr(bond), InterestRate.getCPtr(yield));

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Beispiel #15
0
        public static double convexity(Leg arg0, InterestRate arg1, bool includeSettlementDateFlows)
        {
            double ret = NQuantLibcPINVOKE.CashFlows_convexity__SWIG_2(Leg.getCPtr(arg0), InterestRate.getCPtr(arg1), includeSettlementDateFlows);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            DateTime timer = DateTime.Now;

            Date today = new Date(16, Month.October, 2007);

            Settings.setEvaluationDate(today);

            Console.WriteLine();
            Console.WriteLine("Pricing a callable fixed rate bond using");
            Console.WriteLine("Hull White model w/ reversion parameter = 0.03");
            Console.WriteLine("BAC4.65 09/15/12  ISIN: US06060WBJ36");
            Console.WriteLine("roughly five year tenor, quarterly coupon and call dates");
            Console.WriteLine("reference date is : " + today.ToLongDateString());
            Console.WriteLine("");

            /* Bloomberg OAS1: "N" model (Hull White)
             * varying volatility parameter
             *
             * The curve entered into Bloomberg OAS1 is a flat curve,
             * at constant yield = 5.5%, semiannual compounding.
             * Assume here OAS1 curve uses an ACT/ACT day counter,
             * as documented in PFC1 as a "default" in the latter case.
             */

            // set up a flat curve corresponding to Bloomberg flat curve

            double       bbCurveRate  = 0.055;
            DayCounter   bbDayCounter = new ActualActual(ActualActual.Convention.Bond);
            InterestRate bbIR         = new InterestRate(bbCurveRate, bbDayCounter, Compounding.Compounded, Frequency.Semiannual);

            Handle <YieldTermStructure> termStructure = new Handle <YieldTermStructure>(flatRate(today,
                                                                                                 bbIR.rate(),
                                                                                                 bbIR.dayCounter(),
                                                                                                 bbIR.compounding(),
                                                                                                 bbIR.frequency()));
            // set up the call schedule

            CallabilitySchedule callSchedule = new CallabilitySchedule();
            double callPrice         = 100.0;
            int    numberOfCallDates = 24;
            Date   callDate          = new Date(15, Month.September, 2006);

            for (int i = 0; i < numberOfCallDates; i++)
            {
                Calendar nullCalendar = new NullCalendar();

                Callability.Price myPrice = new Callability.Price(callPrice, Callability.Price.Type.Clean);
                callSchedule.Add(new Callability(myPrice, Callability.Type.Call, callDate));
                callDate = nullCalendar.advance(callDate, 3, TimeUnit.Months);
            }

            // set up the callable bond

            Date      dated          = new Date(16, Month.September, 2004);
            Date      issue          = dated;
            Date      maturity       = new Date(15, Month.September, 2012);
            int       settlementDays = 3; // Bloomberg OAS1 settle is Oct 19, 2007
            Calendar  bondCalendar   = new UnitedStates(UnitedStates.Market.GovernmentBond);
            double    coupon         = .0465;
            Frequency frequency      = Frequency.Quarterly;
            double    redemption     = 100.0;
            double    faceAmount     = 100.0;

            /* The 30/360 day counter Bloomberg uses for this bond cannot
             * reproduce the US Bond/ISMA (constant) cashflows used in PFC1.
             * Therefore use ActAct(Bond)
             */
            DayCounter bondDayCounter = new ActualActual(ActualActual.Convention.Bond);

            // PFC1 shows no indication dates are being adjusted
            // for weekends/holidays for vanilla bonds
            BusinessDayConvention accrualConvention = BusinessDayConvention.Unadjusted;
            BusinessDayConvention paymentConvention = BusinessDayConvention.Unadjusted;

            Schedule sch = new Schedule(dated, maturity, new Period(frequency), bondCalendar,
                                        accrualConvention, accrualConvention,
                                        DateGeneration.Rule.Backward, false);

            int    maxIterations      = 1000;
            double accuracy           = 1e-8;
            int    gridIntervals      = 40;
            double reversionParameter = .03;

            // output price/yield results for varying volatility parameter

            double sigma = Const.QL_EPSILON; // core dumps if zero on Cygwin

            ShortRateModel hw0 = new HullWhite(termStructure, reversionParameter, sigma);

            IPricingEngine engine0 = new TreeCallableFixedRateBondEngine(hw0, gridIntervals, termStructure);

            CallableFixedRateBond callableBond = new CallableFixedRateBond(settlementDays, faceAmount, sch,
                                                                           new InitializedList <double>(1, coupon),
                                                                           bondDayCounter, paymentConvention,
                                                                           redemption, issue, callSchedule);

            callableBond.setPricingEngine(engine0);

            Console.WriteLine("sigma/vol (%) = {0:0.00}", (100.0 * sigma));

            Console.WriteLine("QLNet price/yld (%)  {0:0.00} / {1:0.00} ",
                              callableBond.cleanPrice(),
                              100.0 * callableBond.yield(bondDayCounter,
                                                         Compounding.Compounded,
                                                         frequency,
                                                         accuracy,
                                                         maxIterations));
            Console.WriteLine("Bloomberg price/yld (%) 96,50 / 5,47");
            Console.WriteLine("");
            //

            sigma = .01;

            Console.WriteLine("sigma/vol (%) = {0:0.00}", (100.0 * sigma));

            ShortRateModel hw1 = new HullWhite(termStructure, reversionParameter, sigma);

            IPricingEngine engine1 = new TreeCallableFixedRateBondEngine(hw1, gridIntervals, termStructure);

            callableBond.setPricingEngine(engine1);

            Console.WriteLine("QLNet price/yld (%)  {0:0.00} / {1:0.00} ",
                              callableBond.cleanPrice(),
                              100.0 * callableBond.yield(bondDayCounter,
                                                         Compounding.Compounded,
                                                         frequency,
                                                         accuracy,
                                                         maxIterations));

            Console.WriteLine("Bloomberg price/yld (%)  95,68 / 5,66");
            Console.WriteLine("");

            //

            sigma = .03;

            Console.WriteLine("sigma/vol (%) = {0:0.00}", (100.0 * sigma));

            ShortRateModel hw2 = new HullWhite(termStructure, reversionParameter, sigma);

            IPricingEngine engine2 = new TreeCallableFixedRateBondEngine(hw2, gridIntervals, termStructure);

            callableBond.setPricingEngine(engine2);

            Console.WriteLine("QLNet price/yld (%)  {0:0.00} / {1:0.00} ",
                              callableBond.cleanPrice(),
                              100.0 * callableBond.yield(bondDayCounter,
                                                         Compounding.Compounded,
                                                         frequency,
                                                         accuracy,
                                                         maxIterations));

            Console.WriteLine("Bloomberg price/yld (%) 92,34 / 6,49");
            Console.WriteLine("");
            //

            sigma = .06;

            Console.WriteLine("sigma/vol (%) = {0:0.00}", (100.0 * sigma));

            ShortRateModel hw3 = new HullWhite(termStructure, reversionParameter, sigma);

            IPricingEngine engine3 = new TreeCallableFixedRateBondEngine(hw3, gridIntervals, termStructure);

            callableBond.setPricingEngine(engine3);

            Console.WriteLine("QLNet price/yld (%)  {0:0.00} / {1:0.00} ",
                              callableBond.cleanPrice(),
                              100.0 * callableBond.yield(bondDayCounter,
                                                         Compounding.Compounded,
                                                         frequency,
                                                         accuracy,
                                                         maxIterations));

            Console.WriteLine("Bloomberg price/yld (%) 87,16 / 7,83");
            Console.WriteLine("");
            //

            sigma = .12;

            Console.WriteLine("sigma/vol (%) = {0:0.00}", (100.0 * sigma));

            ShortRateModel hw4 = new HullWhite(termStructure, reversionParameter, sigma);

            IPricingEngine engine4 = new TreeCallableFixedRateBondEngine(hw4, gridIntervals, termStructure);

            callableBond.setPricingEngine(engine4);

            Console.WriteLine("QLNet price/yld (%)  {0:0.00} / {1:0.00} ",
                              callableBond.cleanPrice(),
                              100.0 * callableBond.yield(bondDayCounter,
                                                         Compounding.Compounded,
                                                         frequency,
                                                         accuracy,
                                                         maxIterations));

            Console.WriteLine("Bloomberg price/yld (%) 77,31 / 10,65");

            Console.WriteLine(" \nRun completed in {0}", DateTime.Now - timer);
            Console.WriteLine();

            Console.Write("Press any key to continue ...");
            Console.ReadKey();
        }
Beispiel #17
0
        public static double basisPointValue(Leg leg, InterestRate yield, bool includeSettlementDateFlows)
        {
            double ret = NQuantLibcPINVOKE.CashFlows_basisPointValue__SWIG_2(Leg.getCPtr(leg), InterestRate.getCPtr(yield), includeSettlementDateFlows);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Beispiel #18
0
 /// <summary>
 /// Stringify investment
 /// </summary>
 /// <returns></returns>
 public override string ToString()
 {
     return($"Investment ID {Id}, amount {Amount.ToString("F2")}, interest rate {InterestRate.ToString("F2")} %");
 }
Beispiel #19
0
        public void provide_monthly_interest_rate()
        {
            var interestRate = new InterestRate(0.012d);

            interestRate.Monthly.ShouldBeEquivalentTo(0.001d);
        }
Beispiel #20
0
 public static double basisPointValue(Leg leg, InterestRate yield, bool includeSettlementDateFlows) {
   double ret = NQuantLibcPINVOKE.CashFlows_basisPointValue__SWIG_2(Leg.getCPtr(leg), InterestRate.getCPtr(yield), includeSettlementDateFlows);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #21
0
        public void provide_annual_interest_rate()
        {
            var interestRate = new InterestRate(0.07d);

            interestRate.Annual.ShouldBeEquivalentTo(0.07d);
        }
Beispiel #22
0
 public static double duration(Bond bond, InterestRate yield, Duration.Type type, Date settlementDate) {
   double ret = NQuantLibcPINVOKE.BondFunctions_duration__SWIG_0(Bond.getCPtr(bond), InterestRate.getCPtr(yield), (int)type, Date.getCPtr(settlementDate));
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #23
0
 public InterestRate zeroRate(Date d, DayCounter arg1, Compounding arg2, Frequency f) {
   InterestRate ret = new InterestRate(NQuantLibcPINVOKE.YieldTermStructure_zeroRate__SWIG_1(swigCPtr, Date.getCPtr(d), DayCounter.getCPtr(arg1), (int)arg2, (int)f), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #24
0
 public InterestRate equivalentRate(Compounding comp, Frequency freq, double t) {
   InterestRate ret = new InterestRate(NQuantLibcPINVOKE.InterestRate_equivalentRate__SWIG_0(swigCPtr, (int)comp, (int)freq, t), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #25
0
 public InterestRate zeroRate(double t, Compounding arg1, Frequency f, bool extrapolate) {
   InterestRate ret = new InterestRate(NQuantLibcPINVOKE.YieldTermStructure_zeroRate__SWIG_3(swigCPtr, t, (int)arg1, (int)f, extrapolate), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
            public void ToRow(DataTable tbl)
            {
                tbl.Rows.Add(
                    CustomerID.ToString("G0", gb),

                    CashRequestID.ToString("G0", gb),
                    CreationDate.ToString("d/MMM/yyyy H:mm:ss", gb),
                    ManualDecisionTime.ToString("d/MMM/yyyy H:mm:ss", gb),
                    ApprovedAmount.ToString("C0", gb),

                    InterestRate.ToString("P2", gb),
                    RepaymentPeriod.ToString("G0", gb),
                    ManualSetupFeePercent.ToString("P2", gb),
                    BrokerSetupFeePercent.ToString("P2", gb),

                    SpreadSetupFee ? "spread" : "deduced",
                    string.Empty,
                    string.Empty,
                    string.Empty,

                    "total"
                    );

                var first = GetFirstTrail();
                var main  = GetMainTrail();
                var last  = GetLastTrail();

                if (first.IsEmpty && main.IsEmpty && last.IsEmpty)
                {
                    return;
                }

                tbl.Rows.Add(
                    string.Empty,

                    first.GetTrailID("First"),
                    first.DecisionTimeStr,
                    first.StatusStr,
                    first.TagStr,

                    main.GetTrailID("Main"),
                    main.DecisionTimeStr,
                    main.StatusStr,
                    main.TagStr,

                    last.GetTrailID("Last"),
                    last.DecisionTimeStr,
                    last.StatusStr,
                    last.TagStr,

                    string.Empty
                    );

                var firstTraces = first.Traces;
                var mainTraces  = main.Traces;
                var lastTraces  = last.Traces;

                int maxLen = Math.Max(firstTraces.Length, Math.Max(mainTraces.Length, lastTraces.Length));

                for (int i = 0; i < maxLen; i++)
                {
                    NotAutoApprovedTrace f = i < firstTraces.Length ? firstTraces[i] : new NotAutoApprovedTrace();
                    NotAutoApprovedTrace m = i < mainTraces.Length ? mainTraces[i] : new NotAutoApprovedTrace();
                    NotAutoApprovedTrace l = i < lastTraces.Length ? lastTraces[i] : new NotAutoApprovedTrace();

                    tbl.Rows.Add(
                        string.Empty,

                        string.Empty,
                        f.TraceNameStr,
                        f.CommentStr,
                        string.Empty,

                        string.Empty,
                        m.TraceNameStr,
                        m.Comment,
                        string.Empty,

                        string.Empty,
                        l.TraceNameStr,
                        l.CommentStr,
                        string.Empty,

                        string.Empty
                        );
                }         // for i
            }             // ToRow
Beispiel #27
0
 public InterestRate zeroRate(double t, Compounding arg1) {
   InterestRate ret = new InterestRate(NQuantLibcPINVOKE.YieldTermStructure_zeroRate__SWIG_5(swigCPtr, t, (int)arg1), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #28
0
        public static double cleanPrice(Bond bond, InterestRate yield)
        {
            double ret = NQuantLibcPINVOKE.BondFunctions_cleanPrice__SWIG_3(Bond.getCPtr(bond), InterestRate.getCPtr(yield));

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Beispiel #29
0
 public InterestRate forwardRate(Date d1, Date d2, DayCounter arg2, Compounding arg3) {
   InterestRate ret = new InterestRate(NQuantLibcPINVOKE.YieldTermStructure_forwardRate__SWIG_2(swigCPtr, Date.getCPtr(d1), Date.getCPtr(d2), DayCounter.getCPtr(arg2), (int)arg3), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #30
0
        public static double basisPointValue(Bond bond, InterestRate yield, Date settlementDate)
        {
            double ret = NQuantLibcPINVOKE.BondFunctions_basisPointValue__SWIG_0(Bond.getCPtr(bond), InterestRate.getCPtr(yield), Date.getCPtr(settlementDate));

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Beispiel #31
0
 public InterestRate forwardRate(double t1, double t2, Compounding arg2) {
   InterestRate ret = new InterestRate(NQuantLibcPINVOKE.YieldTermStructure_forwardRate__SWIG_5(swigCPtr, t1, t2, (int)arg2), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #32
0
 public static double cleanPrice(Bond bond, InterestRate yield, Date settlementDate = null)
 {
     return(dirtyPrice(bond, yield, settlementDate) - bond.accruedAmount(settlementDate));
 }
        /// <summary>
        /// Returns true if BookSummary instances are equal
        /// </summary>
        /// <param name="other">Instance of BookSummary to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(BookSummary other)
        {
            if (other is null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     UnderlyingIndex == other.UnderlyingIndex ||
                     UnderlyingIndex != null &&
                     UnderlyingIndex.Equals(other.UnderlyingIndex)
                     ) &&
                 (
                     Volume == other.Volume ||
                     Volume != null &&
                     Volume.Equals(other.Volume)
                 ) &&
                 (
                     VolumeUsd == other.VolumeUsd ||
                     VolumeUsd != null &&
                     VolumeUsd.Equals(other.VolumeUsd)
                 ) &&
                 (
                     UnderlyingPrice == other.UnderlyingPrice ||
                     UnderlyingPrice != null &&
                     UnderlyingPrice.Equals(other.UnderlyingPrice)
                 ) &&
                 (
                     BidPrice == other.BidPrice ||
                     BidPrice != null &&
                     BidPrice.Equals(other.BidPrice)
                 ) &&
                 (
                     OpenInterest == other.OpenInterest ||
                     OpenInterest != null &&
                     OpenInterest.Equals(other.OpenInterest)
                 ) &&
                 (
                     QuoteCurrency == other.QuoteCurrency ||
                     QuoteCurrency != null &&
                     QuoteCurrency.Equals(other.QuoteCurrency)
                 ) &&
                 (
                     High == other.High ||
                     High != null &&
                     High.Equals(other.High)
                 ) &&
                 (
                     EstimatedDeliveryPrice == other.EstimatedDeliveryPrice ||
                     EstimatedDeliveryPrice != null &&
                     EstimatedDeliveryPrice.Equals(other.EstimatedDeliveryPrice)
                 ) &&
                 (
                     Last == other.Last ||
                     Last != null &&
                     Last.Equals(other.Last)
                 ) &&
                 (
                     MidPrice == other.MidPrice ||
                     MidPrice != null &&
                     MidPrice.Equals(other.MidPrice)
                 ) &&
                 (
                     InterestRate == other.InterestRate ||
                     InterestRate != null &&
                     InterestRate.Equals(other.InterestRate)
                 ) &&
                 (
                     Funding8h == other.Funding8h ||
                     Funding8h != null &&
                     Funding8h.Equals(other.Funding8h)
                 ) &&
                 (
                     MarkPrice == other.MarkPrice ||
                     MarkPrice != null &&
                     MarkPrice.Equals(other.MarkPrice)
                 ) &&
                 (
                     AskPrice == other.AskPrice ||
                     AskPrice != null &&
                     AskPrice.Equals(other.AskPrice)
                 ) &&
                 (
                     InstrumentName == other.InstrumentName ||
                     InstrumentName != null &&
                     InstrumentName.Equals(other.InstrumentName)
                 ) &&
                 (
                     Low == other.Low ||
                     Low != null &&
                     Low.Equals(other.Low)
                 ) &&
                 (
                     BaseCurrency == other.BaseCurrency ||
                     BaseCurrency != null &&
                     BaseCurrency.Equals(other.BaseCurrency)
                 ) &&
                 (
                     CreationTimestamp == other.CreationTimestamp ||
                     CreationTimestamp != null &&
                     CreationTimestamp.Equals(other.CreationTimestamp)
                 ) &&
                 (
                     CurrentFunding == other.CurrentFunding ||
                     CurrentFunding != null &&
                     CurrentFunding.Equals(other.CurrentFunding)
                 ));
        }
Beispiel #34
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(InterestRate obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (UnderlyingIndex != null)
         {
             hashCode = hashCode * 59 + UnderlyingIndex.GetHashCode();
         }
         if (Volume != null)
         {
             hashCode = hashCode * 59 + Volume.GetHashCode();
         }
         if (VolumeUsd != null)
         {
             hashCode = hashCode * 59 + VolumeUsd.GetHashCode();
         }
         if (UnderlyingPrice != null)
         {
             hashCode = hashCode * 59 + UnderlyingPrice.GetHashCode();
         }
         if (BidPrice != null)
         {
             hashCode = hashCode * 59 + BidPrice.GetHashCode();
         }
         if (OpenInterest != null)
         {
             hashCode = hashCode * 59 + OpenInterest.GetHashCode();
         }
         if (QuoteCurrency != null)
         {
             hashCode = hashCode * 59 + QuoteCurrency.GetHashCode();
         }
         if (High != null)
         {
             hashCode = hashCode * 59 + High.GetHashCode();
         }
         if (EstimatedDeliveryPrice != null)
         {
             hashCode = hashCode * 59 + EstimatedDeliveryPrice.GetHashCode();
         }
         if (Last != null)
         {
             hashCode = hashCode * 59 + Last.GetHashCode();
         }
         if (MidPrice != null)
         {
             hashCode = hashCode * 59 + MidPrice.GetHashCode();
         }
         if (InterestRate != null)
         {
             hashCode = hashCode * 59 + InterestRate.GetHashCode();
         }
         if (Funding8h != null)
         {
             hashCode = hashCode * 59 + Funding8h.GetHashCode();
         }
         if (MarkPrice != null)
         {
             hashCode = hashCode * 59 + MarkPrice.GetHashCode();
         }
         if (AskPrice != null)
         {
             hashCode = hashCode * 59 + AskPrice.GetHashCode();
         }
         if (InstrumentName != null)
         {
             hashCode = hashCode * 59 + InstrumentName.GetHashCode();
         }
         if (Low != null)
         {
             hashCode = hashCode * 59 + Low.GetHashCode();
         }
         if (BaseCurrency != null)
         {
             hashCode = hashCode * 59 + BaseCurrency.GetHashCode();
         }
         if (CreationTimestamp != null)
         {
             hashCode = hashCode * 59 + CreationTimestamp.GetHashCode();
         }
         if (CurrentFunding != null)
         {
             hashCode = hashCode * 59 + CurrentFunding.GetHashCode();
         }
         return(hashCode);
     }
 }
Beispiel #36
0
        public void testBrazilianCached()
        {
            //("Testing Brazilian public bond prices against cached values...");

            CommonVars vars = new CommonVars();

            double faceAmount = 1000.0;
            double redemption = 100.0;
            Date   issueDate  = new Date(1, Month.January, 2007);

            Date today = new Date(6, Month.June, 2007);

            Settings.setEvaluationDate(today);

            // NTN-F maturity dates
            InitializedList <Date> maturityDates = new InitializedList <Date>(6);

            maturityDates[0] = new Date(1, Month.January, 2008);
            maturityDates[1] = new Date(1, Month.January, 2010);
            maturityDates[2] = new Date(1, Month.July, 2010);
            maturityDates[3] = new Date(1, Month.January, 2012);
            maturityDates[4] = new Date(1, Month.January, 2014);
            maturityDates[5] = new Date(1, Month.January, 2017);

            // NTN-F yields
            InitializedList <double> yields = new InitializedList <double>(6);

            yields[0] = 0.114614;
            yields[1] = 0.105726;
            yields[2] = 0.105328;
            yields[3] = 0.104283;
            yields[4] = 0.103218;
            yields[5] = 0.102948;

            // NTN-F prices
            InitializedList <double> prices = new InitializedList <double>(6);

            prices[0] = 1034.63031372;
            prices[1] = 1030.09919487;
            prices[2] = 1029.98307160;
            prices[3] = 1028.13585068;
            prices[4] = 1028.33383817;
            prices[5] = 1026.19716497;

            int settlementDays = 1;

            vars.faceAmount = 1000.0;

            // The tolerance is high because Andima truncate yields
            double tolerance = 1.0e-4;

            InitializedList <InterestRate> couponRates = new InitializedList <InterestRate>(1);

            couponRates[0] = new InterestRate(0.1, new Thirty360(), Compounding.Compounded, Frequency.Annual);

            for (int bondIndex = 0; bondIndex < maturityDates.Count; bondIndex++)
            {
                // plain
                InterestRate yield = new InterestRate(yields[bondIndex], new Business252(new Brazil()),
                                                      Compounding.Compounded, Frequency.Annual);

                Schedule schedule = new Schedule(new Date(1, Month.January, 2007),
                                                 maturityDates[bondIndex], new Period(Frequency.Semiannual),
                                                 new Brazil(Brazil.Market.Settlement),
                                                 BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                                 DateGeneration.Rule.Backward, false);


                FixedRateBond bond = new FixedRateBond(settlementDays,
                                                       faceAmount,
                                                       schedule,
                                                       couponRates,
                                                       BusinessDayConvention.Following,
                                                       redemption,
                                                       issueDate);

                double cachedPrice = prices[bondIndex];

                double price = vars.faceAmount * (bond.cleanPrice(yield.rate(),
                                                                  yield.dayCounter(),
                                                                  yield.compounding(),
                                                                  yield.frequency(),
                                                                  today) + bond.accruedAmount(today)) / 100;
                if (Math.Abs(price - cachedPrice) > tolerance)
                {
                    Assert.Fail("failed to reproduce cached price:\n"
                                + "    calculated: " + price + "\n"
                                + "    expected:   " + cachedPrice + "\n"
                                + "    error:      " + (price - cachedPrice) + "\n"
                                );
                }
            }
        }
Beispiel #37
0
 protected override void performCalculations()
 {
     rate_ = new InterestRate(forward_.value(), dayCounter(), compounding_, frequency_);
 }
        public ActionResult Create([Bind(Include = "Id,Acronym,Name,MinDate,MinPayIn,Status")] Term term, string ir, string mindate)
        {
            string msg = null, msgacronym = null, msgname = null, msgmindate = null, msgminpayin = null, msgir = null;

            if (String.IsNullOrEmpty(term.Name))
            {
                msgname = "Nhập tên loại kỳ hạn !";
            }
            if (String.IsNullOrEmpty(term.Acronym))
            {
                msgacronym = "Nhập mã loại kỳ hạn !";
            }
            else
            {
                int termcount = db.Terms.Where(n => n.Acronym == term.Acronym && n.Status == 2).Count();
                if (termcount > 0)
                {
                    msgacronym = "Loại kỳ hạn này đã tồn tại !";
                }
            }
            if (String.IsNullOrEmpty(mindate))
            {
                msgmindate = "Nhập số ngày gửi tối thiểu !";
            }
            else if (term.MinDate < 0)
            {
                msgmindate = "Số ngày gửi tối thiểu không thể nhỏ hơn 0 !";
            }
            else if (term.MinDate > 3650)
            {
                msgmindate = "Số ngày gửi tối thiểu không thể lớn hơn 3650 !";
            }
            if (term.MinPayIn == 0)
            {
                msgminpayin = "Nhập số tiền gửi tối thiểu !";
            }
            else if (term.MinPayIn < 0)
            {
                msgminpayin = "Số tiền gửi tối thiểu không thể nhỏ hơn 0 !";
            }
            else if (term.MinPayIn % 50000 > 0)
            {
                msgminpayin = "Đơn vị tiền nhỏ nhất là 50.000 !";
            }
            if (String.IsNullOrEmpty(ir))
            {
                msgir = "Nhập lãi suất !";
            }
            else if (Convert.ToDouble(ir) > 100)
            {
                msgir = "Lãi suất không thể lớn hơn 100 %";
            }
            else if (Convert.ToDouble(ir) <= 0)
            {
                msgir = "Lãi suất phải lớn hơn 0 %";
            }

            if (msgacronym == null && msgname == null && msgmindate == null && msgminpayin == null && msgir == null)
            {
                msg         = "completed";
                term.Status = 2;
                db.Terms.Add(term);
                Bank         bank         = db.Banks.FirstOrDefault(n => n.Status == 2);
                InterestRate interestRate = new InterestRate();
                interestRate.BankId  = bank.Id;
                interestRate.TermId  = term.Id;
                interestRate.Acronym = bank.Acronym + "_" + term.Acronym;
                interestRate.Rate    = Convert.ToDouble(ir);
                interestRate.Status  = 2;
                db.InterestRates.Add(interestRate);
                db.SaveChanges();
                int termid = 0;
                termid = term.Id;
                return(Json(new { termid, msg }, JsonRequestBehavior.AllowGet));
            }
            return(Json(new { msgacronym, msgname, msgmindate, msgminpayin, msgir }, JsonRequestBehavior.AllowGet));
        }
Beispiel #39
0
        internal static InterestRate[] GetInterestRates(Guid[] orderIds)
        {
            string xmlOrderIds = "<Orders>";
            foreach (Guid orderId in orderIds)
            {
                xmlOrderIds += "<Order ID=\"" + orderId.ToString() + "\" />";
            }
            xmlOrderIds += "</Orders>";
            string sql = string.Format("Exec dbo.P_GetInterestRate '{0}'", xmlOrderIds);
            DataSet dataSet = IDataAccess.GetData(sql, SettingManager.Default.ConnectionString);

            InterestRate[] interestRates = new InterestRate[dataSet.Tables[0].Rows.Count];
            int index = 0;
            foreach (DataRow dataRow in dataSet.Tables[0].Rows)
            {
                InterestRate interestRate = new InterestRate();
                interestRate.OrderId = (Guid)dataRow["Id"];
                interestRate.InterestId = (Guid)dataRow["InterestRateID"];
                if (dataRow["InterestRateBuy"] == DBNull.Value)
                {
                    interestRate.Buy = null;
                }
                else
                {
                    interestRate.Buy = (decimal)dataRow["InterestRateBuy"];
                }
                if (dataRow["InterestRateSell"] == DBNull.Value)
                {
                    interestRate.Sell = null;
                }
                else
                {
                    interestRate.Sell = (decimal)dataRow["InterestRateSell"];
                }
                interestRates[index++] = interestRate;
            }
            return interestRates;
        }
Beispiel #40
0
 public static double convexity(Leg arg0, InterestRate arg1, bool includeSettlementDateFlows) {
   double ret = NQuantLibcPINVOKE.CashFlows_convexity__SWIG_2(Leg.getCPtr(arg0), InterestRate.getCPtr(arg1), includeSettlementDateFlows);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #41
0
        internal static InterestRate[] GetInterestRates2(Guid userID, Guid interestRateId)
        {
            string sql = string.Format("Exec dbo.P_GetInterestRate2 '{0}','{1}'", userID, interestRateId);
            DataSet dataSet = IDataAccess.GetData(sql, SettingManager.Default.ConnectionString);
            InterestRate[] interestRates = new InterestRate[dataSet.Tables.Count];
            InterestRate interestRate1 = new InterestRate();
            interestRate1.InterestRates = new InterestRate[dataSet.Tables[0].Rows.Count];
            InterestRate interestRate2 = new InterestRate();
            interestRate2.InterestRates = new InterestRate[dataSet.Tables[1].Rows.Count];
            interestRates[0] = interestRate1;
            interestRates[1] = interestRate2;
            int index = 0;
            foreach (DataRow dataRow in dataSet.Tables[0].Rows)
            {
                InterestRate interestRate = new InterestRate();
                interestRate.OrderId = (Guid)dataRow["Id"];
                interestRate.InterestId = (Guid)dataRow["InterestRateID"];
                if (dataRow["InterestRateBuy"] == DBNull.Value)
                {
                    interestRate.Buy = null;
                }
                else
                {
                    interestRate.Buy = (decimal)dataRow["InterestRateBuy"];
                }
                if (dataRow["InterestRateSell"] == DBNull.Value)
                {
                    interestRate.Sell = null;
                }
                else
                {
                    interestRate.Sell = (decimal)dataRow["InterestRateSell"];
                }
                interestRates[0].InterestRates[index++] = interestRate;
            }

            index = 0;
            foreach (DataRow dataRow in dataSet.Tables[1].Rows)
            {
                InterestRate interestRate = new InterestRate();
                interestRate.InterestId = (Guid)dataRow["InterestRateID"];
                interestRate.Buy = (decimal)dataRow["InterestRateBuy"];
                interestRate.Sell = (decimal)dataRow["InterestRateSell"];
                interestRates[1].InterestRates[index++] = interestRate;
            }

            return interestRates;
        }
Beispiel #42
0
 public static double npv(Leg arg0, InterestRate arg1, bool includeSettlementDateFlows, Date settlementDate) {
   double ret = NQuantLibcPINVOKE.CashFlows_npv__SWIG_7(Leg.getCPtr(arg0), InterestRate.getCPtr(arg1), includeSettlementDateFlows, Date.getCPtr(settlementDate));
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #43
0
 public InterestRate forwardRate() {
   InterestRate ret = new InterestRate(NQuantLibcPINVOKE.ForwardRateAgreement_forwardRate(swigCPtr), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #44
0
 public InterestRate interestRate() {
   InterestRate ret = new InterestRate(NQuantLibcPINVOKE.FixedRateCoupon_interestRate(swigCPtr), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #45
0
        static void Main(string[] args)
        {
            double nominal = 575000000;

            Date _marketDate;
            Date _settlementDate;
            Dictionary <string, double> _depositRates;
            Dictionary <string, double> _swapRates;
            List <RateHelper>           _rateHelpers;
            Calendar _calendar   = new TARGET();
            int      _fixingDays = 2;

            _marketDate = new Date(new DateTime(2015, 12, 17));
            Settings.setEvaluationDate(_marketDate);

            _depositRates = new Dictionary <string, double>();
            _depositRates.Add("1M", 0.0045);
            _depositRates.Add("3M", 0.0070);
            _depositRates.Add("6M", 0.0090);

            _swapRates = new Dictionary <string, double>();
            _swapRates.Add("1Y", 0.0080);
            _swapRates.Add("2Y", 0.0109);
            _swapRates.Add("3Y", 0.0134);
            _swapRates.Add("4Y", 0.0153);
            _swapRates.Add("5Y", 0.0169);
            _swapRates.Add("7Y", 0.0193);
            _swapRates.Add("10Y", 0.0218);
            _swapRates.Add("30Y", 0.0262);

            _rateHelpers = new List <RateHelper>();
            foreach (var v in _depositRates)
            {
                SimpleQuote sq = new SimpleQuote(v.Value);
                _rateHelpers.Add(new DepositRateHelper(new Handle <Quote>(sq), new Period(v.Key),
                                                       _fixingDays, _calendar, BusinessDayConvention.ModifiedFollowing, true, new Actual360()));
            }
            foreach (var v in _swapRates)
            {
                SimpleQuote sq = new SimpleQuote(v.Value);
                _rateHelpers.Add(new SwapRateHelper(new Handle <Quote>(sq), new Period(v.Key),
                                                    _calendar, Frequency.Semiannual, BusinessDayConvention.Unadjusted,
                                                    new Thirty360(Thirty360.Thirty360Convention.USA), new Euribor3M()));
            }

            _marketDate     = _calendar.adjust(_marketDate);
            _settlementDate = _calendar.advance(_marketDate, _fixingDays, TimeUnit.Days);

            YieldTermStructure yieldTermStructure = new PiecewiseYieldCurve <Discount, LogLinear>(
                _settlementDate, _rateHelpers, new ActualActual(ActualActual.Convention.ISDA));

            RelinkableHandle <YieldTermStructure> yieldTermStructureHandle = new RelinkableHandle <YieldTermStructure>();


            Frequency             fixedLegFrequency  = Frequency.Semiannual;
            BusinessDayConvention fixedLegConvention = BusinessDayConvention.ModifiedFollowing;
            DayCounter            fixedLegDayCounter = new Thirty360(Thirty360.Thirty360Convention.USA);
            double fixedRate = 0.0144;

            Frequency             floatLegFrequency  = Frequency.Quarterly;
            BusinessDayConvention floatLegConvention = BusinessDayConvention.ModifiedFollowing;
            DayCounter            floatLegDayCounter = new Actual360();
            IborIndex             iborIndex          = new Euribor3M(yieldTermStructureHandle);

            iborIndex.addFixing(new Date(18, Month.Aug, 2015), 0.0033285);
            iborIndex.addFixing(new Date(18, Month.Nov, 2015), 0.0036960);
            double floatSpread = 0.0;

            VanillaSwap.Type swapType = VanillaSwap.Type.Receiver;

            Date     maturity      = new Date(20, Month.Nov, 2018);
            Date     effective     = new Date(20, Month.Nov, 2013);
            Schedule fixedSchedule = new Schedule(effective, maturity, new Period(fixedLegFrequency), _calendar, fixedLegConvention, fixedLegConvention, DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(effective, maturity, new Period(floatLegFrequency), _calendar, floatLegConvention, floatLegConvention, DateGeneration.Rule.Forward, false);

            VanillaSwap vanillaSwap = new VanillaSwap(swapType, nominal, fixedSchedule, fixedRate, fixedLegDayCounter, floatSchedule, iborIndex, floatSpread, floatLegDayCounter);

            InterestRate        interestRate = new InterestRate(fixedRate, fixedLegDayCounter, Compounding.Simple, fixedLegFrequency);
            List <InterestRate> coupons      = new List <InterestRate>();

            for (int i = 0; i < fixedSchedule.Count; i++)
            {
                coupons.Add(interestRate);
            }
            FixedRateBond    fixedBond = new FixedRateBond(_fixingDays, nominal, fixedSchedule, coupons, BusinessDayConvention.ModifiedFollowing);
            FloatingRateBond floatBond = new FloatingRateBond(_fixingDays, nominal, floatSchedule, iborIndex, floatLegDayCounter);

            IPricingEngine bondPricingEngine = new DiscountingBondEngine(yieldTermStructureHandle);

            fixedBond.setPricingEngine(bondPricingEngine);
            floatBond.setPricingEngine(bondPricingEngine);

            IPricingEngine swapPricingEngine = new DiscountingSwapEngine(yieldTermStructureHandle);

            vanillaSwap.setPricingEngine(swapPricingEngine);

            yieldTermStructureHandle.linkTo(yieldTermStructure);

            double swapNPV      = vanillaSwap.NPV();
            double swapFixedNPV = vanillaSwap.fixedLegNPV();
            double swapFloatNPV = vanillaSwap.floatingLegNPV();

            double bondFixedNPV = fixedBond.NPV();
            double bondFloatNPV = floatBond.NPV();

            int    w = (swapType == VanillaSwap.Type.Receiver ? 1 : -1);
            double asBondsMarketValue      = w * (bondFixedNPV - bondFloatNPV);
            double asBondsMarketValueNoAcc = w * (fixedBond.cleanPrice() - floatBond.cleanPrice()) / 100.0 * nominal;
            double asBondsAccruedInterest  = asBondsMarketValue - asBondsMarketValueNoAcc;

            Console.WriteLine("Vanilla Swap Maket Value      : {0:N}", swapNPV);
            Console.WriteLine("As Bonds Market Value         : {0:N}", asBondsMarketValue);
            Console.WriteLine("As Bonds Market Value (no acc): {0:N}", asBondsMarketValueNoAcc);
            Console.WriteLine("As Bonds Accrued Interest     : {0:N}", asBondsAccruedInterest);

            Date   rollDate      = new Date(1, Month.Nov, 2015);
            double bondFixedCash = 0;

            foreach (CashFlow cf in fixedBond.cashflows())
            {
                if (cf.date() > rollDate & cf.date() <= _marketDate)
                {
                    bondFixedCash += cf.amount();
                }
            }
            double bondFloatCash = 0;

            foreach (CashFlow cf in floatBond.cashflows())
            {
                if (cf.date() > rollDate & cf.date() <= _marketDate)
                {
                    bondFloatCash += cf.amount();
                }
            }
            double asBondsCash = w * (bondFixedCash - bondFloatCash);

            Console.WriteLine("As Bonds Settled Cash         : {0:N}", asBondsCash);
        }
Beispiel #46
0
 public static double duration(Bond bond, InterestRate yield) {
   double ret = NQuantLibcPINVOKE.BondFunctions_duration__SWIG_2(Bond.getCPtr(bond), InterestRate.getCPtr(yield));
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
        public void loadPrime(String primeFilename)
        {
            ReadCSV csv = new ReadCSV(primeFilename);

            while (csv.Next())
            {
                DateTime date = csv.GetDate("date");
                double rate = csv.GetDouble("prime");
                InterestRate ir = new InterestRate(date, rate);
                this.rates.Add(ir);
            }

            csv.Close();
            this.rates.Sort();
        }
Beispiel #48
0
 public static double yieldValueBasisPoint(Bond bond, InterestRate yield) {
   double ret = NQuantLibcPINVOKE.BondFunctions_yieldValueBasisPoint__SWIG_1(Bond.getCPtr(bond), InterestRate.getCPtr(yield));
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Beispiel #49
0
 public static InterestRate impliedRate(double compound, DayCounter resultDC, Compounding comp, Frequency freq, Date d1, Date d2) {
   InterestRate ret = new InterestRate(NQuantLibcPINVOKE.InterestRate_impliedRate__SWIG_3(compound, DayCounter.getCPtr(resultDC), (int)comp, (int)freq, Date.getCPtr(d1), Date.getCPtr(d2)), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }