public void ProduceOfferReturnsCorrectResult(
            LoanType loanType,
            int term,
            PaymentFrequency frequency)
        {
            var sut         = new DesiredLoanMortgageApplicationProcessor();
            var application = new MortgageApplication
            {
                DesiredLoanType  = loanType,
                DesiredTerm      = term,
                DesiredFrequency = frequency
            };

            var actual = sut.ProduceOffer(application);

            var expected = new IRendering[]
            {
                new Heading2Rendering("Desired loan"),
                new BoldRendering("Loan type:"),
                new TextRendering(" " + loanType),
                new LineBreakRendering(),
                new BoldRendering("Term:"),
                new TextRendering(" " + term + " years."),
                new LineBreakRendering(),
                new BoldRendering("Frequency:"),
                new TextRendering(" " + frequency),
                new LineBreakRendering()
            };

            Assert.Equal(expected, actual);
        }
        public void ProduceOfferReturnsCorrectResult(
            LoanType loanType,
            int term,
            PaymentFrequency frequency)
        {
            var sut = new DesiredLoanMortgageApplicationProcessor();
            var application = new MortgageApplication
            {
                DesiredLoanType = loanType,
                DesiredTerm = term,
                DesiredFrequency = frequency
            };

            var actual = sut.ProduceOffer(application);

            var expected = new IRendering[]
            {
                new Heading2Rendering("Desired loan"),
                new BoldRendering("Loan type:"),
                new TextRendering(" " + loanType),
                new LineBreakRendering(),
                new BoldRendering("Term:"),
                new TextRendering(" " + term + " years."),
                new LineBreakRendering(),
                new BoldRendering("Frequency:"),
                new TextRendering(" " + frequency),
                new LineBreakRendering()
            };
            Assert.Equal(expected, actual);
        }
Example #3
0
        /// <summary>
        /// The yield calculated using the "book" value of the bond in place of the current market price.
        /// </summary>
        /// <param name="notional"></param>
        /// <param name="couponRate"></param>
        /// <param name="paymentFrequency"></param>
        /// <param name="evaluationDate"></param>
        /// <param name="paymentDates"></param>
        /// <param name="purchasePrice"></param>
        /// <param name="purchaseDate"></param>
        /// <returns></returns>
        public static double BookYield(double notional, double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double purchasePrice, DateTime purchaseDate)
        {
            DateTime maturityDate = paymentDates[paymentDates.Length - 1];
            double   bv           = BookValue(notional, purchasePrice, purchaseDate, evaluationDate, maturityDate);

            return(Yield(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, bv));
        }
        internal static PaymentFrequency SelectPaymentFrequency(string frequencyMonths)
        {
            PaymentFrequency paymentFrequency = null;

            StringBuilder SqlStatement = new StringBuilder();

            //SQL Statement =============================================================
            SqlStatement.Append("Select * From PaymentFrequencies ");
            SqlStatement.Append("Where PaymentFrequencyMonths='");
            SqlStatement.Append(frequencyMonths);
            SqlStatement.Append("'");

            //SqlCommand sqlCommand = new SqlCommand(SqlStatement.ToString(), Sahara.Core.Settings.Azure.Databases.DatabaseConnections.AccountsSqlConnection);
            SqlCommand sqlCommand = Settings.Azure.Databases.DatabaseConnections.AccountsSqlConnection.CreateCommand();

            sqlCommand.CommandText = SqlStatement.ToString();


            sqlCommand.Connection.OpenWithRetry();
            SqlDataReader reader = sqlCommand.ExecuteReaderWithRetry();

            while (reader.Read())
            {
                paymentFrequency = Transforms.Transforms.DataReader_to_PaymentFrequency(reader);
            }

            sqlCommand.Connection.Close();

            return(paymentFrequency);
        }
Example #5
0
        public static double Yield(double notional, double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double price)
        {
            double T = (paymentDates.Last() - evaluationDate).Days / CalendarDaysPerYear;

            if (paymentFrequency == 0)
            {
                return(Math.Pow(notional / price, 1.0 / T) - 1.0);
            }

            const double tolerance = 0.00001;
            const int    maxLoops  = 16;

            //Initial estimate for yield is based on first order Taylor expansion and annual frequency.
            double c = couponRate * notional;
            double y = (notional + T * c - price) / (price + (T - 1) * (notional + 0.5 * T * c));

            double impliedPrice = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, y);

            int nLoops = 0;

            while (Math.Abs(impliedPrice - price) > tolerance)
            {
                nLoops++;
                if (nLoops > maxLoops)
                {
                    throw new Exception("Yield did not converge.");
                }
                double dollarDur = DollarDuration(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, y);
                y            = y - (impliedPrice - price) / dollarDur;
                impliedPrice = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, y);
            }
            return(y);
        }
Example #6
0
        /// <summary>
        /// ([Price minus] + [Price plus]  - 2 x [Price zero]) / ([Price zero] x dY^2).
        /// [Price zero] is the present value of the bond evaluate at the current yield.
        /// [Price minus] and [Price plus] are the present value calculate using (yield - dY) and (yield + dY), respectively.
        /// dY = 0.0001
        /// </summary>
        public static double EffectiveConvexity(double notional, double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double yield)
        {
            double pZero = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, yield);
            double pPlus = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, yield + 0.0001);
            double pMinu = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, yield - 0.0001);

            return(100000000 * (pMinu + pPlus - 2 * pZero) / (pZero));
        }
 public static List <AmortizationScheduleItem> GenerateAmortizationSchedule(
     Loan loan,
     PaymentFrequency paymentFrequency,
     PaymentType paymentType,
     int term
     )
 {
     throw new System.NotImplementedException();
 }
Example #8
0
		public Scenario(string title, string subTitle, bool isDepleting, CompoundingFrequency compoundingFrequency, PaymentFrequency paymentFrequency, PeriodFrequency periodFrequency)
		{
			Title = title;
			SubTitle = subTitle;
			IsDepleting = isDepleting;
			CompoundingFrequency = compoundingFrequency;
			PaymentFrequency = paymentFrequency;
			PeriodFrequency = periodFrequency;
		}
        public PaymentFrequency FindPaymentFrequencyByName(string paymentFrequencyName)
        {
            PaymentFrequency f1 = _context.PaymentFrequencies.Where(x => x.PaymentFrequencyName.ToUpper().StartsWith(paymentFrequencyName.ToUpper())).FirstOrDefault();
            PaymentFrequency f2 = (from cf in _context.PaymentFrequencies
                                   where cf.PaymentFrequencyName.ToUpper().StartsWith(paymentFrequencyName.ToUpper())
                                   select cf).FirstOrDefault();

            return(f2);
        }
Example #10
0
        /// <summary>
        /// -(d[present value] / d[yield]) x (1/[present value])
        /// </summary>
        public static double ModifiedDuration(double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double yield)
        {
            //Note: Modified duration does not depend on the notional of the bond. Both dVdY and pv are proportional to the notional.
            //As long as we use the same notional in both formulas, the final result will be the same.
            double dVdY = DollarDuration(100.00, couponRate, paymentFrequency, evaluationDate, paymentDates, yield);
            double pv   = PresentValue(100.00, couponRate, paymentFrequency, evaluationDate, paymentDates, yield);

            return(-dVdY / pv);
        }
Example #11
0
 /// <summary>
 /// Azonos nagyságú törlesztőrészletek esetére
 /// </summary>
 /// <param name="instalmentsCount">A törlesztések száma</param>
 /// <param name="instalment">Egy törlesztő részlet mértéke</param>
 /// <param name="paymentFrequency">Törlesztés gyakorisága. Pl.: heti,havi</param>
 public ThmCalculation(int instalmentsCount, double instalment, PaymentFrequency paymentFrequency)
 {
     this.instalment       = instalment;
     this.paymentFrequency = paymentFrequency;
     this.instalments      = new double[instalmentsCount];
     for (int i = 0; i < this.instalments.Length; i++)
     {
         this.instalments[i] = instalment;
     }
 }
Example #12
0
        public static PaymentFrequency DataReader_to_PaymentFrequency(SqlDataReader reader)
        {
            PaymentFrequency paymentFrequency = new PaymentFrequency();

            paymentFrequency.PaymentFrequencyMonths = (int)reader["PaymentFrequencyMonths"];
            paymentFrequency.PaymentFrequencyName   = (String)reader["PaymentFrequencyName"];
            paymentFrequency.PriceBreak             = (Decimal)reader["PriceBreak"];
            paymentFrequency.Interval      = (String)reader["Interval"];
            paymentFrequency.IntervalCount = (int)reader["IntervalCount"];
            return(paymentFrequency);
        }
        /// <summary>
        /// This method selects value from Payment Frequency field. Returns nothing.
        /// </summary>
        /// <param name="paymentFrequency">use PaymentFrequency type</param>
        public void SelectPaymentFrequency(PaymentFrequency paymentFrequency)
        {
            string paymentFrequencyPath = "//*[@id='FrequenceVersement']//..//..//div[@class='selectric-scroll']//ul//*[";

            paymentFrequencyBtn.Click();
            paymentFrequency++;
            int         item = (int)paymentFrequency;
            IWebElement paymentFrequencySelect = driver.FindElement(By.XPath(paymentFrequencyPath + item + "]"));

            paymentFrequencySelect.Click();
        }
Example #14
0
 protected Property(T externalSourceId, int noOfBedrooms, PropertyType propertyType, string displayAddress, decimal price,
                    string priceCurrencyCode, PaymentFrequency paymentFrequency, Location location)
 {
     ExternalSourceId  = externalSourceId;
     NoOfBedrooms      = noOfBedrooms;
     Type              = propertyType;
     DisplayAddress    = displayAddress;
     Price             = price;
     Location          = location;
     PriceCurrencyCode = priceCurrencyCode;
     PaymentFrequency  = paymentFrequency;
 }
Example #15
0
        public double CalculatePayments(
            double loanAmount,
            double interestRate,
            double loanLength,
            PaymentFrequency paymentFrequency)
        {
            var numberPayments = loanLength * 12;

            interestRate /= 1200.00;
            var monthlyPayment = -((-loanAmount * Math.Pow(1 + interestRate, numberPayments)) / (((Math.Pow((1 + interestRate), numberPayments) - 1) / interestRate))) * 12 / (int)paymentFrequency;
            return monthlyPayment;
        }
Example #16
0
        public double CalculateLength(
            double loanAmount,
            double paymentAmount,
            double interestRate,
            PaymentFrequency paymentFrequency)
        {
            interestRate /= 1200.00;
            loanAmount *= (-1);
            var monthlyPayment = paymentAmount / 12 * (int)paymentFrequency;

            return Math.Log(monthlyPayment / (loanAmount * interestRate + monthlyPayment)) / Math.Log(1 + interestRate) / 12;
        }
Example #17
0
        public double CalculateLength(
            double loanAmount,
            double paymentAmount,
            double interestRate,
            PaymentFrequency paymentFrequency)
        {
            interestRate /= 1200.00;
            loanAmount   *= (-1);
            var monthlyPayment = paymentAmount / 12 * (int)paymentFrequency;

            return(Math.Log(monthlyPayment / (loanAmount * interestRate + monthlyPayment)) / Math.Log(1 + interestRate) / 12);
        }
Example #18
0
        public double CalculatePayments(
            double loanAmount,
            double interestRate,
            double loanLength,
            PaymentFrequency paymentFrequency)
        {
            var numberPayments = loanLength * 12;

            interestRate /= 1200.00;
            var monthlyPayment = -((-loanAmount * Math.Pow(1 + interestRate, numberPayments)) / (((Math.Pow((1 + interestRate), numberPayments) - 1) / interestRate))) * 12 / (int)paymentFrequency;

            return(monthlyPayment);
        }
Example #19
0
 private static PaymentSchedule GetTestPaymentSchedule(
     DateTime?endDate = null,
     PaymentFrequency paymentFrequency = PaymentFrequency.Annual,
     decimal paymentAmount             = 0,
     PaymentType paymentType           = PaymentType.InterestOnly,
     DateTime?startDate = null
     ) => new PaymentSchedule
 {
     EndDate          = endDate ?? new DateTime(2001, 1, 1),
     PaymentAmount    = paymentAmount,
     PaymentFrequency = paymentFrequency,
     PaymentType      = paymentType,
     StartDate        = startDate ?? new DateTime(2001, 1, 1)
 };
        public void ItPublishesTheCorrectCommands
            (bool isToday, PaymentFrequency frequency  // inputs
            , int immediate, int future, int standing) // expectations
        {
            calendar.IsToday(Arg.Any <DateTime>()).Returns(isToday);
            var transfer = new Transfer {
                Frequency = frequency
            };

            sut.Handle(transfer);

            publisher.Received(immediate).Publish(Arg.Any <TransferNow>());
            publisher.Received(future).Publish(Arg.Any <TransferOn>());
            publisher.Received(standing).Publish(Arg.Any <SetupStandingOrder>());
        }
Example #21
0
        /// <summary>
        /// Present value for a bond.
        /// </summary>
        public static double PresentValue(double notional, double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double yield)
        {
            double pv            = 0;
            double df            = 0;
            double couponPayment = paymentFrequency == PaymentFrequency.Zero ? 0 : notional * couponRate / (double)paymentFrequency;

            foreach (DateTime date in paymentDates)
            {
                double years = (date - evaluationDate).Days / CalendarDaysPerYear;
                df  = Math.Pow(1.0 + yield, -years);
                pv += df;
            }
            pv *= couponPayment;
            pv += df * notional;
            return(pv);
        }
Example #22
0
        /// <summary>
        /// d[present value] / d[yield]
        /// </summary>
        public static double DollarDuration(double notional, double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double yield)
        {
            double dur = 0;
            double df = 0, years = 0;
            double couponPayment = paymentFrequency == PaymentFrequency.Zero ? 0 : notional * couponRate / (double)paymentFrequency;

            foreach (DateTime date in paymentDates)
            {
                years = (date - evaluationDate).Days / CalendarDaysPerYear;
                df    = Math.Pow(1.0 + yield, -years - 1);
                dur  -= years * df;
            }
            dur *= couponPayment;
            dur -= years * df * notional;
            return(dur);
        }
Example #23
0
        public static PaymentFrequency GetPaymentFrequency(string frequencyMonths)
        {
            //ConnectionMultiplexer con = ConnectionMultiplexer.Connect(Sahara.Core.Settings.Azure.Redis.RedisConnections.AccountManager_RedisConfiguration);
            //IDatabase cache = con.GetDatabase();
            //IDatabase cache = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.AccountManager_Multiplexer.GetDatabase();
            IDatabase cache = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.RedisMultiplexer.GetDatabase();

            string redisHashField = PaymentPlansHash.Fields.PaymentFrequency(frequencyMonths);

            PaymentFrequency paymentFrequencyCache = null;

            try
            {
                var redisValue = cache.HashGet(PaymentPlansHash.Key, redisHashField);
                if (redisValue.HasValue)
                {
                    paymentFrequencyCache = JsonConvert.DeserializeObject <PaymentFrequency>(redisValue);
                }
            }
            catch
            {
            }


            if (paymentFrequencyCache == null)
            {
                var paymentFrequency = Sql.Statements.SelectStatements.SelectPaymentFrequency(frequencyMonths);

                try
                {
                    //Store into redis cache:
                    cache.HashSet(PaymentPlansHash.Key, redisHashField, JsonConvert.SerializeObject(paymentFrequency), When.Always, CommandFlags.FireAndForget);
                    //con.Close();
                }
                catch
                {
                }


                return(paymentFrequency);
            }
            else
            {
                return(paymentFrequencyCache);
            }
        }
        public static double? CalculatePayments(
            double? loanAmount,
            double? interestRate,
            double? loanLength,
            PaymentFrequency? paymentFrequency)
        {
            if (loanAmount == null || interestRate == null || loanLength == null || paymentFrequency == null)
                return null;

            var loanAmountValue = loanAmount.Value;
            var interestRateValue = interestRate.Value;
            var paymentFrequencyValue = paymentFrequency.Value;
            var numberPayments = loanLength.Value * 12;

            interestRateValue /= 1200.00;
            var monthlyPayment = -((-loanAmountValue * Math.Pow(1 + interestRateValue, numberPayments)) / (((Math.Pow((1 + interestRateValue), numberPayments) - 1) / interestRateValue))) * 12 / (int)paymentFrequencyValue;
            return Math.Round(monthlyPayment, 2);
        }
Example #25
0
        /// <summary>
        /// d^2[present value] / d^2[yield] x (1/[present value])
        /// </summary>
        public static double Convexity(double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double yield)
        {
            //Note: Convexity does not depend on the notional of the bond. Both cnvx and pv are proportional to the notional.
            //As long as we use the same notional in both formulas, the final result will be the same.
            const double notional = 100;

            double cnvx = 0;
            double df = 0, years = 0;
            double couponPayment =  paymentFrequency == PaymentFrequency.Zero ? 0 : notional * couponRate / (double)paymentFrequency;
            foreach (DateTime date in paymentDates)
            {
                years = (date - evaluationDate).Days / CalendarDaysPerYear;
                df = Math.Pow(1.0 + yield, -years - 2);
                cnvx += years * (1 + years) * df;
            }
            cnvx *= couponPayment;
            cnvx += years * df * notional;
            double pv = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, yield);
            return cnvx / pv;
        }
Example #26
0
        private List <DateTime> GenerateDates(DateTime start, DateTime end, PaymentFrequency frequency)
        {
            List <DateTime> dateTimes = new List <DateTime>();
            DateTime        nextDate  = start;

            do
            {
                dateTimes.Add(nextDate);
                switch (frequency)
                {
                case PaymentFrequency.Annualy:
                    nextDate = nextDate.AddYears(1);
                    break;

                case PaymentFrequency.HalfYearly:
                    nextDate = nextDate.AddMonths(6);
                    break;

                case PaymentFrequency.Quarterly:
                    nextDate = nextDate.AddMonths(3);
                    break;

                case PaymentFrequency.Monthly:
                    nextDate = nextDate.AddMonths(1);
                    break;

                case PaymentFrequency.Fortnightly:
                    nextDate = nextDate.AddDays(14);
                    break;

                case PaymentFrequency.Weekly:
                    nextDate = nextDate.AddDays(7);
                    break;

                default:
                    nextDate = end;
                    break;
                }
            } while (nextDate <= end);
            return(dateTimes);
        }
        public static double? CalculateLength(
            double? loanAmount,
            double? paymentAmount,
            double? interestRate,
            PaymentFrequency? paymentFrequency)
        {
            if (loanAmount == null || interestRate == null || paymentAmount == null || paymentFrequency == null)
                return null;

            var interestRateValue = interestRate.Value;
            var loanAmountValue = loanAmount.Value;
            var paymentAmountValue = paymentAmount.Value;
            var paymentFrequencyValue = paymentFrequency.Value;

            interestRateValue /= 1200.00;
            loanAmountValue *= (-1);

            var monthlyPayment = paymentAmountValue / 12 * (int)paymentFrequencyValue;

            return Math.Round(Math.Log(monthlyPayment / (loanAmountValue * interestRateValue + monthlyPayment)) / Math.Log(1 + interestRateValue) / 12, 3);
        }
Example #28
0
        /// <summary>
        /// d^2[present value] / d^2[yield] x (1/[present value])
        /// </summary>
        public static double Convexity(double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double yield)
        {
            //Note: Convexity does not depend on the notional of the bond. Both cnvx and pv are proportional to the notional.
            //As long as we use the same notional in both formulas, the final result will be the same.
            const double notional = 100;

            double cnvx = 0;
            double df = 0, years = 0;
            double couponPayment = paymentFrequency == PaymentFrequency.Zero ? 0 : notional * couponRate / (double)paymentFrequency;

            foreach (DateTime date in paymentDates)
            {
                years = (date - evaluationDate).Days / CalendarDaysPerYear;
                df    = Math.Pow(1.0 + yield, -years - 2);
                cnvx += years * (1 + years) * df;
            }
            cnvx *= couponPayment;
            cnvx += years * df * notional;
            double pv = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, yield);

            return(cnvx / pv);
        }
Example #29
0
        private static void RunFrequencyTest(
            List <DateTime> expected,
            LocalDate endDate,
            PaymentFrequency frequency
            )
        {
            //Act
            var actual = AmortizationCalculator.GenerateAmortizationSchedule(
                GetTestLoan(
                    amount: 1000,
                    maturityDate: endDate.ToDateTimeUnspecified()
                    ),
                new List <PaymentSchedule>
            {
                GetTestPaymentSchedule(
                    endDate: endDate.ToDateTimeUnspecified(),
                    paymentFrequency: frequency
                    )
            }
                );

            //Assert
            actual.Select(x => x.Date).Should().Equal(expected);
        }
        public void GenerateTotalByDateRange()
        {
            //Arrange
            var databaseFactory = new DatabaseFactory();
            var unitOfWork      = new UnitOfWork(databaseFactory);

            var employeeHoursRepository      = new EmployeeHoursRepository(databaseFactory);
            var totalEmployeeHoursRepository = new TotalEmployeeHoursRepository(databaseFactory);

            var employeeDepartmentRepository   = new EmployeeDepartmentRepository(databaseFactory);
            var employeeRepository             = new EmployeeRepository(databaseFactory, employeeDepartmentRepository);
            var attendanceRepository           = new AttendanceRepository(databaseFactory);
            var attendanceLogRepository        = new AttendanceLogRepository(databaseFactory, employeeRepository);
            var settingRepository              = new SettingRepository(databaseFactory);
            var employeeWorkScheduleRepository = new EmployeeWorkScheduleRepository(databaseFactory);
            var employeeInfoRepository         = new EmployeeInfoRepository(databaseFactory);
            var frequencyRepository            = new FrequencyRepository(databaseFactory);
            var paymentFrequencyRepository     = new PaymentFrequencyRepository(databaseFactory);

            var employeeInfoService         = new EmployeeInfoService(employeeInfoRepository);
            var attendanceLogService        = new AttendanceLogService(attendanceLogRepository);
            var attendanceService           = new AttendanceService(unitOfWork, attendanceRepository, attendanceLogService, employeeHoursRepository);
            var settingService              = new SettingService(settingRepository);
            var employeeWorkScheduleService = new EmployeeWorkScheduleService(employeeWorkScheduleRepository);

            var employeeHoursService = new EmployeeHoursService(unitOfWork, employeeHoursRepository,
                                                                attendanceService, settingService, employeeWorkScheduleService, employeeInfoService);
            var totalEmployeeHoursService = new TotalEmployeeHoursService(unitOfWork, totalEmployeeHoursRepository, employeeHoursService, settingService);

            //Delete info
            employeeRepository.ExecuteSqlCommand("SET FOREIGN_KEY_CHECKS = 0");
            employeeRepository.ExecuteSqlCommand("TRUNCATE TABLE frequency");
            employeeRepository.ExecuteSqlCommand("TRUNCATE TABLE payment_frequency");
            employeeRepository.ExecuteSqlCommand("TRUNCATE TABLE employee_hours");
            employeeRepository.ExecuteSqlCommand("TRUNCATE TABLE employee_hours_total");
            employeeRepository.ExecuteSqlCommand("TRUNCATE TABLE employee");
            employeeRepository.ExecuteSqlCommand("SET FOREIGN_KEY_CHECKS = 1");

            unitOfWork.Commit();

            var employee1 = new Employee
            {
                EmployeeCode = "11001",
                FirstName    = "Jona",
                LastName     = "Pereira",
                MiddleName   = "Aprecio",
                BirthDate    = DateTime.Parse("02/02/1991"),
                Gender       = 1,
                IsActive     = true
            };

            var employee2 = new Employee
            {
                EmployeeCode = "11001",
                FirstName    = "Jona",
                LastName     = "Pereira",
                MiddleName   = "Aprecio",
                BirthDate    = DateTime.Parse("02/02/1991"),
                Gender       = 1,
                IsActive     = true
            };

            var frequency = new Frequency
            {
                FrequencyName = "Weekly",
                FrequencyType = Entities.Enums.FrequencyType.Weekly
            };

            frequencyRepository.Add(frequency);

            var paymentFrequency = new PaymentFrequency
            {
                Frequency = frequency
            };

            paymentFrequencyRepository.Add(paymentFrequency);

            var employeeInfo1 = new EmployeeInfo
            {
                Employee        = employee1,
                SalaryFrequency = FrequencyType.Weekly
            };

            var employeeInfo2 = new EmployeeInfo
            {
                Employee        = employee2,
                SalaryFrequency = FrequencyType.Weekly
            };

            employeeInfoRepository.Add(employeeInfo1);
            employeeInfoRepository.Add(employeeInfo2);

            /* "03/01/2016 - Employee 1 Regular Total hour 8 */
            var employeeHours1 = new EmployeeHours
            {
                Date               = DateTime.Parse("03/01/2016"),
                Employee           = employee1,
                Hours              = 4,
                OriginAttendanceId = 1,
                Type               = Entities.Enums.RateType.Regular
            };

            var employeeHours3 = new EmployeeHours
            {
                Date               = DateTime.Parse("03/01/2016"),
                Employee           = employee1,
                Hours              = 4,
                OriginAttendanceId = 3,
                Type               = Entities.Enums.RateType.Regular
            };

            /* 03/01/2016 - Employee 1 OT Total hour 3 */
            var employeeHours4 = new EmployeeHours
            {
                Date               = DateTime.Parse("03/01/2016"),
                Employee           = employee1,
                Hours              = 3,
                OriginAttendanceId = 3,
                Type               = Entities.Enums.RateType.OverTime
            };

            /* 03/01/2016 - Employee 1 ND Total hour 1 */
            var employeeHours5 = new EmployeeHours
            {
                Date               = DateTime.Parse("03/01/2016"),
                Employee           = employee1,
                Hours              = 1,
                OriginAttendanceId = 3,
                Type               = Entities.Enums.RateType.NightDifferential
            };

            /* 03/01/2016 - Employee 2 OT Total hour 3 */
            var employeeHours2 = new EmployeeHours
            {
                Date               = DateTime.Parse("03/01/2016"),
                Employee           = employee2,
                Hours              = 3,
                OriginAttendanceId = 2,
                Type               = Entities.Enums.RateType.OverTime
            };

            /* 03/02/2016 - Employee 1 OT Total hour 1 */
            var employeeHours8 = new EmployeeHours
            {
                Date               = DateTime.Parse("03/02/2016"),
                Employee           = employee1,
                Hours              = 1,
                OriginAttendanceId = 5,
                Type               = Entities.Enums.RateType.OverTime
            };

            /* 03/02/2016 - Employee 2 Regular Total hour 4 */
            var employeeHours6 = new EmployeeHours
            {
                Date               = DateTime.Parse("03/02/2016"),
                Employee           = employee2,
                Hours              = 4,
                OriginAttendanceId = 4,
                Type               = Entities.Enums.RateType.Regular
            };

            /* 03/02/2016 - Employee 2 NightDifferential Total hour 6 */
            var employeeHours7 = new EmployeeHours
            {
                Date               = DateTime.Parse("03/02/2016"),
                Employee           = employee2,
                Hours              = 4,
                OriginAttendanceId = 4,
                Type               = Entities.Enums.RateType.NightDifferential
            };

            var employeeHours10 = new EmployeeHours
            {
                Date               = DateTime.Parse("03/02/2016"),
                Employee           = employee2,
                Hours              = 2,
                OriginAttendanceId = 4,
                Type               = Entities.Enums.RateType.NightDifferential
            };

            /* NOT INCLUDED */
            var employeeHours9 = new EmployeeHours
            {
                Date               = DateTime.Parse("03/03/2016"),
                Employee           = employee1,
                Hours              = 10,
                OriginAttendanceId = 5,
                Type               = Entities.Enums.RateType.OverTime
            };

            employeeHoursRepository.Add(employeeHours1);
            employeeHoursRepository.Add(employeeHours2);
            employeeHoursRepository.Add(employeeHours3);
            employeeHoursRepository.Add(employeeHours4);
            employeeHoursRepository.Add(employeeHours5);
            employeeHoursRepository.Add(employeeHours6);
            employeeHoursRepository.Add(employeeHours7);
            employeeHoursRepository.Add(employeeHours8);
            employeeHoursRepository.Add(employeeHours9);
            employeeHoursRepository.Add(employeeHours10);

            unitOfWork.Commit();

            DateTime dateFrom = DateTime.Parse("03/01/2016");
            DateTime dateTo   = DateTime.Parse("03/02/2016");

            totalEmployeeHoursService.GenerateTotalByDateRange(dateFrom, dateTo);

            var totalEmployeeHours = totalEmployeeHoursService.GetByDateRange(dateFrom, dateTo);

            Assert.AreEqual(7, totalEmployeeHours.Count());

            Assert.AreEqual(1, totalEmployeeHours[0].EmployeeId);
            Assert.AreEqual(DateTime.Parse("03/02/2016"), totalEmployeeHours[0].Date);
            Assert.AreEqual(Entities.Enums.RateType.OverTime, totalEmployeeHours[0].Type);
            Assert.AreEqual(1, totalEmployeeHours[0].Hours);

            Assert.AreEqual(2, totalEmployeeHours[1].EmployeeId);
            Assert.AreEqual(DateTime.Parse("03/02/2016"), totalEmployeeHours[1].Date);
            Assert.AreEqual(Entities.Enums.RateType.Regular, totalEmployeeHours[1].Type);
            Assert.AreEqual(4, totalEmployeeHours[1].Hours);

            Assert.AreEqual(2, totalEmployeeHours[2].EmployeeId);
            Assert.AreEqual(DateTime.Parse("03/02/2016"), totalEmployeeHours[2].Date);
            Assert.AreEqual(Entities.Enums.RateType.NightDifferential, totalEmployeeHours[2].Type);
            Assert.AreEqual(6, totalEmployeeHours[2].Hours);

            Assert.AreEqual(1, totalEmployeeHours[3].EmployeeId);
            Assert.AreEqual(DateTime.Parse("03/01/2016"), totalEmployeeHours[3].Date);
            Assert.AreEqual(Entities.Enums.RateType.Regular, totalEmployeeHours[3].Type);
            Assert.AreEqual(8, totalEmployeeHours[3].Hours);

            Assert.AreEqual(1, totalEmployeeHours[4].EmployeeId);
            Assert.AreEqual(DateTime.Parse("03/01/2016"), totalEmployeeHours[4].Date);
            Assert.AreEqual(Entities.Enums.RateType.OverTime, totalEmployeeHours[4].Type);
            Assert.AreEqual(3, totalEmployeeHours[4].Hours);

            Assert.AreEqual(1, totalEmployeeHours[5].EmployeeId);
            Assert.AreEqual(DateTime.Parse("03/01/2016"), totalEmployeeHours[5].Date);
            Assert.AreEqual(Entities.Enums.RateType.NightDifferential, totalEmployeeHours[5].Type);
            Assert.AreEqual(1, totalEmployeeHours[5].Hours);

            Assert.AreEqual(2, totalEmployeeHours[6].EmployeeId);
            Assert.AreEqual(DateTime.Parse("03/01/2016"), totalEmployeeHours[6].Date);
            Assert.AreEqual(Entities.Enums.RateType.OverTime, totalEmployeeHours[6].Type);
            Assert.AreEqual(3, totalEmployeeHours[6].Hours);

            Assert.AreEqual(true, employeeHours1.IsIncludedInTotal);
            Assert.AreEqual(true, employeeHours2.IsIncludedInTotal);
            Assert.AreEqual(true, employeeHours3.IsIncludedInTotal);
            Assert.AreEqual(true, employeeHours4.IsIncludedInTotal);
            Assert.AreEqual(true, employeeHours5.IsIncludedInTotal);
            Assert.AreEqual(true, employeeHours6.IsIncludedInTotal);
            Assert.AreEqual(true, employeeHours7.IsIncludedInTotal);
            Assert.AreEqual(true, employeeHours8.IsIncludedInTotal);
            Assert.AreEqual(false, employeeHours9.IsIncludedInTotal);
        }
Example #31
0
 /// <summary>
 /// Interest = Principal x Coupon x DayCountFactor
 /// </summary>
 public static double DayCountFactor(DayCountConvention dayCountConvention, DateTime date1, DateTime date2, DateTime date3, PaymentFrequency paymentFrequency)
 {
     switch(dayCountConvention)
     {
         case DayCountConvention.ActActUS:
             return (date2 - date1).Days / ((double)paymentFrequency * (date3 - date1).Days);
         default:
             throw new Exception(string.Format(@"No DayCountFactor method for DayCountConvention = {0}", dayCountConvention));
     }
 }
Example #32
0
 /// <summary>
 /// d[present value] / d[yield]
 /// </summary>
 public static double DollarDuration(double notional, double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double yield)
 {
     double dur = 0;
     double df = 0, years = 0;
     double couponPayment = paymentFrequency == PaymentFrequency.Zero ? 0 : notional * couponRate / (double)paymentFrequency;
     foreach (DateTime date in paymentDates)
     {
         years = (date - evaluationDate).Days / CalendarDaysPerYear;
         df = Math.Pow(1.0 + yield, -years - 1);
         dur -= years * df;
     }
     dur *= couponPayment;
     dur -= years * df * notional;
     return dur;
 }
Example #33
0
 /// <summary>
 /// ([Price minus] - [Price plus]) / (2 x [Price zero] x dY).
 /// [Price zero] is the present value of the bond evaluate at the current yield.
 /// [Price minus] and [Price plus] are the present value calculate using (yield - dY) and (yield + dY), respectively.
 /// dY = 0.0001
 /// </summary>
 public static double EffectiveDuration(double notional, double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double yield)
 {
     double pZero = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, yield);
     double pPlus = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, yield + 0.0001);
     double pMinu = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, yield - 0.0001);
     return 10000 * (pMinu - pPlus) / (2 * pZero);
 }
Example #34
0
        /// <summary>
        /// Interest = Principal x Coupon x DayCountFactor
        /// </summary>
        public static double DayCountFactor(DayCountConvention dayCountConvention, DateTime date1, DateTime date2, DateTime date3, PaymentFrequency paymentFrequency)
        {
            switch (dayCountConvention)
            {
            case DayCountConvention.ActActUS:
                return((date2 - date1).Days / ((double)paymentFrequency * (date3 - date1).Days));

            default:
                throw new Exception(string.Format(@"No DayCountFactor method for DayCountConvention = {0}", dayCountConvention));
            }
        }
Example #35
0
 public Loan(string description, string loanType, string loanId, LoanCode loanCode, string activityDate,
             string checkDigits, string reference,
             string nickname,
             int branch,
             int createdByUser,
             int createdAtBranch,
             int loanPurpose,
             CouponCode couponCode,
             string vinNumber,
             string mFOELId,
             string noteNumber,
             string micrAccountNumber,
             Decimal loanBalance,
             Decimal originalBalance,
             Decimal creditLimit,
             Decimal availableCredit,
             Decimal cashAdvanceLimit,
             Decimal availableCashAdvance,
             Decimal balanceTransferLimit,
             Decimal availableBalanceTransfer,
             Decimal combinedCABTLimit,
             Decimal availableCombinedCABT,
             string creditLimitExpiration,
             AvailableCreditCalculationType availableCreditCalculation,
             int creditLimitGroup,
             Decimal amountAdvanced,
             string lastAdvanceDate,
             string lastPaymentDate,
             string firstPaymentDate,
             PaymentType paymentType,
             PaymentMethod paymentMethod,
             PaymentFrequency paymentFrequency,
             string originalLoanDate,
             string openDate,
             string closeDate,
             Decimal payment,
             Decimal alternatePayment,
             string alternatePmtEffective,
             string alternatePmtExpiration,
             Decimal partialPayment,
             Decimal unappliedPartialPayment,
             Decimal stmtUnappliedPartialPmt,
             string allowUnappliedPartialPmt,
             Decimal payoffAmount
             )
 {
     Description                = description;
     Type                       = loanType;
     ID                         = loanId;
     Code                       = loanCode;
     ActivityDate               = activityDate.ParseNullableSymDateString();
     CheckDigits                = checkDigits;
     Reference                  = reference;
     Nickname                   = nickname;
     Branch                     = branch;
     CreatedByUser              = createdByUser;
     CreatedAtBranch            = createdAtBranch;
     LoanPurpose                = loanPurpose;
     CouponCode                 = couponCode;
     VINNumber                  = vinNumber;
     MFOELID                    = mFOELId;
     NoteNumber                 = noteNumber;
     MICRAccountNumber          = micrAccountNumber;
     LoanBalance                = loanBalance;
     OriginalBalance            = originalBalance;
     CreditLimit                = creditLimit;
     AvailableCredit            = availableCredit;
     CashAdvanceLimit           = cashAdvanceLimit;
     AvailableCashAdvance       = availableCashAdvance;
     BalanceTransferLimit       = balanceTransferLimit;
     AvailableBalanceTransfer   = availableBalanceTransfer;
     CombinedCABTLimit          = combinedCABTLimit;
     AvailableCombinedCABT      = availableCombinedCABT;
     CreditLimitExpiration      = creditLimitExpiration.ParseNullableSymDateString();
     AvailableCreditCalculation = availableCreditCalculation;
     CreditLimitGroup           = creditLimitGroup;
     AmountAdvanced             = amountAdvanced;
     LastAdvanceDate            = lastAdvanceDate.ParseNullableSymDateString();
     LastPaymentDate            = lastPaymentDate.ParseNullableSymDateString();
     FirstPaymentDate           = firstPaymentDate.ParseNullableSymDateString();
     PaymentType                = paymentType;
     PaymentMethod              = paymentMethod;
     PaymentFrequency           = paymentFrequency;
     OriginalLoanDate           = originalLoanDate.ParseNullableSymDateString();
     OpenDate                   = openDate.ParseNullableSymDateString();
     CloseDate                  = closeDate.ParseNullableSymDateString();
     Payment                    = payment;
     AlternatePayment           = alternatePayment;
     AlternatePmtEffective      = alternatePmtEffective.ParseNullableSymDateString();
     AlternatePmtExpiration     = alternatePmtExpiration.ParseNullableSymDateString();
     PartialPayment             = partialPayment;
     UnappliedPartialPayment    = unappliedPartialPayment;
     StmtUnappliedPartialPmt    = stmtUnappliedPartialPmt;
     AllowUnappliedPartialPmt   = allowUnappliedPartialPmt;
     PayoffAmount               = payoffAmount;
 }
Example #36
0
 /// <summary>
 /// Present value for a bond.
 /// </summary>
 public static double PresentValue(double notional, double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double yield)
 {
     double pv = 0;
     double df = 0;
     double couponPayment = paymentFrequency == PaymentFrequency.Zero ? 0 : notional * couponRate / (double) paymentFrequency;
     foreach(DateTime date in paymentDates)
     {
         double years = (date - evaluationDate).Days / CalendarDaysPerYear;
         df = Math.Pow(1.0 + yield, -years);
         pv += df;
     }
     pv *= couponPayment;
     pv += df * notional;
     return pv;
 }
Example #37
0
        public static double Yield(double notional, double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double price)
        {
            double T = (paymentDates.Last() - evaluationDate).Days / CalendarDaysPerYear;
            if(paymentFrequency == 0)
                return Math.Pow(notional / price, 1.0 / T) - 1.0;

            const double tolerance = 0.00001;
            const int maxLoops = 16;

            //Initial estimate for yield is based on first order Taylor expansion and annual frequency.
            double c = couponRate * notional;
            double y = (notional + T * c - price) / (price + (T - 1) * (notional + 0.5 * T * c));

            double impliedPrice = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, y);

            int nLoops = 0;
            while (Math.Abs(impliedPrice - price) > tolerance)
            {
                nLoops++;
                if (nLoops > maxLoops)
                    throw new Exception("Yield did not converge.");
                double dollarDur = DollarDuration(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, y);
                y = y - (impliedPrice - price) / dollarDur;
                impliedPrice = PresentValue(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, y);
            }
            return y;
        }
Example #38
0
 /// <summary>
 /// The yield calculated using the "book" value of the bond in place of the current market price.
 /// </summary>
 /// <param name="notional"></param>
 /// <param name="couponRate"></param>
 /// <param name="paymentFrequency"></param>
 /// <param name="evaluationDate"></param>
 /// <param name="paymentDates"></param>
 /// <param name="purchasePrice"></param>
 /// <param name="purchaseDate"></param>
 /// <returns></returns>
 public static double BookYield(double notional, double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double purchasePrice, DateTime purchaseDate)
 {
     DateTime maturityDate = paymentDates[paymentDates.Length - 1];
     double bv = BookValue(notional, purchasePrice, purchaseDate, evaluationDate, maturityDate);
     return Yield(notional, couponRate, paymentFrequency, evaluationDate, paymentDates, bv);
 }
Example #39
0
 public RightmoveProperty(int externalSourceId, int noOfBedrooms, PropertyType propertyType, string displayAddress,
                          decimal price, string priceCurrencyCode, PaymentFrequency priceFrequency, string postcode, Location location)
     : base(externalSourceId, noOfBedrooms, propertyType, displayAddress, price, priceCurrencyCode, priceFrequency, location)
 {
     Postcode = postcode;
 }
Example #40
0
        /// <summary>
        /// Returns the accrued interest for a security that pays periodic interest
        /// </summary>
        /// <param name="issue">The security's issue date.</param>
        /// <param name="first_interest">The security's first interest date.</param>
        /// <param name="settlement">The security's settlement date. The security settlement date is the date after the issue date when the security is traded to the buyer.</param>
        /// <param name="rate">The security's annual coupon rate.</param>
        /// <param name="par">The security's par value.</param>
        /// <param name="frequency">The number of coupon payments per year.</param>
        /// <param name="basis">The type of day count basis to use.</param>
        /// <param name="calc_method">A logical value that specifies the way to calculate the total accrued interest when the date of settlement is later than the date of first_interest. A value of TRUE (1) returns the total accrued interest from issue to settlement. A value of FALSE (0) returns the accrued interest from first_interest to settlement. If you do not enter the argument, it defaults to TRUE.</param>
        /// <returns>The accrued interest for a security that pays periodic interest.</returns>
        public static double ACCRINT(
            DateTime issue,
            DateTime first_interest,
            DateTime settlement,
            double rate,
            double par,
            PaymentFrequency frequency,
            DayCountBasis basis = DayCountBasis.US_NASD,
            bool calc_method = true)
        {
            if (rate <= 0) throw new ArgumentOutOfRangeException(nameof(rate), "'rate' must be greater than 0");
            if (par <= 0) throw new ArgumentOutOfRangeException(nameof(par), "'par' must be greater than 0");

            if (issue >= settlement)
                throw new ArgumentException("The issue date must be before the settlement date.", nameof(issue));


            throw new NotImplementedException();
            //return par * (rate / (double)frequency) * Functions.Sum(i => 0, 1, 2).Real;
        }
 public void AddPaymentFrequency(PaymentFrequency pf)
 {
     _context.PaymentFrequencies.Add(pf);
 }
Example #42
0
 /// <summary>
 /// -(d[present value] / d[yield]) x (1/[present value])
 /// </summary>
 public static double ModifiedDuration(double couponRate, PaymentFrequency paymentFrequency, DateTime evaluationDate, DateTime[] paymentDates, double yield)
 {
     //Note: Modified duration does not depend on the notional of the bond. Both dVdY and pv are proportional to the notional.
     //As long as we use the same notional in both formulas, the final result will be the same.
     double dVdY = DollarDuration(100.00, couponRate, paymentFrequency, evaluationDate, paymentDates, yield);
     double pv = PresentValue(100.00, couponRate, paymentFrequency, evaluationDate, paymentDates, yield);
     return -dVdY / pv;
 }
Example #43
0
 public Payment(string name, int dateOfMonth, double paymentAmount,string frequency, PaymentCategory category)
     : this(name, dateOfMonth, paymentAmount,category)
 {
     this._paymentFrequency = (PaymentFrequency) Enum.Parse(typeof(PaymentFrequency),frequency.ToString(),true);
 }
Example #44
0
 /// <summary>
 /// Különböző nagyságú törlesztőrészletek esetére
 /// </summary>
 /// <param name="instalments">Törlesztő részletek időben rendezett tömbje. A tömb első eleme az első törlesztő részlet, az utolsó eleme az utoljára fizetendő részlet.</param>
 /// <param name="paymentFrequency">Törlesztés gyakorisága. Pl.: heti,havi</param>
 public ThmCalculation(double[] instalments, PaymentFrequency paymentFrequency)
 {
     this.instalments      = instalments;
     this.paymentFrequency = paymentFrequency;
 }