public GFunctionExactYield(CmsCoupon coupon) { SwapIndex swapIndex = coupon.swapIndex(); VanillaSwap swap = swapIndex.underlyingSwap(coupon.fixingDate()); Schedule schedule = swap.fixedSchedule(); Handle <YieldTermStructure> rateCurve = swapIndex.forwardingTermStructure(); DayCounter dc = swapIndex.dayCounter(); double swapStartTime = dc.yearFraction(rateCurve.link.referenceDate(), schedule.startDate()); double swapFirstPaymentTime = dc.yearFraction(rateCurve.link.referenceDate(), schedule.date(1)); double paymentTime = dc.yearFraction(rateCurve.link.referenceDate(), coupon.date()); delta_ = (paymentTime - swapStartTime) / (swapFirstPaymentTime - swapStartTime); List <CashFlow> fixedLeg = new List <CashFlow>(swap.fixedLeg()); int n = fixedLeg.Count; accruals_ = new List <double>(); for (int i = 0; i < n; ++i) { Coupon coupon1 = fixedLeg[i] as Coupon; accruals_.Add(coupon1.accrualPeriod()); } }
public double swaption(Swaption.Arguments arguments, double fixedRate, double range, int intervals) { Date settlement = termStructure().link.referenceDate(); DayCounter dayCounter = termStructure().link.dayCounter(); double start = dayCounter.yearFraction(settlement, arguments.floatingResetDates[0]); double w = (arguments.type == VanillaSwap.Type.Payer ? 1 : -1); List <double> fixedPayTimes = new InitializedList <double>(arguments.fixedPayDates.Count); for (int i = 0; i < fixedPayTimes.Count; ++i) { fixedPayTimes[i] = dayCounter.yearFraction(settlement, arguments.fixedPayDates[i]); } SwaptionPricingFunction function = new SwaptionPricingFunction(a(), sigma(), b(), eta(), rho(), w, start, fixedPayTimes, fixedRate, this); double upper = function.mux() + range * function.sigmax(); double lower = function.mux() - range * function.sigmax(); SegmentIntegral integrator = new SegmentIntegral(intervals); return(arguments.nominal * w * termStructure().link.discount(start) * integrator.value(function.value, lower, upper)); }
public DiscretizedCallableFixedRateBond(CallableBond.Arguments args, Date referenceDate, DayCounter dayCounter) { arguments_ = args; redemptionTime_ = dayCounter.yearFraction(referenceDate, args.redemptionDate); for (int i = 0; i < args.couponDates.Count ; ++i) couponTimes_.Add(dayCounter.yearFraction(referenceDate, args.couponDates[i])); for (int i = 0; i < args.callabilityDates.Count ; ++i) callabilityTimes_.Add( dayCounter.yearFraction(referenceDate, args.callabilityDates[i])); // similar to the tree swaption engine, we collapse similar coupon // and exercise dates to avoid mispricing. Delete if unnecessary. for (int i = 0; i < callabilityTimes_.Count; i++) { double exerciseTime = callabilityTimes_[i]; for (int j = 0; j < couponTimes_.Count ; j++) { if (withinNextWeek(exerciseTime, couponTimes_[j])) couponTimes_[j] = exerciseTime; } } }
public DiscretizedSwap(VanillaSwap.Arguments args, Date referenceDate, DayCounter dayCounter) { arguments_ = args; fixedResetTimes_ = new InitializedList<double>(args.fixedResetDates.Count); for (int i = 0; i < fixedResetTimes_.Count; ++i) fixedResetTimes_[i] = dayCounter.yearFraction(referenceDate, args.fixedResetDates[i]); fixedPayTimes_ = new InitializedList<double>(args.fixedPayDates.Count); for (int i = 0; i < fixedPayTimes_.Count; ++i) fixedPayTimes_[i] = dayCounter.yearFraction(referenceDate, args.fixedPayDates[i]); floatingResetTimes_ = new InitializedList<double>(args.floatingResetDates.Count); for (int i = 0; i < floatingResetTimes_.Count; ++i) floatingResetTimes_[i] = dayCounter.yearFraction(referenceDate, args.floatingResetDates[i]); floatingPayTimes_ = new InitializedList<double>(args.floatingPayDates.Count); for (int i = 0; i < floatingPayTimes_.Count; ++i) floatingPayTimes_[i] = dayCounter.yearFraction(referenceDate, args.floatingPayDates[i]); }
public DiscretizedCallableFixedRateBond(CallableBond.Arguments args, Date referenceDate, DayCounter dayCounter) { arguments_ = args; redemptionTime_ = dayCounter.yearFraction(referenceDate, args.redemptionDate); for (int i = 0; i < args.couponDates.Count; ++i) { couponTimes_.Add(dayCounter.yearFraction(referenceDate, args.couponDates[i])); } for (int i = 0; i < args.callabilityDates.Count; ++i) { callabilityTimes_.Add(dayCounter.yearFraction(referenceDate, args.callabilityDates[i])); } // similar to the tree swaption engine, we collapse similar coupon // and exercise dates to avoid mispricing. Delete if unnecessary. for (int i = 0; i < callabilityTimes_.Count; i++) { double exerciseTime = callabilityTimes_[i]; for (int j = 0; j < couponTimes_.Count; j++) { if (withinNextWeek(exerciseTime, couponTimes_[j])) { couponTimes_[j] = exerciseTime; } } } }
// converts the yield volatility into a forward price volatility private double forwardPriceVolatility() { Date bondMaturity = arguments_.redemptionDate; Date exerciseDate = arguments_.callabilityDates[0]; List <CashFlow> fixedLeg = arguments_.cashflows; // value of bond cash flows at option maturity double fwdNpv = CashFlows.npv(fixedLeg, discountCurve_, exerciseDate); DayCounter dayCounter = arguments_.paymentDayCounter; Frequency frequency = arguments_.frequency; // adjust if zero coupon bond (see also bond.cpp) if (frequency == Frequency.NoFrequency || frequency == Frequency.Once) { frequency = Frequency.Annual; } double fwdYtm = CashFlows.yield(fixedLeg, fwdNpv, dayCounter, Compounding.Compounded, frequency, false, exerciseDate); InterestRate fwdRate = new InterestRate(fwdYtm, dayCounter, Compounding.Compounded, frequency); double fwdDur = CashFlows.duration(fixedLeg, fwdRate, Duration.Type.Modified, exerciseDate); double cashStrike = arguments_.callabilityPrices[0]; dayCounter = volatility_.link.dayCounter(); Date referenceDate = volatility_.link.referenceDate(); double exerciseTime = dayCounter.yearFraction(referenceDate, exerciseDate); double maturityTime = dayCounter.yearFraction(referenceDate, bondMaturity); double yieldVol = volatility_.link.volatility(exerciseTime, maturityTime - exerciseTime, cashStrike); double fwdPriceVol = yieldVol * fwdDur * fwdYtm; return(fwdPriceVol); }
public DiscretizedSwaption(Swaption.Arguments args, Date referenceDate, DayCounter dayCounter) : base(new DiscretizedSwap(args, referenceDate, dayCounter), args.exercise.type(), new List<double>()) { arguments_=args; exerciseTimes_ = new InitializedList<double>(arguments_.exercise.dates().Count); for (int i = 0; i < exerciseTimes_.Count; ++i) exerciseTimes_[i] = dayCounter.yearFraction(referenceDate, arguments_.exercise.date(i)); // Date adjustments can get time vectors out of synch. // Here, we try and collapse similar dates which could cause // a mispricing. for (int i=0; i<arguments_.exercise.dates().Count; i++) { Date exerciseDate = arguments_.exercise.date(i); for (int j = 0; j < arguments_.fixedPayDates.Count; j++) { if (withinNextWeek(exerciseDate, arguments_.fixedPayDates[j]) // coupons in the future are dealt with below && arguments_.fixedResetDates[j] < referenceDate) arguments_.fixedPayDates[j] = exerciseDate; } for (int j = 0; j < arguments_.fixedResetDates.Count; j++) { if (withinPreviousWeek(exerciseDate, arguments_.fixedResetDates[j])) arguments_.fixedResetDates[j] = exerciseDate; } for (int j = 0; j < arguments_.floatingResetDates.Count; j++) { if (withinPreviousWeek(exerciseDate, arguments_.floatingResetDates[j])) arguments_.floatingResetDates[j] = exerciseDate; } } double lastFixedPayment = dayCounter.yearFraction(referenceDate, arguments_.fixedPayDates.Last() ); double lastFloatingPayment = dayCounter.yearFraction(referenceDate, arguments_.floatingPayDates.Last()); lastPayment_ = Math.Max(lastFixedPayment,lastFloatingPayment); underlying_ = new DiscretizedSwap(arguments_, referenceDate, dayCounter); }
public DiscretizedCapFloor(CapFloor.Arguments args, Date referenceDate, DayCounter dayCounter) { arguments_ = args; startTimes_= new InitializedList<double>(args.startDates.Count); for (int i = 0; i < startTimes_.Count; ++i) startTimes_[i] = dayCounter.yearFraction(referenceDate, args.startDates[i]); endTimes_ = new InitializedList<double>(args.endDates.Count); for (int i = 0; i < endTimes_.Count; ++i) endTimes_[i] = dayCounter.yearFraction(referenceDate, args.endDates[i]); }
public void BuildDates(QLNet.Calendar calendar, QLNet.DayCounter dc) { _dates.Resize(_tenors.Count); Date today = Settings.evaluationDate(); for (int i = 0; i < _tenors.Count; i++) { if (_tenors[i].units() == TimeUnit.Days) { _dates[i] = calendar.adjust(today + _tenors[i]); } else { _dates[i] = calendar.advance(today, _tenors[i], BusinessDayConvention.Following, true); } } QLNet.Utils.QL_REQUIRE(_dates.Count == _tenors.Count, () => "Date/Tenor mismatch"); // Build times _times.Resize(_dates.Count); for (int i = 0; i < _dates.Count; i++) { _times[i] = dc.yearFraction(today, _dates[i]); } _timeGrid = new TimeGrid(_times, _times.Count); // Log the date grid //log(); }
protected virtual void getOriginalResults() { DayCounter rfdc = process_.riskFreeRate().link.dayCounter(); DayCounter divdc = process_.dividendYield().link.dayCounter(); double resetTime = rfdc.yearFraction(process_.riskFreeRate().link.referenceDate(), this.arguments_.resetDate); double discQ = process_.dividendYield().link.discount(this.arguments_.resetDate); this.results_.value = discQ * originalResults_.value; // I need the strike derivative here ... if (originalResults_.delta != null && originalResults_.strikeSensitivity != null) { this.results_.delta = discQ * (originalResults_.delta + this.arguments_.moneyness * originalResults_.strikeSensitivity); } this.results_.gamma = 0.0; this.results_.theta = process_.dividendYield().link. zeroRate(this.arguments_.resetDate, divdc, Compounding.Continuous, Frequency.NoFrequency).value() * this.results_.value; if (originalResults_.vega != null) { this.results_.vega = discQ * originalResults_.vega; } if (originalResults_.rho != null) { this.results_.rho = discQ * originalResults_.rho; } if (originalResults_.dividendRho != null) { this.results_.dividendRho = -resetTime * this.results_.value + discQ * originalResults_.dividendRho; } }
protected virtual double seasonalityCorrection(double rate, Date atDate, DayCounter dc, Date curveBaseDate, bool isZeroRate) { // need _two_ corrections in order to get: seasonality = factor[atDate-seasonalityBase] / factor[reference-seasonalityBase] // i.e. for ZERO inflation rates you have the true fixing at the curve base so this factor must be normalized to one // for YoY inflation rates your reference point is the year before double factorAt = this.seasonalityFactor(atDate); //Getting seasonality correction for either ZC or YoY double f; if (isZeroRate) { double factorBase = this.seasonalityFactor(curveBaseDate); double seasonalityAt = factorAt / factorBase; double timeFromCurveBase = dc.yearFraction(curveBaseDate, atDate); f = Math.Pow(seasonalityAt, 1 / timeFromCurveBase); } else { double factor1Ybefore = this.seasonalityFactor(atDate - new Period(1, TimeUnit.Years)); f = factorAt / factor1Ybefore; } return((rate + 1) * f - 1); }
public static double simpleDuration(List <CashFlow> cashflows, InterestRate y, Date settlementDate) { if (cashflows.Count == 0) { return(0.0); } double P = 0, dPdy = 0; DayCounter dc = y.dayCounter(); foreach (CashFlow cf in cashflows.Where(cf => !cf.hasOccurred(settlementDate))) { double t = dc.yearFraction(settlementDate, cf.date()); double c = cf.amount(); double B = y.discountFactor(t); P += c * B; dPdy += t * c * B; } // no cashflows if (P == 0.0) { return(0.0); } return(dPdy / P); }
public FdmDividendHandler(DividendSchedule schedule, FdmMesher mesher, Date referenceDate, DayCounter dayCounter, int equityDirection) { x_ = new Vector(mesher.layout().dim()[equityDirection]); mesher_ = mesher; equityDirection_ = equityDirection; dividends_ = new List <double>(); dividendDates_ = new List <Date>(); dividendTimes_ = new List <double>(); foreach (Dividend iter in schedule) { dividends_.Add(iter.amount()); dividendDates_.Add(iter.date()); dividendTimes_.Add( dayCounter.yearFraction(referenceDate, iter.date())); } Vector tmp = mesher_.locations(equityDirection); int spacing = mesher_.layout().spacing()[equityDirection]; for (int i = 0; i < x_.size(); ++i) { x_[i] = Math.Exp(tmp[i * spacing]); } }
public OvernightIndexedCoupon( Date paymentDate, double nominal, Date startDate, Date endDate, OvernightIndex overnightIndex, double gearing = 1.0, double spread = 0.0, Date refPeriodStart = null, Date refPeriodEnd = null, DayCounter dayCounter = null) : base(nominal, paymentDate, startDate, endDate, overnightIndex.fixingDays(), overnightIndex, gearing, spread, refPeriodStart, refPeriodEnd, dayCounter, false) { // value dates Schedule sch = new MakeSchedule() .from(startDate) .to(endDate) .withTenor(new Period(1, TimeUnit.Days)) .withCalendar(overnightIndex.fixingCalendar()) .withConvention(overnightIndex.businessDayConvention()) .backwards() .value(); valueDates_ = sch.dates(); if (valueDates_.Count < 2) { throw new ArgumentException("degenerate schedule"); } // fixing dates n_ = valueDates_.Count() - 1; if (overnightIndex.fixingDays() == 0) { fixingDates_ = new List <Date>(valueDates_); } else { fixingDates_ = new List <Date>(n_); for (int i = 0; i < n_; ++i) { fixingDates_[i] = overnightIndex.fixingDate(valueDates_[i]); } } // accrual (compounding) periods dt_ = new List <double>(n_); DayCounter dc = overnightIndex.dayCounter(); for (int i = 0; i < n_; ++i) { dt_.Add(dc.yearFraction(valueDates_[i], valueDates_[i + 1])); } setPricer(new OvernightIndexedCouponPricer()); }
/*! 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, dayCounter, compoundingConvention, Frequency.Annual, tenor)); }
//! implied rate for a given compound factor between two dates. /*! The resulting rate is calculated taking the required * day-counting rule into account. */ public static InterestRate impliedRate(double compound, DayCounter resultDC, Compounding comp, Frequency freq, Date d1, Date d2, Date refStart = null, Date refEnd = null) { Utils.QL_REQUIRE(d2 >= d1, "d1 (" + d1 + ") later than d2 (" + d2 + ")"); double t = resultDC.yearFraction(d1, d2, refStart, refEnd); return(impliedRate(compound, resultDC, comp, freq, t)); }
public virtual double yearFraction(Date d1, Date d2, Date refPeriodStart, Date refPeriodEnd) { if (empty()) { throw Error.MissingImplementation(); } return(dayCounter_.yearFraction(d1, d2, refPeriodStart, refPeriodEnd)); }
public static double modifiedDuration(List <CashFlow> cashflows, InterestRate y, Date settlementDate) { if (cashflows.Count == 0) { return(0.0); } double P = 0.0; double dPdy = 0.0; double r = y.rate(); int N = (int)y.frequency(); DayCounter dc = y.dayCounter(); foreach (CashFlow cf in cashflows.Where(cf => !cf.hasOccurred(settlementDate))) { double t = dc.yearFraction(settlementDate, cf.date()); double c = cf.amount(); double B = y.discountFactor(t); P += c * B; switch (y.compounding()) { case Compounding.Simple: dPdy -= c * B * B * t; break; case Compounding.Compounded: dPdy -= c * t * B / (1 + r / N); break; case Compounding.Continuous: dPdy -= c * B * t; break; case Compounding.SimpleThenCompounded: if (t <= 1.0 / N) { dPdy -= c * B * B * t; } else { dPdy -= c * t * B / (1 + r / N); } break; default: throw new ArgumentException("unknown compounding convention (" + y.compounding() + ")"); } } if (P == 0.0) // no cashflows { return(0.0); } return(-dPdy / P); // reverse derivative sign }
public LiborForwardModelProcess(int size, IborIndex index, IDiscretization disc) : base(disc) { size_ = size; index_ = index; initialValues_ = new InitializedList <double>(size_); fixingTimes_ = new InitializedList <double>(size); fixingDates_ = new InitializedList <Date>(size_); accrualStartTimes_ = new InitializedList <double>(size); accrualEndTimes_ = new InitializedList <double>(size); accrualPeriod_ = new InitializedList <double>(size_); m1 = new Vector(size_); m2 = new Vector(size_); DayCounter dayCounter = index.dayCounter(); IList <CashFlow> flows = cashFlows(1); if (!(size_ == flows.Count)) { throw new ArgumentException("wrong number of cashflows"); } Date settlement = index_.forwardingTermStructure().link.referenceDate(); Date startDate; IborCoupon iborcoupon = (IborCoupon)flows[0]; startDate = iborcoupon.fixingDate(); for (int i = 0; i < size_; ++i) { IborCoupon coupon = (IborCoupon)flows[i]; if (!(coupon.date() == coupon.accrualEndDate())) { throw new ArgumentException("irregular coupon types are not suppported"); } initialValues_[i] = coupon.rate(); accrualPeriod_[i] = coupon.accrualPeriod(); fixingDates_[i] = coupon.fixingDate(); fixingTimes_[i] = dayCounter.yearFraction(startDate, coupon.fixingDate()); accrualStartTimes_[i] = dayCounter.yearFraction(settlement, coupon.accrualStartDate()); accrualEndTimes_[i] = dayCounter.yearFraction(settlement, coupon.accrualEndDate()); } }
//! equivalent rate for a compounding period between two dates /*! The resulting rate is calculated taking the required * day-counting rule into account. */ public InterestRate equivalentRate(DayCounter resultDC, Compounding comp, Frequency freq, Date d1, Date d2, Date refStart = null, Date refEnd = null) { Utils.QL_REQUIRE(d2 >= d1, "d1 (" + d1 + ") later than d2 (" + d2 + ")"); double t1 = dc_.yearFraction(d1, d2, refStart, refEnd); double t2 = resultDC.yearFraction(d1, d2, refStart, refEnd); return(impliedRate(compoundFactor(t1), resultDC, comp, freq, t2)); }
public void initializeExerciseTime() { if (!(exerciseDate_ >= referenceDate_)) { throw new ApplicationException("expiry date (" + exerciseDate_ + ") must be greater than reference date (" + referenceDate_ + ")"); } exerciseTime_ = dc_.yearFraction(referenceDate_, exerciseDate_); }
public override void calculate() { if (arguments_.exercise.type() != Exercise.Type.European) { throw new ApplicationException("not an European option"); } StrikedTypePayoff payoff = arguments_.payoff as StrikedTypePayoff; if (payoff == null) { throw new ApplicationException("non-striked payoff given"); } double variance = process_.blackVolatility().link.blackVariance(arguments_.exercise.lastDate(), payoff.strike()); double dividendDiscount = process_.dividendYield().link.discount(arguments_.exercise.lastDate()); double riskFreeDiscount = process_.riskFreeRate().link.discount(arguments_.exercise.lastDate()); double spot = process_.stateVariable().link.value(); if (!(spot > 0.0)) { throw new ApplicationException("negative or null underlying given"); } double forwardPrice = spot * dividendDiscount / riskFreeDiscount; BlackCalculator black = new BlackCalculator(payoff, forwardPrice, Math.Sqrt(variance), riskFreeDiscount); results_.value = black.value(); results_.delta = black.delta(spot); results_.deltaForward = black.deltaForward(); results_.elasticity = black.elasticity(spot); results_.gamma = black.gamma(spot); DayCounter rfdc = process_.riskFreeRate().link.dayCounter(); DayCounter divdc = process_.dividendYield().link.dayCounter(); DayCounter voldc = process_.blackVolatility().link.dayCounter(); double t = rfdc.yearFraction(process_.riskFreeRate().link.referenceDate(), arguments_.exercise.lastDate()); results_.rho = black.rho(t); t = divdc.yearFraction(process_.dividendYield().link.referenceDate(), arguments_.exercise.lastDate()); results_.dividendRho = black.dividendRho(t); t = voldc.yearFraction(process_.blackVolatility().link.referenceDate(), arguments_.exercise.lastDate()); results_.vega = black.vega(t); try { results_.theta = black.theta(spot, t); results_.thetaPerDay = black.thetaPerDay(spot, t); } catch { results_.theta = null; results_.thetaPerDay = null; } results_.strikeSensitivity = black.strikeSensitivity(); results_.itmCashProbability = black.itmCashProbability(); }
//===========================================================================// // GFunctionWithShifts // //===========================================================================// public GFunctionWithShifts(CmsCoupon coupon, Handle <Quote> meanReversion) { meanReversion_ = meanReversion; calibratedShift_ = 0.03; tmpRs_ = 10000000.0; accuracy_ = 1.0e-14; SwapIndex swapIndex = coupon.swapIndex(); VanillaSwap swap = swapIndex.underlyingSwap(coupon.fixingDate()); swapRateValue_ = swap.fairRate(); objectiveFunction_ = new ObjectiveFunction(this, swapRateValue_); Schedule schedule = swap.fixedSchedule(); Handle <YieldTermStructure> rateCurve = swapIndex.forwardingTermStructure(); DayCounter dc = swapIndex.dayCounter(); swapStartTime_ = dc.yearFraction(rateCurve.link.referenceDate(), schedule.startDate()); discountAtStart_ = rateCurve.link.discount(schedule.startDate()); double paymentTime = dc.yearFraction(rateCurve.link.referenceDate(), coupon.date()); shapedPaymentTime_ = shapeOfShift(paymentTime); List <CashFlow> fixedLeg = new List <CashFlow>(swap.fixedLeg()); int n = fixedLeg.Count; shapedSwapPaymentTimes_ = new List <double>(); swapPaymentDiscounts_ = new List <double>(); accruals_ = new List <double>(); for (int i = 0; i < n; ++i) { Coupon coupon1 = fixedLeg[i] as Coupon; accruals_.Add(coupon1.accrualPeriod()); Date paymentDate = new Date(coupon1.date().serialNumber()); double swapPaymentTime = dc.yearFraction(rateCurve.link.referenceDate(), paymentDate); shapedSwapPaymentTimes_.Add(shapeOfShift(swapPaymentTime)); swapPaymentDiscounts_.Add(rateCurve.link.discount(paymentDate)); } discountRatio_ = swapPaymentDiscounts_.Last() / discountAtStart_; }
public DiscretizedCapFloor(CapFloor.Arguments args, Date referenceDate, DayCounter dayCounter) { arguments_ = args; startTimes_ = new InitializedList <double>(args.startDates.Count); for (int i = 0; i < startTimes_.Count; ++i) { startTimes_[i] = dayCounter.yearFraction(referenceDate, args.startDates[i]); } endTimes_ = new InitializedList <double>(args.endDates.Count); for (int i = 0; i < endTimes_.Count; ++i) { endTimes_[i] = dayCounter.yearFraction(referenceDate, args.endDates[i]); } }
public static InterestRate impliedRate(double compound, Date d1, Date d2, DayCounter resultDC, Compounding comp, Frequency freq) { if (!(d2 > d1)) { throw new ArgumentException("d1 (" + d1 + ") " + "later than or equal to d2 (" + d2 + ")"); } double t = resultDC.yearFraction(d1, d2); return(impliedRate(compound, t, resultDC, comp, freq)); }
public override void calculate() { if (!(arguments_.settlementType == Settlement.Type.Physical)) { throw new ApplicationException("cash-settled swaptions not priced with Lfm engine"); } double basisPoint = 1.0e-4; VanillaSwap swap = arguments_.swap; IPricingEngine pe = new DiscountingSwapEngine(discountCurve_); swap.setPricingEngine(pe); double correction = swap.spread * Math.Abs(swap.floatingLegBPS() / swap.fixedLegBPS()); double fixedRate = swap.fixedRate - correction; double fairRate = swap.fairRate() - correction; SwaptionVolatilityMatrix volatility = model_.getSwaptionVolatilityMatrix(); Date referenceDate = volatility.referenceDate(); DayCounter dayCounter = volatility.dayCounter(); double exercise = dayCounter.yearFraction(referenceDate, arguments_.exercise.date(0)); double swapLength = dayCounter.yearFraction(referenceDate, arguments_.fixedPayDates.Last()) - dayCounter.yearFraction(referenceDate, arguments_.fixedResetDates[0]); Option.Type w = arguments_.type == VanillaSwap.Type.Payer ? Option.Type.Call : Option.Type.Put; double vol = volatility.volatility(exercise, swapLength, fairRate, true); results_.value = (swap.fixedLegBPS() / basisPoint) * Utils.blackFormula(w, fixedRate, fairRate, vol * Math.Sqrt(exercise)); }
public RangeAccrualFloatersCoupon(Date paymentDate, double nominal, IborIndex index, Date startDate, Date endDate, int fixingDays, DayCounter dayCounter, double gearing, double spread, Date refPeriodStart, Date refPeriodEnd, Schedule observationsSchedule, double lowerTrigger, double upperTrigger) : base(paymentDate, nominal, startDate, endDate, fixingDays, index, gearing, spread, refPeriodStart, refPeriodEnd, dayCounter) { observationsSchedule_ = observationsSchedule; lowerTrigger_ = lowerTrigger; upperTrigger_ = upperTrigger; Utils.QL_REQUIRE(lowerTrigger_ < upperTrigger, () => "lowerTrigger_>=upperTrigger"); Utils.QL_REQUIRE(observationsSchedule_.startDate() == startDate, () => "incompatible start date"); Utils.QL_REQUIRE(observationsSchedule_.endDate() == endDate, () => "incompatible end date"); observationDates_ = new List <Date>(observationsSchedule_.dates()); observationDates_.RemoveAt(observationDates_.Count - 1); //remove end date observationDates_.RemoveAt(0); //remove start date observationsNo_ = observationDates_.Count; Handle <YieldTermStructure> rateCurve = index.forwardingTermStructure(); Date referenceDate = rateCurve.link.referenceDate(); startTime_ = dayCounter.yearFraction(referenceDate, startDate); endTime_ = dayCounter.yearFraction(referenceDate, endDate); observationTimes_ = new List <double>(); for (int i = 0; i < observationsNo_; i++) { observationTimes_.Add(dayCounter.yearFraction(referenceDate, observationDates_[i])); } }
public InterestRate equivalentRate(Date d1, Date d2, DayCounter resultDC, Compounding comp, Frequency freq) { if (!(d2 > d1)) { throw new ArgumentException("d1 (" + d1 + ") " + "later than or equal to d2 (" + d2 + ")"); } double t1 = dc_.yearFraction(d1, d2); double t2 = resultDC.yearFraction(d1, d2); return(impliedRate(compoundFactor(t1), t2, resultDC, comp, freq)); }
public static Date time2Date(Date referenceDate, DayCounter dc, double t) { t -= 1e4 * Const.QL_EPSILON; // add a small buffer for rounding errors Date d = new Date(referenceDate); while (dc.yearFraction(referenceDate, d += new Period(1, TimeUnit.Years)) < t) { ; } d -= new Period(1, TimeUnit.Years); while (dc.yearFraction(referenceDate, d += new Period(1, TimeUnit.Months)) < t) { ; } d -= new Period(1, TimeUnit.Months); while (dc.yearFraction(referenceDate, d++) < t) { ; } return(d); }
public override Vector values(Vector x) { Date refDate = fittingMethod_.curve_.referenceDate(); DayCounter dc = fittingMethod_.curve_.dayCounter(); int n = fittingMethod_.curve_.bondHelpers_.Count; Vector values = new Vector(n); for (int i = 0; i < n; ++i) { BondHelper helper = fittingMethod_.curve_.bondHelpers_[i]; Bond bond = helper.bond(); Date bondSettlement = bond.settlementDate(); // CleanPrice_i = sum( cf_k * d(t_k) ) - accruedAmount double modelPrice = 0.0; List <CashFlow> cf = bond.cashflows(); for (int k = firstCashFlow_[i]; k < cf.Count; ++k) { double tenor = dc.yearFraction(refDate, cf[k].date()); modelPrice += cf[k].amount() * fittingMethod_.discountFunction(x, tenor); } if (helper.useCleanPrice()) { modelPrice -= bond.accruedAmount(bondSettlement); } // adjust price (NPV) for forward settlement if (bondSettlement != refDate) { double tenor = dc.yearFraction(refDate, bondSettlement); modelPrice /= fittingMethod_.discountFunction(x, tenor); } double marketPrice = helper.quote().link.value(); double error = modelPrice - marketPrice; double weightedError = fittingMethod_.weights_[i] * error; values[i] = weightedError * weightedError; } return(values); }
//public InterpolatedDiscountCurve(List<Date> dates, List<double> discounts, DayCounter dayCounter, // Calendar cal = Calendar(), Interpolator interpolator = Interpolator()) public InterpolatedDiscountCurve(List <Date> dates, List <double> discounts, DayCounter dayCounter, Calendar cal, List <Handle <Quote> > jumps = null, List <Date> jumpDates = null, Interpolator interpolator = default(Interpolator)) : base(dates.First(), cal, dayCounter, jumps, jumpDates) { times_ = new List <double>(); data_ = discounts; interpolator_ = interpolator; dates_ = dates; if (dates_.empty()) { throw new ApplicationException("no input dates given"); } if (data_.empty()) { throw new ApplicationException("no input discount factors given"); } if (data_.Count != dates_.Count) { throw new ApplicationException("dates/discount factors count mismatch"); } if (data_[0] != 1.0) { throw new ApplicationException("the first discount must be == 1.0 " + "to flag the corrsponding date as settlement date"); } times_ = new InitializedList <double>(dates_.Count - 1); times_.Add(0.0); for (int i = 1; i < dates_.Count; i++) { if (!(dates_[i] > dates_[i - 1])) { throw new ApplicationException("invalid date (" + dates_[i] + ", vs " + dates_[i - 1] + ")"); } if (!(data_[i] > 0.0)) { throw new ApplicationException("negative discount"); } times_[i] = dayCounter.yearFraction(dates_[0], dates_[i]); if (Utils.close(times_[i], times_[i - 1])) { throw new ApplicationException("two dates correspond to the same time " + "under this curve's day count convention"); } } setupInterpolation(); interpolation_.update(); }
// helper function used to calculate Time-To-Discount for each stage when calculating discount factor stepwisely public static double getStepwiseDiscountTime(CashFlow cashFlow, DayCounter dc, Date npvDate, Date lastDate) { Date cashFlowDate = cashFlow.date(); Date refStartDate, refEndDate; Coupon coupon = cashFlow as Coupon; if (coupon != null) { refStartDate = coupon.referencePeriodStart; refEndDate = coupon.referencePeriodEnd; } else { if (lastDate == npvDate) { // we don't have a previous coupon date, // so we fake it refStartDate = cashFlowDate - new Period(1, TimeUnit.Years); } else { refStartDate = lastDate; } refEndDate = cashFlowDate; } if (coupon != null && lastDate != coupon.accrualStartDate()) { double couponPeriod = dc.yearFraction(coupon.accrualStartDate(), cashFlowDate, refStartDate, refEndDate); double accruedPeriod = dc.yearFraction(coupon.accrualStartDate(), lastDate, refStartDate, refEndDate); return(couponPeriod - accruedPeriod); } else { return(dc.yearFraction(lastDate, cashFlowDate, refStartDate, refEndDate)); } }
public static double inflationYearFraction(Frequency f, bool indexIsInterpolated, DayCounter dayCounter, Date d1, Date d2) { double t=0; if (indexIsInterpolated) { // N.B. we do not use linear interpolation between flat // fixing forecasts for forecasts. This avoids awkwardnesses // when bootstrapping the inflation curve. t = dayCounter.yearFraction(d1, d2); } else { // I.e. fixing is constant for the whole inflation period. // Use the value for half way along the period. // But the inflation time is the time between period starts KeyValuePair<Date,Date> limD1 = inflationPeriod(d1, f); KeyValuePair<Date,Date> limD2 = inflationPeriod(d2, f); t = dayCounter.yearFraction(limD1.Key, limD2.Key); } return t; }
public FdmAffineModelTermStructure( Vector r, Calendar cal, DayCounter dayCounter, Date referenceDate, Date modelReferenceDate, IAffineModel model) : base(referenceDate, cal, dayCounter) { r_ = r; t_ = dayCounter.yearFraction(modelReferenceDate, referenceDate); model_ = model; model_.registerWith(update); }
public DiscretizedSwap(VanillaSwap.Arguments args, Date referenceDate, DayCounter dayCounter) { arguments_ = args; fixedResetTimes_ = new InitializedList <double>(args.fixedResetDates.Count); for (int i = 0; i < fixedResetTimes_.Count; ++i) { fixedResetTimes_[i] = dayCounter.yearFraction(referenceDate, args.fixedResetDates[i]); } fixedPayTimes_ = new InitializedList <double>(args.fixedPayDates.Count); for (int i = 0; i < fixedPayTimes_.Count; ++i) { fixedPayTimes_[i] = dayCounter.yearFraction(referenceDate, args.fixedPayDates[i]); } floatingResetTimes_ = new InitializedList <double>(args.floatingResetDates.Count); for (int i = 0; i < floatingResetTimes_.Count; ++i) { floatingResetTimes_[i] = dayCounter.yearFraction(referenceDate, args.floatingResetDates[i]); } floatingPayTimes_ = new InitializedList <double>(args.floatingPayDates.Count); for (int i = 0; i < floatingPayTimes_.Count; ++i) { floatingPayTimes_[i] = dayCounter.yearFraction(referenceDate, args.floatingPayDates[i]); } }
public static InterestRate impliedRate(double compound, Date d1, Date d2, DayCounter resultDC, Compounding comp, Frequency freq) { if (!(d2 > d1)) throw new ArgumentException("d1 (" + d1 + ") " + "later than or equal to d2 (" + d2 + ")"); double t = resultDC.yearFraction(d1, d2); return impliedRate(compound, t, resultDC, comp, freq); }
public InterestRate equivalentRate(Date d1, Date d2, DayCounter resultDC, Compounding comp, Frequency freq) { if (!(d2 > d1)) throw new ArgumentException("d1 (" + d1 + ") " + "later than or equal to d2 (" + d2 + ")"); double t1 = dc_.yearFraction(d1, d2); double t2 = resultDC.yearFraction(d1, d2); return impliedRate(compoundFactor(t1), t2, resultDC, comp, freq); }
//! implied rate for a given compound factor between two dates. /*! The resulting rate is calculated taking the required day-counting rule into account. */ public static InterestRate impliedRate(double compound, DayCounter resultDC, Compounding comp, Frequency freq, Date d1, Date d2, Date refStart = null, Date refEnd = null) { Utils.QL_REQUIRE(d2>=d1, "d1 (" + d1 + ") later than d2 (" + d2 + ")"); double t = resultDC.yearFraction(d1, d2, refStart, refEnd); return impliedRate(compound, resultDC, comp, freq, t); }
//! equivalent rate for a compounding period between two dates /*! The resulting rate is calculated taking the required day-counting rule into account. */ public InterestRate equivalentRate(DayCounter resultDC, Compounding comp, Frequency freq, Date d1, Date d2, Date refStart = null,Date refEnd = null) { Utils.QL_REQUIRE(d2>=d1, "d1 (" + d1 + ") later than d2 (" + d2 + ")"); double t1 = dc_.yearFraction(d1, d2, refStart, refEnd); double t2 = resultDC.yearFraction(d1, d2, refStart, refEnd); return impliedRate(compoundFactor(t1), resultDC, comp, freq, t2); }
protected virtual double seasonalityCorrection(double rate, Date atDate, DayCounter dc, Date curveBaseDate, bool isZeroRate) { // need _two_ corrections in order to get: seasonality = factor[atDate-seasonalityBase] / factor[reference-seasonalityBase] // i.e. for ZERO inflation rates you have the true fixing at the curve base so this factor must be normalized to one // for YoY inflation rates your reference point is the year before double factorAt = this.seasonalityFactor(atDate); //Getting seasonality correction for either ZC or YoY double f; if (isZeroRate) { double factorBase = this.seasonalityFactor(curveBaseDate); double seasonalityAt = factorAt / factorBase; double timeFromCurveBase = dc.yearFraction(curveBaseDate, atDate); f = Math.Pow(seasonalityAt, 1 / timeFromCurveBase); } else { double factor1Ybefore = this.seasonalityFactor(atDate - new Period(1, TimeUnit.Years)); f = factorAt / factor1Ybefore; } return (rate + 1) * f - 1; }
/*! 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); }
public FuturesRateHelper(Handle<Quote> price, Date immDate, int nMonths, Calendar calendar, BusinessDayConvention convention, bool endOfMonth, DayCounter dayCounter, Handle<Quote> convexityAdjustment) : base(price) { convAdj_ = convexityAdjustment; if (!IMM.isIMMdate(immDate, false)) throw new ArgumentException(immDate + "is not a valid IMM date"); earliestDate_ = immDate; latestDate_ = calendar.advance(immDate, new Period(nMonths, TimeUnit.Months), convention, endOfMonth); yearFraction_ = dayCounter.yearFraction(earliestDate_, latestDate_); convAdj_.registerWith(update); }
// overloaded constructors public FuturesRateHelper(double price, Date immDate, int nMonths, Calendar calendar, BusinessDayConvention convention, bool endOfMonth, DayCounter dayCounter, double convAdj) : base(price) { convAdj_ = new Handle<Quote>(new SimpleQuote(convAdj)); if (!IMM.isIMMdate(immDate, false)) throw new ArgumentException(immDate + "is not a valid IMM date"); earliestDate_ = immDate; latestDate_ = calendar.advance(immDate, new Period(nMonths, TimeUnit.Months), convention, endOfMonth); yearFraction_ = dayCounter.yearFraction(earliestDate_, latestDate_); }