Esempio n. 1
0
        private void SolveBondYield()
        {
            DateTime previousCoupon;
            DateTime nextCoupon;

            Basis.GetPreviousNextCoupons(this.Settlement, this.Maturity, this.Period, out previousCoupon, out nextCoupon);

            var accruedPeriod = Basis.AccruedPeriod(this.Settlement, previousCoupon, this.Period, this.DayCountBasis);
            var payments      = Basis.PaymentCount(this.Maturity, nextCoupon, this.Period);

            this.Accrued = accruedPeriod * (this.Rate / this.Period) * this.Principal;

            Func <double, double> bondPrice = (calcYield =>
            {
                var pv = 0d;
                for (var i = 0; i < payments; ++i)
                {
                    var payment = (this.Rate / this.Period);
                    var discountFactor = Math.Pow(1 + calcYield / this.Period, -(1 - accruedPeriod + i));
                    pv += (i == payments - 1) ? (payment + 1) * discountFactor : payment * discountFactor;
                }
                return(pv - accruedPeriod * (this.Rate / this.Period) - this.Clean);
            });

            this.YieldToMaturity = Mathematics.FindRoot(bondPrice, 0d, 0.5d);
            this.PV = this.Clean * this.Principal + this.Accrued;
        }
Esempio n. 2
0
        public void TestFindQuadraticRoot()
        {
            // Quadratic with roots of x = -7 and x = 4
            Func <double, double> function = x => (2 * x - 8) * (x + 7);

            Assert.AreEqual(-7.0, Mathematics.FindRoot(function, -10d, 0d), Mathematics.Error, "Finding root where x=-7");
            Assert.AreEqual(4.0, Mathematics.FindRoot(function, 0d, 10d), Mathematics.Error, "Finding root where x=4");
        }
Esempio n. 3
0
        public void SolveInternalRateOfReturn()
        {
            Func <double, double> cashflowPrice = (calcRate =>
            {
                var pv = 0d;
                for (var i = 1; i <= this.Years * this.Period; ++i)
                {
                    pv += this.Principal * (this.Coupon / this.Period) * Math.Pow(1 + calcRate / this.Period, -i);
                }
                return(pv - this.PV);
            });

            //	Assume yield is between 0% and 50%
            this.Rate = Mathematics.FindRoot(cashflowPrice, 0d, 0.5d);
        }