public static InterestRate ImpliedRate(IDayCounter dc, double compoundFactor, Compounding c, Frequency f, double time) { double r; if (Helper.Equals(compoundFactor, 1.0)) { r = 0.0; } else { switch (c) { case Compounding.Simple: r = (compoundFactor - 1.0)/time; break; case Compounding.Compounded: r = (Math.Pow(compoundFactor, 1.0 / ((double)f * time)) - 1.0) * (double)f; break; case Compounding.Continuous: r = Math.Log(compoundFactor)/time; break; default: throw new NotImplementedException($"Unknown Compounding {c}"); } } return new InterestRate(dc, r, c, f); }
public FlatForward(Date referenceDate, double forward, DayCounter dayCounter, Compounding compounding, Frequency frequency) : base(referenceDate, new Calendar(), dayCounter) { forward_ = new SimpleQuote(forward); compounding_ = compounding; frequency_ = frequency; }
public InterestRate EquivalentRate(IDayCounter dc, Compounding c, Frequency f, DateTimeOffset d1, DateTimeOffset d2) { var t1 = _dc.YearFraction(d1, d2); var t2 = dc.YearFraction(d1, d2); var compoundFactor = CompoundFactor(t1); return ImpliedRate(dc, compoundFactor, c, f, t2); }
public InterestRate(IDayCounter dc, double r, Compounding c, Frequency f) { _dc = dc; _r = r; _c = c; _f = f; }
// setup public CommonVars() { // force garbage collection // garbage collection in .NET is rather weird and we do need when we run several tests in a row GC.Collect(); // data calendar = new TARGET(); settlementDays = 2; today = new Date(9, Month.June, 2009); compounding = Compounding.Continuous; dayCount = new Actual360(); settlementDate = calendar.advance(today, settlementDays, TimeUnit.Days); Settings.setEvaluationDate(today); int[] ts = new int[] { 13, 41, 75, 165, 256, 345, 524, 703 }; double[] r = new double[] { 0.035, 0.033, 0.034, 0.034, 0.036, 0.037, 0.039, 0.040 }; List<double> rates = new List<double>() { 0.035 }; List<Date> dates = new List<Date>() { settlementDate }; for (int i = 0; i < 8; ++i) { dates.Add(calendar.advance(today, ts[i], TimeUnit.Days)); rates.Add(r[i]); } termStructure = new InterpolatedZeroCurve<Linear>(dates, rates, dayCount); }
static YieldTermStructure flatRate(Date today, double forward, DayCounter dc, Compounding compounding, Frequency frequency) { return new FlatForward(today, forward, dc, compounding, frequency); //FlatForward flatRate = new FlatForward(settlementDate, r.rate(), r.dayCounter(), r.compounding(), r.frequency()); }
public FlatForward(Date referenceDate, Quote forward, DayCounter dayCounter, Compounding compounding, Frequency frequency) : base(referenceDate, new Calendar(), dayCounter) { forward_ = forward; compounding_ = compounding; frequency_ = frequency; forward_.registerWith(update); }
public YieldFinder(double faceAmount, List<CashFlow> cashflows, double dirtyPrice, DayCounter dayCounter, Compounding compounding, Frequency frequency, Date settlement) { _faceAmount = faceAmount; _cashflows = cashflows; _dirtyPrice = dirtyPrice; _compounding = compounding; _dayCounter = dayCounter; _frequency = frequency; _settlement = settlement; }
public InterestRateData(double _r, Compounding _comp, Frequency _freq, double _t, Compounding _comp2, Frequency _freq2, double _expected, int _precision) { r = _r; comp = _comp; freq = _freq; t = _t; comp2 = _comp2; freq2 = _freq2; expected = _expected; precision = _precision; }
public InterestRate(double? r, DayCounter dc, Compounding comp, Frequency freq) { r_ = r; dc_ = dc; comp_ = comp; if (comp_ == Compounding.Compounded || comp_ == Compounding.SimpleThenCompounded) { freqMakesSense_ = true; if (!(freq != Frequency.Once && freq != Frequency.NoFrequency)) throw new ArgumentException("Frequency not allowed for this interest rate"); freq_ = (double)freq; } }
public ZeroSpreadedTermStructure(Handle<YieldTermStructure> h, Quote spread, Compounding comp, Frequency freq, DayCounter dc) { originalCurve_ = h; spread_ = spread; comp_ = comp; freq_ = freq; dc_ = dc; //QL_REQUIRE(h->dayCounter()==dc_, // "spread daycounter (" << dc_ << // ") must be the same of the curve to be spreaded (" << // originalCurve_->dayCounter() << // ")"); originalCurve_.registerWith(update); spread_.registerWith(update); }
public InterestRate zeroRate(Date d, DayCounter dayCounter, Compounding comp, Frequency freq, bool extrapolate) { if (d == referenceDate()) { double t = 0.0001; double compound = 1 / discount(t, extrapolate); return InterestRate.impliedRate(compound, t, dayCounter, comp, freq); } else { double compound = 1 / discount(d, extrapolate); return InterestRate.impliedRate(compound, referenceDate(), d, dayCounter, comp, freq); } }
//! Standard constructor public InterestRate(double r, DayCounter dc, Compounding comp, Frequency freq) { r_ = r; dc_ = dc; comp_ = comp; freqMakesSense_ = false; if (comp_ == Compounding.Compounded || comp_ == Compounding.SimpleThenCompounded) { freqMakesSense_ = true; Utils.QL_REQUIRE(freq != Frequency.Once && freq != Frequency.NoFrequency, "frequency not allowed for this interest rate"); freq_ = (double)freq; } }
public ZeroSpreadedTermStructure(Handle<YieldTermStructure> h, Handle<Quote> spread, Compounding comp = Compounding.Continuous, Frequency freq = Frequency.NoFrequency, DayCounter dc = null) { originalCurve_ = h; spread_ = spread; comp_ = comp; freq_ = freq; dc_ = dc; originalCurve_.registerWith(update); spread_.registerWith(update); }
public InterestRate zeroRate(double t, Compounding comp, Frequency freq) { return(zeroRate(t, comp, freq, false)); }
public static double yieldRidder(Ridder solver, Bond bond, double cleanPrice, DayCounter dayCounter, Compounding compounding, Frequency frequency, Date settlementDate) { double ret = NQuantLibcPINVOKE.BondFunctions_yieldRidder__SWIG_2(Ridder.getCPtr(solver), Bond.getCPtr(bond), cleanPrice, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency, Date.getCPtr(settlementDate)); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public FlatForward(Date referenceDate, QuoteHandle forward, DayCounter dayCounter, Compounding compounding, Frequency frequency) : this(NQuantLibcPINVOKE.new_FlatForward__SWIG_0(Date.getCPtr(referenceDate), QuoteHandle.getCPtr(forward), DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public ZeroSpreadedTermStructure(Handle <YieldTermStructure> h, Quote spread, Compounding comp, Frequency freq, DayCounter dc) { originalCurve_ = h; spread_ = spread; comp_ = comp; freq_ = freq; dc_ = dc; //QL_REQUIRE(h->dayCounter()==dc_, // "spread daycounter (" << dc_ << // ") must be the same of the curve to be spreaded (" << // originalCurve_->dayCounter() << // ")"); originalCurve_.registerWith(update); spread_.registerWith(update); }
public static double yieldSecant(Secant solver, Bond bond, double cleanPrice, DayCounter dayCounter, Compounding compounding, Frequency frequency) { double ret = NQuantLibcPINVOKE.BondFunctions_yieldSecant__SWIG_3(Secant.getCPtr(solver), Bond.getCPtr(bond), cleanPrice, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public static double yieldFalsePosition(FalsePosition solver, Bond bond, double cleanPrice, DayCounter dayCounter, Compounding compounding, Frequency frequency, Date settlementDate, double accuracy, double guess) { double ret = NQuantLibcPINVOKE.BondFunctions_yieldFalsePosition__SWIG_0(FalsePosition.getCPtr(solver), Bond.getCPtr(bond), cleanPrice, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency, Date.getCPtr(settlementDate), accuracy, guess); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public static double duration(Bond bond, double yield, DayCounter dayCounter, Compounding compounding, Frequency frequency, Duration.Type type) { double ret = NQuantLibcPINVOKE.BondFunctions_duration__SWIG_4(Bond.getCPtr(bond), yield, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency, (int)type); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public static double yieldValueBasisPoint(Bond bond, double yield, DayCounter dayCounter, Compounding compounding, Frequency frequency) { double ret = NQuantLibcPINVOKE.BondFunctions_yieldValueBasisPoint__SWIG_3(Bond.getCPtr(bond), yield, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; }
public void testYield() { //"Testing consistency of bond price/yield calculation..."); CommonVars vars = new CommonVars(); double tolerance = 1.0e-7; int maxEvaluations = 100; int[] issueMonths = new int[] { -24, -18, -12, -6, 0, 6, 12, 18, 24 }; int[] lengths = new int[] { 3, 5, 10, 15, 20 }; int settlementDays = 3; double[] coupons = new double[] { 0.02, 0.05, 0.08 }; Frequency[] frequencies = new Frequency[] { Frequency.Semiannual, Frequency.Annual }; DayCounter bondDayCount = new Thirty360(); BusinessDayConvention accrualConvention = BusinessDayConvention.Unadjusted; BusinessDayConvention paymentConvention = BusinessDayConvention.ModifiedFollowing; double redemption = 100.0; double[] yields = new double[] { 0.03, 0.04, 0.05, 0.06, 0.07 }; Compounding[] compounding = new Compounding[] { Compounding.Compounded, Compounding.Continuous }; for (int i = 0; i < issueMonths.Length; i++) { for (int j = 0; j < lengths.Length; j++) { for (int k = 0; k < coupons.Length; k++) { for (int l = 0; l < frequencies.Length; l++) { for (int n = 0; n < compounding.Length; n++) { Date dated = vars.calendar.advance(vars.today, issueMonths[i], TimeUnit.Months); Date issue = dated; Date maturity = vars.calendar.advance(issue, lengths[j], TimeUnit.Years); Schedule sch = new Schedule(dated, maturity, new Period(frequencies[l]), vars.calendar, accrualConvention, accrualConvention, DateGeneration.Rule.Backward, false); FixedRateBond bond = new FixedRateBond(settlementDays, vars.faceAmount, sch, new List<double>() { coupons[k] }, bondDayCount, paymentConvention, redemption, issue); for (int m = 0; m < yields.Length; m++) { double price = bond.cleanPrice(yields[m], bondDayCount, compounding[n], frequencies[l]); double calculated = bond.yield(price, bondDayCount, compounding[n], frequencies[l], null, tolerance, maxEvaluations); if (Math.Abs(yields[m] - calculated) > tolerance) { // the difference might not matter double price2 = bond.cleanPrice(calculated, bondDayCount, compounding[n], frequencies[l]); if (Math.Abs(price - price2) / price > tolerance) { Assert.Fail("yield recalculation failed:\n" + " issue: " + issue + "\n" + " maturity: " + maturity + "\n" + " coupon: " + coupons[k] + "\n" + " frequency: " + frequencies[l] + "\n\n" + " yield: " + yields[m] + " " + (compounding[n] == Compounding.Compounded ? "compounded" : "continuous") + "\n" + " price: " + price + "\n" + " yield': " + calculated + "\n" + " price': " + price2); } } } } } } } } }
// The resulting interest rate has the same day-counting rule used by the term structure. The same rule should be used for calculating the passed time t. public InterestRate zeroRate(double t, Compounding comp) { return(zeroRate(t, comp, Frequency.Annual, false)); }
public static double yieldValueBasisPoint(Bond bond, double yield, DayCounter dayCounter, Compounding compounding, Frequency frequency, Date settlementDate) { double ret = NQuantLibcPINVOKE.BondFunctions_yieldValueBasisPoint__SWIG_2(Bond.getCPtr(bond), yield, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency, Date.getCPtr(settlementDate)); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public static double basisPointValue(Bond bond, double yield, DayCounter dayCounter, Compounding compounding, Frequency frequency) { double ret = NQuantLibcPINVOKE.BondFunctions_basisPointValue__SWIG_3(Bond.getCPtr(bond), yield, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public static double duration(Bond bond, double yield, DayCounter dayCounter, Compounding compounding, Frequency frequency, Duration.Type type) { double ret = NQuantLibcPINVOKE.BondFunctions_duration__SWIG_4(Bond.getCPtr(bond), yield, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency, (int)type); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; }
public InterestRate forwardRate(Date d1, Date d2, DayCounter resultDayCounter, Compounding comp, Frequency freq) { return(forwardRate(d1, d2, resultDayCounter, comp, freq, false)); }
//public IndexHistoryCleaner indexCleaner; // initial setup public CommonVars() { backup = new SavedSettings(); //indexCleaner = new IndexHistoryCleaner(); termStructure = new RelinkableHandle<YieldTermStructure>(); int swapSettlementDays = 2; faceAmount = 100.0; BusinessDayConvention fixedConvention = BusinessDayConvention.Unadjusted; compounding = Compounding.Continuous; Frequency fixedFrequency = Frequency.Annual; Frequency floatingFrequency = Frequency.Semiannual; iborIndex = new Euribor(new Period(floatingFrequency), termStructure); Calendar calendar = iborIndex.fixingCalendar(); swapIndex= new SwapIndex("EuriborSwapIsdaFixA", new Period(10,TimeUnit.Years), swapSettlementDays, iborIndex.currency(), calendar, new Period(fixedFrequency), fixedConvention, iborIndex.dayCounter(), iborIndex); spread = 0.0; nonnullspread = 0.003; Date today = new Date(24,Month.April,2007); Settings.setEvaluationDate(today); //Date today = Settings::instance().evaluationDate(); termStructure.linkTo(Utilities.flatRate(today, 0.05, new Actual365Fixed())); pricer = new BlackIborCouponPricer(); Handle<SwaptionVolatilityStructure> swaptionVolatilityStructure = new Handle<SwaptionVolatilityStructure>(new ConstantSwaptionVolatility(today, new NullCalendar(),BusinessDayConvention.Following, 0.2, new Actual365Fixed())); Handle<Quote> meanReversionQuote = new Handle<Quote>(new SimpleQuote(0.01)); cmspricer = new AnalyticHaganPricer(swaptionVolatilityStructure, GFunctionFactory.YieldCurveModel.Standard, meanReversionQuote); }
public InterestRate forwardRate(Date d1, Date d2, DayCounter resultDayCounter, Compounding comp, Frequency freq, bool extrapolate) { if (d1 == d2) { double t1 = timeFromReference(d1); double t2 = t1 + 0.0001; double compound = discount(t1, extrapolate) / discount(t2, extrapolate); return(InterestRate.impliedRate(compound, t2 - t1, resultDayCounter, comp, freq)); } else { if (!(d1 < d2)) { throw new ArgumentException(d1 + " later than " + d2); } double compound = discount(d1, extrapolate) / discount(d2, extrapolate); return(InterestRate.impliedRate(compound, d1, d2, resultDayCounter, comp, freq)); } }
public LogCubicZeroCurve(DateVector dates, DoubleVector yields, DayCounter dayCounter, Calendar calendar, DefaultLogCubic i, Compounding compounding, Frequency frequency) : this(NQuantLibcPINVOKE.new_LogCubicZeroCurve__SWIG_0(DateVector.getCPtr(dates), DoubleVector.getCPtr(yields), DayCounter.getCPtr(dayCounter), Calendar.getCPtr(calendar), DefaultLogCubic.getCPtr(i), (int)compounding, (int)frequency), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
// The resulting interest rate has the required day-counting rule. // warning dates are not adjusted for holidays public InterestRate forwardRate(Date d, Period p, DayCounter resultDayCounter, Compounding comp) { return(forwardRate(d, d + p, resultDayCounter, comp, Frequency.Annual, false)); }
public static double zSpread(Bond bond, double cleanPrice, YieldTermStructure discountCurve, DayCounter dayCounter, Compounding compounding, Frequency frequency, Date settlementDate, double accuracy, uint maxIterations, double guess) { double ret = NQuantLibcPINVOKE.BondFunctions_zSpread__SWIG_0(Bond.getCPtr(bond), cleanPrice, YieldTermStructure.getCPtr(discountCurve), DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency, Date.getCPtr(settlementDate), accuracy, maxIterations, guess); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public InterestRate forwardRate(Date d, Period p, DayCounter resultDayCounter, Compounding comp, Frequency freq, bool extrapolate) { return(forwardRate(d, d + p, resultDayCounter, comp, freq, extrapolate)); }
public FixedRateLeg withCouponRates(List <double> couponRates, DayCounter paymentDayCounter, Compounding comp) { return(withCouponRates(couponRates, paymentDayCounter, comp, Frequency.Annual)); }
public InterestRate forwardRate(double t1, double t2, Compounding comp, Frequency freq) { return(forwardRate(t1, t2, comp, freq, false)); }
public FlatForward(int settlementDays, Calendar calendar, QuoteHandle forward, DayCounter dayCounter, Compounding compounding) : this(NQuantLibcPINVOKE.new_FlatForward__SWIG_7(settlementDays, Calendar.getCPtr(calendar), QuoteHandle.getCPtr(forward), DayCounter.getCPtr(dayCounter), (int)compounding), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public InterestRate zeroRate(Date d, DayCounter dayCounter, Compounding comp, Frequency freq) { return(zeroRate(d, dayCounter, comp, freq, false)); }
public FlatForward(Date referenceDate, double forward, DayCounter dayCounter, Compounding compounding) : this(NQuantLibcPINVOKE.new_FlatForward__SWIG_4(Date.getCPtr(referenceDate), forward, DayCounter.getCPtr(dayCounter), (int)compounding), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public static double dirtyPriceFromYield(double faceAmount, List <CashFlow> cashflows, double yield, DayCounter dayCounter, Compounding compounding, Frequency frequency, Date settlement) { if (frequency == Frequency.NoFrequency || frequency == Frequency.Once) { frequency = Frequency.Annual; } InterestRate y = new InterestRate(yield, dayCounter, compounding, frequency); double price = 0.0; double discount = 1.0; Date lastDate = null; for (int i = 0; i < cashflows.Count - 1; ++i) { if (cashflows[i].hasOccurred(settlement)) { continue; } Date couponDate = cashflows[i].Date; double amount = cashflows[i].amount(); if (lastDate == null) { // first not-expired coupon if (i > 0) { lastDate = cashflows[i - 1].Date; } else { if (cashflows[i].GetType().IsSubclassOf(typeof(Coupon))) { lastDate = ((Coupon)cashflows[i]).accrualStartDate(); } else { lastDate = couponDate - new Period(1, TimeUnit.Years); } } discount *= y.discountFactor(settlement, couponDate, lastDate, couponDate); } else { discount *= y.discountFactor(lastDate, couponDate); } lastDate = couponDate; price += amount * discount; } CashFlow redemption = cashflows.Last(); if (!redemption.hasOccurred(settlement)) { Date redemptionDate = redemption.Date; double amount = redemption.amount(); if (lastDate == null) { // no coupons lastDate = redemptionDate - new Period(1, TimeUnit.Years); discount *= y.discountFactor(settlement, redemptionDate, lastDate, redemptionDate); } else { discount *= y.discountFactor(lastDate, redemptionDate); } price += amount * discount; } return(price / faceAmount * 100.0); }
public FlatForward(int settlementDays, Calendar calendar, double forward, DayCounter dayCounter, Compounding compounding, Frequency frequency) : this(NQuantLibcPINVOKE.new_FlatForward__SWIG_9(settlementDays, Calendar.getCPtr(calendar), forward, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public LogLinearZeroCurve(DateVector dates, DoubleVector yields, DayCounter dayCounter, Calendar calendar, LogLinear i, Compounding compounding) : this(NQuantLibcPINVOKE.new_LogLinearZeroCurve__SWIG_1(DateVector.getCPtr(dates), DoubleVector.getCPtr(yields), DayCounter.getCPtr(dayCounter), Calendar.getCPtr(calendar), LogLinear.getCPtr(i), (int)compounding), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public FlatForward(int settlementDays, Calendar calendar, double forward, DayCounter dayCounter, Compounding compounding) : this(NQuantLibcPINVOKE.new_FlatForward__SWIG_10(settlementDays, Calendar.getCPtr(calendar), forward, DayCounter.getCPtr(dayCounter), (int)compounding), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); }
public static double yieldValueBasisPoint(Leg leg, double yield, DayCounter dayCounter, Compounding compounding, Frequency frequency, bool includeSettlementDateFlows, Date settlementDate = null, Date npvDate = null) { return yieldValueBasisPoint(leg, new InterestRate(yield, dayCounter, compounding, frequency), includeSettlementDateFlows, settlementDate, npvDate); }
public static double yield(Bond bond, double cleanPrice, DayCounter dayCounter, Compounding compounding, Frequency frequency, Date settlementDate, double accuracy) { double ret = NQuantLibcPINVOKE.BondFunctions_yield__SWIG_2(Bond.getCPtr(bond), cleanPrice, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency, Date.getCPtr(settlementDate), accuracy); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; }
//! implied Z-spread. public static double zSpread(Leg leg, double npv, YieldTermStructure discount, DayCounter dayCounter, Compounding compounding, Frequency frequency, bool includeSettlementDateFlows, Date settlementDate = null, Date npvDate = null, double accuracy = 1.0e-10, int maxIterations = 100, double guess = 0.0) { if (settlementDate == null) settlementDate = Settings.evaluationDate(); if (npvDate == null) npvDate = settlementDate; Brent solver = new Brent(); solver.setMaxEvaluations(maxIterations); ZSpreadFinder objFunction = new ZSpreadFinder(leg,discount,npv,dayCounter, compounding, frequency, includeSettlementDateFlows, settlementDate, npvDate); double step = 0.01; return solver.solve(objFunction, accuracy, guess, step); }
public static double basisPointValue(Bond bond, double yield, DayCounter dayCounter, Compounding compounding, Frequency frequency, Date settlementDate) { double ret = NQuantLibcPINVOKE.BondFunctions_basisPointValue__SWIG_2(Bond.getCPtr(bond), yield, DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency, Date.getCPtr(settlementDate)); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; }
public IrrFinder(Leg leg, double npv,DayCounter dayCounter,Compounding comp,Frequency freq, bool includeSettlementDateFlows,Date settlementDate,Date npvDate) { leg_ = leg; npv_ = npv; dayCounter_ = dayCounter; compounding_= comp; frequency_ = freq; includeSettlementDateFlows_ = includeSettlementDateFlows; settlementDate_=settlementDate; npvDate_=npvDate; if (settlementDate == null) settlementDate = Settings.evaluationDate(); if (npvDate == null) npvDate = settlementDate; checkSign(); }
/*! Simple yield calculation based on underlying spot and forward values, taking into account underlying income. When \f$ t>0 \f$, call with: underlyingSpotValue=spotValue(t), forwardValue=strikePrice, to get current yield. For a repo, if \f$ t=0 \f$, impliedYield should reproduce the spot repo rate. For FRA's, this should reproduce the relevant zero rate at the FRA's maturityDate_; */ public InterestRate impliedYield(double underlyingSpotValue, double forwardValue, Date settlementDate, Compounding compoundingConvention, DayCounter dayCounter) { double tenor = dayCounter.yearFraction(settlementDate,maturityDate_) ; double compoundingFactor = forwardValue/ (underlyingSpotValue-spotIncome(incomeDiscountCurve_)) ; return InterestRate.impliedRate(compoundingFactor, tenor, dayCounter, compoundingConvention); }
//! Implied internal rate of return. // The function verifies // the theoretical existance of an IRR and numerically // establishes the IRR to the desired precision. public static double yield(Leg leg, double npv, DayCounter dayCounter, Compounding compounding, Frequency frequency, bool includeSettlementDateFlows, Date settlementDate = null, Date npvDate = null, double accuracy = 1.0e-10, int maxIterations = 100, double guess = 0.05) { NewtonSafe solver = new NewtonSafe(); solver.setMaxEvaluations(maxIterations); IrrFinder objFunction = new IrrFinder(leg, npv, dayCounter, compounding, frequency, includeSettlementDateFlows, settlementDate, npvDate); return solver.solve(objFunction, accuracy, guess, guess/10.0); }
private void ParseItem(string text) { // Start off optimistic with the results. Change the properties as necessary. var result = new ImportResult { Status = ImportStatus.Succeeded, Text = text.Trim() }; // Add the result to the results list. Results.Add(result); // See if there might be at least a token to parse, i.e., "t:text", the bare minimum. if (!text.ToLowerInvariant().Contains($"{Key.Text}{Delimiter.KeyValue}")) { // "t:" was not found, does it contain "e:", the alt? if (!text.ToLowerInvariant().Contains($"{Key.Text}{Delimiter.KeyValue}")) { result.Status = ImportStatus.Error; result.AddMessage($"{MessageType.ItemError} There were no recognizable tokens found."); result.AddMessage($" The mandatory token ('t:' or 'e:') was not found."); return; } // If we get here, the "e:" was used to specify the text } // Extract token of data from the text. Return if an error was found. var tokens = Tokenize(text, ref result); if (result.Status == ImportStatus.Error) { return; } // Now we can bother to create a stem since the text is passed error checks. Anything // found beyond this point is a warning, except for a missing value for the text key. Stem stem = new Stem(); foreach (var token in tokens) { switch (token.Key) { case Key.Id: if (Guid.TryParse(token.Value, out Guid guid)) { result.Id = stem.Id = guid; } break; case Key.RootId: if (Guid.TryParse(token.Value, out Guid rid)) { stem.RootId = rid; } break; case Key.BaseId: if (Guid.TryParse(token.Value, out Guid bid)) { stem.BaseId = bid; } break; case Key.Text: case Key.TextAlt: stem.Form = token.Value; break; case Key.Category: stem.Category = token.Value.ParseTag(); break; case Key.Root: // Put the Id of this stem in the lookingForRoot _lookingForRoot.Add(stem.Id, token.Value); break; case Key.Base: // Put the Id of this stem in the lookingForBase _lookingForBase.Add(stem.Id, token.Value); break; case Key.Requisite: stem.RequisiteValues |= Requisites.ToValue(token.Value); break; case Key.Suggestion: stem.SuggestionValues |= Suggestion.ToValue(token.Value); break; case Key.Compounding: stem.CompoundingValues |= Compounding.ToValue(token.Value); break; case Key.Affixes: case Key.AffixesAlt: if (string.IsNullOrWhiteSpace(token.Value)) { break; } stem.Affixes = new List <string>(token .Value .Split(new string[] { Delimiter.Item }, StringSplitOptions.RemoveEmptyEntries) .Select(t => t.Trim()) .Distinct()); foreach (var affix in stem.Affixes) { if (!AffixExists(affix)) { result.Status = ImportStatus.Warning; result.AddMessage($"{MessageType.TokenWarning} Affix not found ('{affix}')."); } } break; case Key.Sense: // Replace any space, ' ', with a period, '.'. stem.Sense = token.Value?.Replace(Delimiter.Space, Delimiter.Morpheme) .Unescape() .Replace(Delimiter.Pipe, Delimiter.SemiColon); break; case Key.Comments: stem.Comments = token.Value?.Unescape() .Replace(Delimiter.Pipe, Delimiter.SemiColon); break; default: result.Status = ImportStatus.Warning; result.AddMessage($"{MessageType.TokenWarning} Unrecognized key ('{token}')."); break; } } // Set the ID for the results for tracking. This is late as the ID might have been parsed // from the text. if (result.Id == Guid.Empty) { result.Id = stem.Id; } // Duplicate check if (_referenceStems.Where(s => s.Form == stem.Form & s.Category == stem.Category).Count() > 0) { result.Status = ImportStatus.Warning; result.AddMessage($"{MessageType.TokenWarning} Possible duplicate ('{stem.Form}')."); DebugHelper.Warning(result.Message); } DebugHelper.Info($"Adding stem (text: '{stem.Form}')..."); _referenceStems.Add(stem); }
public static double zSpread(Bond bond, double cleanPrice, YieldTermStructure discountCurve, DayCounter dayCounter, Compounding compounding, Frequency frequency) { double ret = NQuantLibcPINVOKE.BondFunctions_zSpread__SWIG_4(Bond.getCPtr(bond), cleanPrice, YieldTermStructure.getCPtr(discountCurve), DayCounter.getCPtr(dayCounter), (int)compounding, (int)frequency); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
// NPV of the cash flows. // The NPV is the sum of the cash flows, each discounted // according to the z-spreaded term structure. The result // is affected by the choice of the z-spread compounding // and the relative frequency and day counter. public static double npv(Leg leg,YieldTermStructure discountCurve,double zSpread,DayCounter dc,Compounding comp, Frequency freq,bool includeSettlementDateFlows, Date settlementDate = null,Date npvDate = null) { if (leg.empty()) return 0.0; if (settlementDate == null) settlementDate = Settings.evaluationDate(); if (npvDate == null) npvDate = settlementDate; Handle<YieldTermStructure> discountCurveHandle = new Handle<YieldTermStructure>(discountCurve); Handle<Quote> zSpreadQuoteHandle = new Handle<Quote>(new SimpleQuote(zSpread)); ZeroSpreadedTermStructure spreadedCurve = new ZeroSpreadedTermStructure(discountCurveHandle,zSpreadQuoteHandle, comp, freq, dc); spreadedCurve.enableExtrapolation(discountCurveHandle.link.allowsExtrapolation()); return npv(leg, spreadedCurve, includeSettlementDateFlows, settlementDate, npvDate); }
// Calculate dirty price from yield, adapting public static double FullPriceFromYield(double yield, Date[] CashFlowsDate, double[] CashFlows, int freq, Dc dc, Date SettlementDate, Compounding compounding, double FaceValue) { // initial discount double df = 1.0; // discount double yf = 0.0; // find next payment date that is greater than settlement date, previous payments will no more need int iStart = Array.FindIndex(CashFlowsDate, n => n > SettlementDate); // index of next payment int iEnd = CashFlowsDate.GetLength(0); // total payments (past+ future) int dim = iEnd - iStart; // number of payments in the future // myCFs vector of future payments(after settlement date) // myCFsDates vector of date of each element of myCFs, starting from settlement date Date[] myCFsDates = new Date[dim + 1]; // start from settlement date + future dates of payment double[] myCFs = new double[dim]; // future payments Array.ConstrainedCopy(CashFlowsDate, iStart, myCFsDates, 1, dim); // populate myCFsDates 1 to dim index myCFsDates[0] = SettlementDate; // first element of myCFsDates is settlement date Array.ConstrainedCopy(CashFlows, iStart, myCFs, 0, dim); // populate myCFs // Iterate to add each cash flow discounted, according to given convention double fullPrice = 0.0; // starting value for (int i = 0; i < dim; i++) { yf = myCFsDates[i].YF(myCFsDates[i + 1], dc); // calculate new yf df *= CalCDF(yield, yf, freq, compounding); // calculate new df fullPrice += myCFs[i] * df; } // Adding discounted face amount fullPrice += FaceValue * df; // final result return(fullPrice); }
//! deprecated implied Z-spread. public static double zSpread(Leg leg, YieldTermStructure d, double npv, DayCounter dayCounter, Compounding compounding, Frequency frequency, bool includeSettlementDateFlows, Date settlementDate = null, Date npvDate = null, double accuracy = 1.0e-10, int maxIterations = 100, double guess = 0.0) { return zSpread(leg, npv, d, dayCounter, compounding, frequency, includeSettlementDateFlows, settlementDate, npvDate, accuracy, maxIterations, guess); }
// Calculate Yield from dirty price public static double YieldFromFullPrice(double fullPrice, double yieldGuess, Date[] CashFlowsDate, double[] CashFlows, int freq, Dc dc, Date SettlementDate, Compounding compounding, double FaceValue) { int N = CashFlowsDate.GetLength(0); // number of Cash flows dates int k = Array.FindIndex(CashFlowsDate, n => n > SettlementDate); // get index of first cash flow after settlement date Date[] Dates = new Date[N - k]; // array with pay dates after settlement double[] Flows = new double[N - k]; // flows after settlement Array.Copy(CashFlowsDate, k, Dates, 0, N - k); // fill array with needed data Array.Copy(CashFlows, k, Flows, 0, N - k); // fill array with needed data // define my function: we should find yield that match starting price NumMethod.myMethodDelegate fname = y_ => fullPrice - FullPriceFromYield(y_, Dates, Flows, freq, dc, SettlementDate, compounding, FaceValue); // return yield return(NumMethod.NewRapNum(fname, yieldGuess)); }
public ZSpreadFinder(Leg leg,YieldTermStructure discountCurve,double npv,DayCounter dc,Compounding comp,Frequency freq, bool includeSettlementDateFlows, Date settlementDate, Date npvDate) { leg_ = leg; npv_ = npv; zSpread_ = new SimpleQuote(0.0); curve_ = new ZeroSpreadedTermStructure(new Handle<YieldTermStructure>(discountCurve), new Handle<Quote>(zSpread_), comp, freq, dc); includeSettlementDateFlows_ = includeSettlementDateFlows; settlementDate_ = settlementDate; npvDate_ = npvDate; if (settlementDate == null) settlementDate = Settings.evaluationDate(); if (npvDate == null) npvDate = settlementDate; // if the discount curve allows extrapolation, let's // the spreaded curve do too. curve_.enableExtrapolation(discountCurve.allowsExtrapolation()); }
public SpreadedBackwardFlatZeroInterpolatedTermStructure(YieldTermStructureHandle curveHandle, QuoteHandleVector spreadHandles, DateVector dates, Compounding comp) : this(NQuantLibcPINVOKE.new_SpreadedBackwardFlatZeroInterpolatedTermStructure__SWIG_3(YieldTermStructureHandle.getCPtr(curveHandle), QuoteHandleVector.getCPtr(spreadHandles), DateVector.getCPtr(dates), (int)comp), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public static double duration(Leg leg, double yield, DayCounter dayCounter, Compounding compounding, Frequency frequency, Duration.Type type, bool includeSettlementDateFlows, Date settlementDate = null, Date npvDate = null) { return duration(leg, new InterestRate(yield, dayCounter, compounding, frequency), type, includeSettlementDateFlows, settlementDate, npvDate); }
/*! The resulting interest rate has the required day-counting * rule. * \warning dates are not adjusted for holidays */ public InterestRate forwardRate(Date d, Period p, DayCounter dayCounter, Compounding comp, Frequency freq = Frequency.Annual, bool extrapolate = false) { return(forwardRate(d, d + p, dayCounter, comp, freq, extrapolate)); }