PHPackages                             uruba/financalc - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. uruba/financalc

ActiveLibrary[Payment Processing](/categories/payments)

uruba/financalc
===============

A lightweight, simple and easy PHP library for calculating annuities (e.g., mortgages) according to various input data

v0.3.14(10y ago)303.5k4[3 issues](https://github.com/uruba/FinanCalc/issues)1UnlicensePHPPHP &gt;=5.4.0

Since Jun 15Pushed 9y ago5 watchersCompare

[ Source](https://github.com/uruba/FinanCalc)[ Packagist](https://packagist.org/packages/uruba/financalc)[ RSS](/packages/uruba-financalc/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (1)Versions (26)Used By (1)

FinanCalc
=========

[](#financalc)

A lightweight, simple and easy PHP library for calculating annuities (e.g., mortgages) and other financial instruments.

[![Composer package](https://camo.githubusercontent.com/7a356c4bce05b1ed3315db03a6bd809c193ad97574968316b8219888a3de0829/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f75727562612f66696e616e63616c632e737667)](https://packagist.org/packages/uruba/financalc)[![Build Status](https://camo.githubusercontent.com/e500bb3ab80e8820d9e96699669b4aef5bda932b82cfd4f3825850cfe39cc9a7/68747470733a2f2f7472617669732d63692e6f72672f75727562612f46696e616e43616c632e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/uruba/FinanCalc)[![Code Climate](https://camo.githubusercontent.com/a0d27226cc92585614de915c1d23bfbe7961a77301a75304f9b73ab53eb793c3/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f75727562612f46696e616e43616c632f6261646765732f6770612e737667)](https://codeclimate.com/github/uruba/FinanCalc)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/748ad261b89bf1db9ee50632ba8b8448488507eee70afb7f1112e886d0a0b549/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f75727562612f46696e616e43616c632f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/uruba/FinanCalc/?branch=master)[![codecov.io](https://camo.githubusercontent.com/7929096614211723ba4544d2a6c9999b61c283d79ba57ed7d62920d5c65b21da/687474703a2f2f636f6465636f762e696f2f6769746875622f75727562612f46696e616e43616c632f636f7665726167652e7376673f6272616e63683d6d6173746572)](http://codecov.io/github/uruba/FinanCalc?branch=master)

Requirements
------------

[](#requirements)

- PHP 5.4+
- BCMath module

Optional:

- PHPUnit (*for testing*)

Features
--------

[](#features)

- Simple interest calculator
- Simple discount calculator
- Annuity present and future value calculator
- Debt amortization calculator
- Bond fair value calculator
- Bond Yield-to-Maturity (YTM) calculator
- Bond duration calculator
- Dividend Discount Model (DDM) calculator
- Investment ratios calculator for stocks/shares

Much more to come – including calculators for discount securities *(NOTE: can now be calculated with help of the simple discount calculator)*, bond valuation, duration, stock pricing... Also looking into other optimizations and improvements. Current hot ideas:

- utilization of reflection in the getters of the calculators' result array for easier and less error-prone implementation of new calculator classes (this has already been tackled by the means of utilizing a helper array of property names)
- time functions for determining the exact dates of events pertaining to calculated instruments (implemented via a TimeSpan object and appropriate getter methods in applicable classes)
- ability to create unpopulated calculator objects (which can then be populated via setters), obviating the need to pass in all the data via constructor and thus providing more flexibility
- support for various day count conventions (this has been in consideration from the jump but it has not been implemented yet)
- better modularity with a straightforward and easy-to-understand workflow (~ a plugin system)
- deserializers (as a part of an I/O package)
- avoid perpetual usage of reflection by means of caching

> **Please bear in mind that this is an ALPHA version containing incomplete features. The codebase is prone to drastic changes during its way out of the alpha stage.**

Learning the ropes
------------------

[](#learning-the-ropes)

### Place the library files into your directory structure

[](#place-the-library-files-into-your-directory-structure)

Just copy all the files somewhere appropriate, like a dedicated "*vendor*" or "*lib*" directory (so that it doesn't make a mess out of your directory hierarchy). Nothing more is needed.

Alternatively, you can obtain the library as a package via Composer. It's hosted on [Packagist](https://packagist.org/packages/uruba/financalc)

### Include it in your project

[](#include-it-in-your-project)

The initialization is dead simple. Just include the **init.php** file in the main directory and you are good to go!

```
// replace the example Composer-bound path with yours
require_once 'vendor/uruba/financalc/init.php';
```

Or, if you are using Composer, you can use its `autoload.php` file instead.

```
require_once 'vendor/autoload.php';
```

### Instantiation

[](#instantiation)

You have two choices as to how to instantiate the appropriate class to get your results:

#### Factory methods

[](#factory-methods)

Since the library automatically keeps track of pre-defined factory methods (contained in the classes which are members of the namespace *FinanCalc\\Calculators\\Factories*), it's very easy and straightforward to utilize them.

From the main *FinanCalc* object (whose instance you get by calling its static method *getInstance()*) you have to call the *getFactory()* method, which takes in the name of the factory class as a parameter of type *string* (you can find all the included factory classes in the *src/calculators/factories* directory).

This method yields you the final calculator object on which you can call the appropriate methods to retrieve your results (as described in the next chapter) or change the input parameters via its setters.

```
use FinanCalc\FinanCalc;

...

$annuityCalculatorFactory = FinanCalc
    ::getInstance()
    ->getFactory('DebtAmortizatorFactory')
    ->newYearlyDebtAmortization(
        40000,
        6,
        0.12);
```

#### Direct instantiation

[](#direct-instantiation)

The second option is to instantiate the calculator class of your choice directly by calling its constructor with appropriate parameters (you can find all the included calculator classes in the *src/calculators* directory).

```
use FinanCalc\Calculators\DebtAmortizator;
use FinanCalc\Utils\Time\TimeUtils;

...

$annuityCalculatorDirect = new DebtAmortizator(
                                       40000,
                                       6,
                                       TimeSpan::asDuration(1),
                                       0.12);
```

### Getting results

[](#getting-results)

There are three ways to retrieve raw results of your calculations:

#### Directly accessible result object

[](#directly-accessible-result-object)

It's very simple to retrieve the results just by calling the appropriate getter methods. Every calculator class implementing the *CalculatorAbstract* has a getter method `getResult()`, which enables you to get an appropriate object representing the result of the calculation according to the data passed earlier to the constructor/factory method of a given calculator class *(this intermediate step is unneeded since the version 0.3.0, please update your code by removing the calls of the getResult() method if you're upgrading from any of the earlier versions)*.

We'll demonstrate the process on our *AnnuityCalculator* – step by step, day by day:

1. step is to instantiate the appropriate calculator class, either by constructor or by a factory method (refer to the previous chapter for more information)

    ```
    use FinanCalc\FinanCalc;

    ...

    // Instantiation by a factory method
    // –
    // in our case we calculate a yearly-compounded annuity
    // with a duration of 5 periods (here years),
    // 100000 money units paid out per period
    // and a compounding interest rate of 0.15 (i.e., 15%)
    $annuityCalculatorObject = FinanCalc
                                    ::getInstance()
                                    ->getFactory('AnnuityCalculatorFactory')
                                    ->newYearlyAnnuity(
                                        100000,
                                        5,
                                        0.15);
    ```
2. step is to get the desired value by exploiting the appropriate getter methods (for a detailed list of available gettter methods please refer to the **Reference** chapter)

    ```
    // get the present value of the annuity in arrears
    // (as a string)
    $PV = $annuityCalculatorObject->getPresentValue(
                        new AnnuityPaymentTypes(AnnuityPaymentTypes::IN_ARREARS)
                    );
    // get the future value of the annuity in arrears
    // (as a string)
    $FV = $annuityCalculatorObject->getFutureValue(
                        new AnnuityPaymentTypes(AnnuityPaymentTypes::IN_ARREARS)
                    );
    ```

Therewith the process is concluded and you can now use the obtained results in any way you see fit.

#### Serialized output

[](#serialized-output)

If you want to get the marshaled object representation of the result, you can utilize the built-in method `getSerializedResult(SerializerInterface $serializer)` which is implemented in the base abstract class, from which every calculator class inherits. You just have to pass a serializer object (i.e., any object of a class which implements the *SerializerInterface* interface) to it.

We'll again demonstrate the process on our venerable *AnnuityCalculator* using the *XMLSerializer*:

1. step is the same – instantiate the appropriate calculator class, either through the constructor or via a factory method (refer to the previous chapter for more information)

    ```
    use FinanCalc\FinanCalc;
    use FinanCalc\Utils\Serializers\XMLSerializer;

    ...

    // Instantiation by a factory method
    // –
    // in our case we calculate a yearly-compounded annuity
    // with a duration of 5 periods (here years),
    // 100000 money units paid out per period
    // and a compounding interest rate of 0.15 (i.e., 15%)
    $annuityCalculatorObject = FinanCalc
                                    ::getInstance()
                                    ->getFactory('AnnuityCalculatorFactory')
                                    ->newYearlyAnnuity(
                                        100000,
                                        5,
                                        0.15);
    ```
2. step is to get the serialized result object

    ```
    $result = $annuityCalculatorObject->getSerializedResult(new XMLSerializer());
    ```
3. now we have a comprehensive representation of the result object in the target format. In our example it looks like this:

    ```

      100000
      5
      0.15

        1.00000000
        12.00000000
        360.00000000

        385497.83
        335215.53

        775373.79
        674238.12

    ```

NOTE: The name of the "root" element in the XML output can be customized by the config property `serializers_root_elem_name`. In the future, it will be automatically assigned according to the type of the result object.

You can easily create your own serializer classes by implementing the *SerializerInterface*. A minimal example of a serializer (in this particular demonstrative case with YAML-formatted output) is here – [FinanCalc-YAMLSerializer](https://github.com/uruba/FinanCalc-YAMLSerializer).

#### Array

[](#array)

You can also get a result's representation as an array. This representation is primarily used to pass the calculator object's properties to a serializer. The output should therefore be equivalent except for the semantic representation. It also enables you to easily implement your own serializer classes, which are then passed the array as their parameter.

Let's demonstrate the process for the last time on our *AnnuityCalculator*:

1. step is the same – instantiate the appropriate calculator class, either through the constructor or via a factory method (refer to the previous chapter for more information)

    ```
    use FinanCalc\FinanCalc;

    ...

    // Instantiation by a factory method
    // –
    // in our case we calculate a yearly-compounded annuity
    // with a duration of 5 periods (here years),
    // 100000 money units paid out per period
    // and a compounding interest rate of 0.15 (i.e., 15%)
    $annuityCalculatorObject = FinanCalc
                                    ::getInstance()
                                    ->getFactory('AnnuityCalculatorFactory')
                                    ->newYearlyAnnuity(
                                        100000,
                                        5,
                                        0.15);
    ```
2. step is to get the result array

    ```
    $result = $annuityCalculatorObject->getResultAsArray();
    ```
3. the result array will look like this (the "var\_export" representation):

    ```
    array (
      'annuitySinglePaymentAmount' => '100000',
      'annuityNoOfCompoundingPeriods' => '5',
      'annuityInterest' => '0.15',
      'annuityPeriodLength' =>
      array (
        'years' => '1.00000000',
        'months' => '12.00000000',
        'days' => '360.00000000',
      ),
      'annuityPresentValue' =>
      array (
        'in_advance' => '385497.83',
        'in_arrears' => '335215.53',
      ),
      'annuityFutureValue' =>
      array (
        'in_advance' => '775373.79',
        'in_arrears' => '674238.12',
      ),
    )
    ```

### Configuration

[](#configuration)

The configuration capabilities are currently very limited so there's next to nothing to tinker with.

The default configuration values are currently to be found in the "*constants/Defaults.php*" file, but there will be a possibility to use an easily accessible JSON (or PHP) configuration file in the future.

### Tests

[](#tests)

The library includes a "*test*" subdirectory which contains all the basic tests. For your peace of mind, feel free to give them a run on your setup (provided that you have PHPUnit good and ready) and ensure that everything checks out.

The test-case examples are adapted directly from the lectures of a university course "*[4ST608 - Introduction to Financial and Insurance Mathematics](https://isis.vse.cz/katalog/syllabus.pl?predmet=62055;lang=en)*" taught at the University of Economics in Prague by Prof. RNDr. Tomáš Cipra, DrSc., to whom goes all the credit.

Reference
---------

[](#reference)

Here you can find the documentation for each of the vanilla calculator types.

The implicit type of setters'/constructors' arguments as well as getters' returned values is String if not stated otherwise.

### [AnnuityCalculator](src/Calculators/AnnuityCalculator.php)

[](#annuitycalculator)

namespace `FinanCalc\Calculators`

- **\_\_construct($annuitySinglePaymentAmount, $annuityNoOfCompoundingPeriods, TimeSpan $annuityPeriodLength, $annuityInterest)**
    - *$annuitySinglePaymentAmount* = **'K'** – the amount of each individual payment (number greater than zero)
    - *$annuityNoOfCompoundingPeriods* = **'n'** – the number of periods pertaining to the interest compounding; if 'n = 0', the annuity is considered a perpetuity
    - *$annuityPeriodLength* = the length of a single period as a TimeSpan object
    - *$annuityInterest* = **'i'** – the interest rate *per a single payment period* by which the unpaid balance is multiplied (i.e., a decimal number typically lower than 1 and greater than 0)

##### Setters

[](#setters)

- **setAnnuitySinglePaymentAmount($annuitySinglePaymentAmount)** – sets K
- **setAnnuityNoOfCompoundingPeriods($annuityNoOfCompoundingPeriods)** – sets n
- **setAnnuityPeriodLength(TimeSpan $annuityPeriodLength)** – sets the length of each compounding period in days
- **setAnnuityInterest($annuityInterest)** – sets i

##### Getters

[](#getters)

- **getAnnuitySinglePaymentAmount()** – gets K
- **getAnnuityNoOfCompoundingPeriods()** – gets n
- **getAnnuityPeriodLength()** – gets the length of each compounding period as a TimeSpan object
- **getAnnuityPeriodLengthInYears()** – gets the length of each compounding period in years
- **getAnnuityPeriodLengthInMonths()** – gets the length of each compounding period in months
- **getAnnuityPeriodLengthInDays()** – gets the length of each compounding period in days
- **getAnnuityInterest()** – gets i
- **getAnnuityLengthInYears()** – gets the length of the annuity in years
- **getAnnuityLengthInMonths()** – gets the length of the annuity in months
- **getAnnuityLengthInDays()** – gets the length of the annuity in days
- **getAnnuityEndDate(DateTime $startDate)** – gets the ending date of the annuity as a DateTime object, based on the starting date passed in as a parameter
- **getAnnuityPresentValue(AnnuityPaymentTypes $annuityType)** – gets the present value of the annuity
    - *AnuityPaymentTypes $annuityType* = determines whether the payments are made either at the beginning or the end of each of the annuity's periods \[*optional for perpetuities*\]
- **getAnnuityPresentValueInAdvance()** – shorthand for *getAnnuityPresentValue(new AnnuityPaymentTypes(AnnuityPaymentTypes::IN\_ADVANCE))*
- **getAnnuityPresentValueInArrears()** – shorthand for *getAnnuityPresentValue(new AnnuityPaymentTypes(AnnuityPaymentTypes::IN\_ARREARS))*
- **getAnnuityFutureValue(AnnuityPaymentTypes $annuityType)** – gets the future value of the annuity
    - *AnuityPaymentTypes $annuityType* = determines whether the payments are made either at the beginning or the end of each of the annuity's periods \[*optional for perpetuities*\]
- **getAnnuityFutureValueInAdvance()** – shorthand for *getAnnuityFutureValue(new AnnuityPaymentTypes(AnnuityPaymentTypes::IN\_ADVANCE))*
- **getAnnuityFutureValueInArrears()** – shorthand for *getAnnuityFutureValue(new AnnuityPaymentTypes(AnnuityPaymentTypes::IN\_ARREARS))*
- **getAnnuityValue(AnnuityPaymentTypes $annuityPaymentType, AnnuityValueTypes $annuityValueType)** – gets either the present or the future value of the annuity
    - *AnuityPaymentTypes $annuityPaymentType* = determines whether the payments are made either at the beginning or the end of each of the annuity's periods \[*optional for perpetuities*\]
    - *AnuityValueTypes $annuityValueType* = determines whether the result is the present or the future value of the annuity
- **getResultAsArray(array $propResultArray = null)** – gets the array of the pertinent property values which you can specify (e.g., if you want only a specified subset thereof) via the optional argument
- **getSerializedResult(SerializerInterface $serializer)** – gets the serialized result, according to the passed SerializerInterface object

#### [AnnuityCalculatorFactory](src/Calculators/Factories/AnnuityCalculatorFactory.php) (*AnnuityCalculator's factory object*)

[](#annuitycalculatorfactory-annuitycalculators-factory-object)

namespace `FinanCalc\Calculators\Factories`

- **newYearlyAnnuity($annuitySinglePaymentAmount, $annuityNoOfCompoundingPeriods, $annuityInterest)**
- **newMonthlyAnnuity($annuitySinglePaymentAmount, $annuityNoOfCompoundingPeriods, $annuityInterest)**
- **newDailyAnnuity($annuitySinglePaymentAmount, $annuityNoOfCompoundingPeriods, $annuityInterest)**
- **newPerpetuity($annuitySinglePaymentAmount, $annuityInterest)**

#### [AnnuityPaymentTypes](src/Constants/AnnuityPaymentTypes.php)

[](#annuitypaymenttypes)

namespace `FinanCalc\Constants`

- *IN\_ADVANCE* = 1
- *IN\_ARREARS* = 2

#### [AnnuityValueTypes](src/Constants/AnnuityValueTypes.php)

[](#annuityvaluetypes)

namespace `FinanCalc\Constants`

- *PRESENT\_VALUE* = 1
- *FUTURE\_VALUE* = 2

---

### [DebtAmortizator](src/Calculators/DebtAmortizator.php)

[](#debtamortizator)

namespace `FinanCalc\Calculators`

- **\_\_construct($debtPrincipal, $debtNoOfCompoundingPeriods, TimeSpan $debtPeriodLength, $debtInterest)**
    - *$debtPrincipal* = **'PV'** – the principal of the debt (number greater than zero)
    - *$debtNoOfCompoundingPeriods* = **'n'** – the count of the debt's compounding periods (number greater than zero)
    - *$debtPeriodLength* = the length of each of the debt's compounding periods as a TimeSpan object
    - *$debtInterest* = **'i'** – the interest per a compounding period, by which the outstanding balance is multiplied (i.e., a decimal number typically lower than 1 and greater than 0)

##### Setters

[](#setters-1)

- **setDebtPrincipal($debtPrincipal)** – sets PV
- **setDebtNoOfCompoundingPeriods($debtNoOfCompoundingPeriods)** – sets n
- **setDebtPeriodLength(TimeSpan $debtPeriodLength)** – sets the length of each compounding period
- **setDebtInterest($debtInterest)** – sets i

##### Getters

[](#getters-1)

- **getDebtDiscountFactor()** – gets the value of the debt's discount factor = **'v'**
- **getDebtSingleRepayment()** – gets the amount of a single repayment = **'K'**
- **getDebtPrincipal()** – gets PV
- **getDebtNoOfCompoundingPeriods()** – gets n
- **getDebtPeriodLength()** – gets the length of each compounding period as a TimeSpan object
- **getDebtPeriodLengthInYears()** – gets the length of each compounding period in years
- **getDebtPeriodLengthInMonths()** – gets the length of each compounding period in months
- **getDebtPeriodLengthInDays()** – gets the length of each compounding period in days
- **getDebtLengthInYears()** – gets the length of the debt in years
- **getDebtLengthInMonths()** – gets the length of the debt in months
- **getDebtLengthInDays()** – gets the length of the debt in days
- **getDebtEndDate(DateTime $startDate)** – gets the ending date of the debt as a DateTime object, based on the starting date passed in as a parameter
- **getDebtInterest()** – gets i
- **getDebtRepayments()** – gets the **array of RepaymentInstance** objects representing all the individual payments within the debt comprised into an array
- **getDebtRepaymentsAsArrays()** – gets the **array of associative arrays** (i.e., an array of RepaymentInstances converted to arrays) representing all the individual payments within the debt
- **getResultAsArray(array $propResultArray = null)** – gets the array of the pertinent property values which you can specify (e.g., if you want only a specified subset thereof) via the optional argument
- **getSerializedResult(SerializerInterface $serializer)** – gets the serialized result, according to the passed SerializerInterface object

#### [DebtAmortizatorFactory](src/Calculators/Factories/DebtAmortizatorFactory.php) (*DebtAmortizator's factory object*)

[](#debtamortizatorfactory-debtamortizators-factory-object)

namespace `FinanCalc\Calculators\Factories`

- **newYearlyDebtAmortization($debtPrincipal, $debtNoOfPeriods, $debtInterest)**
- **newMonthlyDebtAmortization($debtPrincipal, $debtNoOfPeriods, $debtInterest)**
- **newDailyDebtAmortization($debtPrincipal, $debtNoOfPeriods, $debtInterest)**
- **newDebtAmortizationCustomPeriodLength($debtPrincipal, $debtNoOfPeriods, $debtInterest, TimeSpan $debtSinglePeriodLength)**

#### [RepaymentInstance](src/Calculators/DebtAmortizator.php#L324)

[](#repaymentinstance)

namespace `FinanCalc\Calculators\DebtAmortizator`

- **getPrincipalAmount()** – gets the amount of the debt's principal covered by this single repayment
- **getInterestAmount()** – gets the amount of the debt's interest covered by this single repayment
- **getTotalAmount()** – gets the total amount covered by this individual repayment (both the "principal" and "interest" part)

---

### [BondFairValueCalculator](src/Calculators/BondFairValueCalculator.php)

[](#bondfairvaluecalculator)

namespace `FinanCalc\Calculators`

- **\_\_construct($bondFaceValue, $bondAnnualCouponRate, $bondVIR, $bondYearsToMaturity, $bondPaymentFrequency = 1)**
    - *$bondFaceValue* = **'F'** – the face value of the bond (number greater than zero)
    - *$bondAnnualCouponRate* = **'c'** – the annual coupon rate of the bond (i.e., a decimal number typically lower than 1 and greater than 0)
    - *$bondVIR* = **'i' or 'VIR'** – the valuation interest rate of the bond (i.e., a decimal number typically lower than 1 and greater than 0)
    - *bondYearsToMaturity* = the number of years to the maturity of the bond (number greater than zero, can be a decimal number)
    - *bondPaymentFrequency* = the frequency of bond payments (expressed in a divisor of 12 months ~ 1 year); e.g.: divisor 2 means semi-annual payments

##### Setters

[](#setters-2)

- **setBondFaceValue($bondFaceValue)** – sets F
- **setBondAnnualCouponRate($bondAnnualCouponRate)** – sets c
- **setBondVIR($bondVIR)** – sets i/VIR
- **setBondYearsToMaturity($bondYearsToMaturity)** – sets the number of years to the maturity of the bond
- **setBondPaymentFrequency($bondPaymentFrequency)** – sets the frequency of bond payments

##### Getters

[](#getters-2)

- **getBondFaceValue()** – gets F
- **getBondAnnualCouponRate()** – gets c
- **getBondVIR()** – gets i/VIR
- **getBondYearsToMaturity()** – gets the number of years to the maturity of the bond
- **getBondPaymentFrequency()** – gets the frequency of bond payments
- **getBondNoOfPayments()** – gets the total number of payments during the lifespan of the bond
- **getBondFairValue()** – gets the fair value of the bond \[calculated as present value of future cashflows corresponding to the bond by means of the valuation interest rate\]
- **getResultAsArray(array $propResultArray = null)** – gets the array of the pertinent property values which you can specify (e.g., if you want only a specified subset thereof) via the optional argument
- **getSerializedResult(SerializerInterface $serializer)** – gets the serialized result, according to the passed SerializerInterface object

#### [BondFairValueCalculatorFactory](src/Calculators/Factories/BondFairValueCalculatorFactory.php) (*BondFairValueCalculator's factory object*)

[](#bondfairvaluecalculatorfactory-bondfairvaluecalculators-factory-object)

namespace `FinanCalc\Calculators\Factories`

- **newAnnualCouponsBond($bondFaceValue, $bondAnnualCouponRate, $bondVIR, $bondYearsToMaturity)**
- **newSemiAnnualCouponsBond($bondFaceValue, $bondAnnualCouponRate, $bondVIR, $bondYearsToMaturity)**
- **newQuarterlyCouponsBond($bondFaceValue, $bondAnnualCouponRate, $bondVIR, $bondYearsToMaturity)**
- **newMonthlyCouponsBond($bondFaceValue, $bondAnnualCouponRate, $bondVIR, $bondYearsToMaturity)**
- **newCustomCouponFrequencyBond($bondFaceValue, $bondAnnualCouponRate, $bondVIR, $bondYearsToMaturity, $bondPaymentFrequency)**

---

### [BondYTMCalculator](src/Calculators/BondYTMCalculator.php)

[](#bondytmcalculator)

namespace `FinanCalc\Calculators`

- **\_\_construct($bondFaceValue, $bondMarketValue, $bondAnnualCouponRate, $bondYearsToMaturity, $bondPaymentFrequency = 1)**
    - *$bondFaceValue* = **'F'** – the face value of the bond (number greater than zero)
    - *$bondMarketValue* = **'P'** – the market value (i.e., price) of the bond (number greater than zero)
    - *$bondAnnualCouponRate* = **'c'** – the annual coupon rate of the bond (i.e., a decimal number typically lower than 1 and greater than 0)
    - *bondYearsToMaturity* = the number of years to the maturity of the bond (number greater than zero, can be a decimal number)
    - *bondPaymentFrequency* = the frequency of bond payments (expressed in a divisor of 12 months ~ 1 year); e.g.: divisor 2 means semi-annual payments

##### Setters

[](#setters-3)

- **setBondFaceValue($bondFaceValue)** – sets F
- **setBondMarketValue($bondMarketValue)** – sets the market value of the bond
- **setBondAnnualCouponRate($bondAnnualCouponRate)** – sets c
- **setBondYearsToMaturity($bondYearsToMaturity)** – sets the number of years to the maturity of the bond
- **setBondPaymentFrequency($bondPaymentFrequency)** – sets the frequency of bond payments

##### Getters

[](#getters-3)

- **getBondFaceValue()** – gets F
- **getBondMarketValue()** – gets the market value of the bond
- **getBondAnnualCouponRate()** – gets c
- **getBondYearsToMaturity()** – gets the number of years to the maturity of the bond
- **getBondPaymentFrequency()** – gets the frequency of bond payments
- **getBondNoOfPayments()** – gets the total number of payments during the lifespan of the bond
- **getApproxBondYTM()** – gets the approximate value of the bond's yield to maturity in the form of a decimal number \[it is the internal rate of return of the bond\]
- **getResultAsArray(array $propResultArray = null)** – gets the array of the pertinent property values which you can specify (e.g., if you want only a specified subset thereof) via the optional argument
- **getSerializedResult(SerializerInterface $serializer)** – gets the serialized result, according to the passed SerializerInterface object

#### [BondYTMCalculatorFactory](src/Calculators/Factories/BondYTMCalculatorFactory.php) (*BondYTMCalculator's factory object*)

[](#bondytmcalculatorfactory-bondytmcalculators-factory-object)

namespace `FinanCalc\Calculators\Factories`

- **newAnnualCouponsBond($bondFaceValue, $bondMarketValue, $bondAnnualCouponRate, $bondYearsToMaturity)**
- **newSemiAnnualCouponsBond($bondFaceValue, $bondMarketValue, $bondAnnualCouponRate, $bondYearsToMaturity)**
- **newQuarterlyCouponsBond($bondFaceValue, $bondMarketValue, $bondAnnualCouponRate, $bondYearsToMaturity)**
- **newMonthlyCouponsBond($bondFaceValue, $bondMarketValue, $bondAnnualCouponRate, $bondYearsToMaturity)**
- **newCustomCouponFrequencyBond($bondFaceValue, $bondMarketValue, $bondAnnualCouponRate, $bondYearsToMaturity, $bondPaymentFrequency)**

---

### [BondDurationCalculator](src/Calculators/BondDurationCalculator.php)

[](#bonddurationcalculator)

namespace `FinanCalc\Calculators`

- **\_\_construct($bondFaceValue, $bondAnnualCouponRate, $bondAnnualYield, $bondYearsToMaturity, $bondPaymentFrequency = 1)**
    - *$bondFaceValue* = **'F'** – the face value of the bond (number greater than zero)
    - *$bondAnnualCouponRate* = **'c'** – the annual coupon rate of the bond (i.e., a decimal number typically lower than 1 and greater than 0)
    - *$bondAnnualYield* = the annual yield of the bond (calculated as an interest rate divided by the bond's' value)
    - *bondYearsToMaturity* = the number of years to the maturity of the bond (number greater than zero, can be a decimal number)
    - *bondPaymentFrequency* = the frequency of bond payments (expressed in a divisor of 12 months ~ 1 year); e.g.: divisor 2 means semi-annual payments

##### Setters

[](#setters-4)

- **setBondFaceValue($bondFaceValue)** – sets F
- **setBondAnnualCouponRate($bondAnnualCouponRate)** – sets c
- **setBondAnnualYield($bondAnnualYield)** – sets the annual yield of the bond
- **setBondYearsToMaturity($bondYearsToMaturity)** – sets the number of years to the maturity of the bond
- **setBondPaymentFrequency($bondPaymentFrequency)** – sets the frequency of bond payments

##### Getters

[](#getters-4)

- **getBondFaceValue()** – gets F
- **getBondAnnualCouponRate()** – gets c
- **getBondAnnualYield()** – gets the annual yield of the bond
- **getBondYieldPerPaymentPeriod()** – gets the yield of the bond per a payment period
- **getBondYearsToMaturity()** – gets the number of years to the maturity of the bond
- **getBondPaymentFrequency()** – gets the frequency of bond payments
- **getBondNoOfPayments()** – gets the total number of payments during the lifespan of the bond
- **getBondNominalCashFlows()** – gets an array of the bond's nominal cash flows (coupons; in the last payment = coupon + face value)
- **getBondDiscountedCashFlows()** – gets an array of the bond's discounted cash flows (nominal cash flows which are discounted by the means of the bond's yield per period)
- **getBondPresentValue()** – gets the present value of the bond which is represented by sum of all the bond's discounted cash flows (i.e., all the array members returned by the method getBondDiscountedCashFlows() are summed up)
- **getBondDuration()** – gets the bond's duration in years (can be a decimal number)
- **getResultAsArray(array $propResultArray = null)** – gets the array of the pertinent property values which you can specify (e.g., if you want only a specified subset thereof) via the optional argument
- **getSerializedResult(SerializerInterface $serializer)** – gets the serialized result, according to the passed SerializerInterface object

#### [BondDurationCalculatorFactory](src/Calculators/Factories/BondDurationCalculatorFactory.php) (*BondDurationCalculator's factory object*)

[](#bonddurationcalculatorfactory-bonddurationcalculators-factory-object)

namespace `FinanCalc\Calculators\Factories`

- **newAnnualCouponsBond($bondFaceValue, $bondAnnualCouponRate, $bondAnnualYield, $bondYearsToMaturity)**
- **newSemiAnnualCouponsBond($bondFaceValue, $bondAnnualCouponRate, $bondAnnualYield, $bondYearsToMaturity)**
- **newQuarterlyCouponsBond($bondFaceValue, $bondAnnualCouponRate, $bondAnnualYield, $bondYearsToMaturity)**
- **newMonthlyCouponsBond($bondFaceValue, $bondAnnualCouponRate, $bondAnnualYield, $bondYearsToMaturity)**
- **newCustomCouponFrequencyBond($bondFaceValue, $bondAnnualCouponRate, $bondAnnualYield, $bondYearsToMaturity, $bondPaymentFrequency)**

---

### [SimpleDiscountCalculator](src/Calculators/SimpleDiscountCalculator.php)

[](#simplediscountcalculator)

namespace `FinanCalc\Calculators`

- **\_\_construct($amountDue, $annualDiscountRate, TimeSpan $time)**
    - *$principal* = **'S'** – the amount due
    - *$annualInterestRate* = **'d'** – the annual discount rate (i.e., a decimal number typically lower than 1 and greater than 0)
    - *$time* = (converted to years) **'t'** – the total time as a TimeSpan object

##### Setters

[](#setters-5)

- **setAmountDue($amountDue)** – sets S
- **setAnnualDiscountRate($annualDiscountRate)** – sets d
- **setTime(TimeSpan $time)** – sets the total time

##### Getters

[](#getters-5)

- **getAmountDue()** – gets S
- **getAnnualDiscountRate()** – gets d
- **getTime()** – gets the total time as a TimeSpan object
- **getTimeInYears()** – gets the total time in years
- **getTimeInMonths()** – gets the total time in months
- **getTimeInDays()** – gets the total time in days
- **getDiscountAmount()** – gets the discount amount ('D')

#### [SimpleDiscountCalculatorFactory](src/Calculators/Factories/SimpleDiscountCalculatorFactory.php) (*SimpleDiscountCalculator's factory object*)

[](#simplediscountcalculatorfactory-simplediscountcalculators-factory-object)

namespace `FinanCalc\Calculators\Factories`

- **newSimpleDiscount($amountDue, $annualDiscountRate, TimeSpan $time)**

---

### [SimpleInterestCalculator](src/Calculators/SimpleInterestCalculator.php)

[](#simpleinterestcalculator)

namespace `FinanCalc\Calculators`

- **\_\_construct($principal, $annualInterestRate, TimeSpan $time)**
    - *$principal* = **'P'** – the amount of principal
    - *$annualInterestRate* = **'i'** – the annual interest rate (i.e., a decimal number typically lower than 1 and greater than 0)
    - *$time* = (converted to years) **'t'** – the total time as a TimeSpan object

##### Setters

[](#setters-6)

- **setPrincipal($principal)** – sets P
- **setAnnualInterestRate($annualInterestRate)** – sets i
- **setTime(TimeSpan $time)** – sets the total time

##### Getters

[](#getters-6)

- **getPrincipal()** – gets P
- **getAnnualInterestRate()** – gets i
- **getTime()** – gets the total time as a TimeSpan object
- **getTimeInYears()** – gets the total time in years
- **getTimeInMonths()** – gets the total time in months
- **getTimeInDays()** – gets the total time in days
- **getInterestNumber()** – gets the interest number ('IN')
- **getInterestDivisor()** – gets the interest divisor ('ID')
- **getInterestAmount()** – gets the interest amount ('n')

#### [SimpleInterestCalculatorFactory](src/Calculators/Factories/SimpleInterestCalculatorFactory.php) (*SimpleInterestCalculator's factory object*)

[](#simpleinterestcalculatorfactory-simpleinterestcalculators-factory-object)

namespace `FinanCalc\Calculators\Factories`

- **newSimpleInterest($principal, $annualInterestRate, TimeSpan $time)**

---

### [StockDividendDiscountModelCalculator](src/Calculators/StockDividendDiscountModelCalculator.php)

[](#stockdividenddiscountmodelcalculator)

namespace `FinanCalc\Calculators`

- **\_\_construct(StockDDMTypes $dividendDiscountModelType, $stockVIR, $stockAnnualDividendValue, $stockAnnualDividendsGrowth = null)**
    - *$dividendDiscountModelType* = the type of the dividend discount model according to which the result will be calculated (value of the type *StockDDMTypes*)
    - *$stockVIR* = **'i'** – the stock's valuation interest rate
    - *$stockAnnualDividendsValue* = **'D'** – the absolute value of the stock's annual dividends
    - *$stockAnnualDividendsGrowth* = **'g'** – the rate by which the stock's annual dividends are annually multiplied (i.e., a decimal number between 0 and 1) \[*this value applies only to the multiple growth dividend discount model*\]

#### Setters

[](#setters-7)

- **setDividendDiscountModelType(StockDDMTypes $dividendDiscountModelType)** – sets the type of the dividend discount model
- **setStockVIR($stockVIR)** – sets i
- **setStockAnnualDividendsValue($stockAnnualDividendsValue)** – sets D
- **setStockAnnualDividendsGrowth($stockAnnualDividendsGrowth)** – sets g

#### Getters

[](#getters-7)

- **getDividendDiscountModelType()** – gets the type of the dividend discount model
- **getStockVIR()** – gets i
- **getStockAnnualDividendsValue()** – gets D
- **getStockAnnualDividendsGrowth()** – gets g
- **getStockPresentValue()** – gets the present (~ fair) value of the stock
- **getResultAsArray(array $propResultArray = null)** – gets the array of the pertinent property values which you can specify (e.g., if you want only a specified subset thereof) via the optional argument
- **getSerializedResult(SerializerInterface $serializer)** – gets the serialized result, according to the passed SerializerInterface object

#### [StockDividendDiscountModelCalculatorFactory](src/Calculators/Factories/StockDividendDiscountModelCalculatorFactory.php) (*StockDividendDiscountModelCalculator's factory object*)

[](#stockdividenddiscountmodelcalculatorfactory-stockdividenddiscountmodelcalculators-factory-object)

namespace `FinanCalc\Calculators\Factories`

- **newZeroGrowthDividendDiscountModel($stockVIR, $stockAnnualDividendValue)**
- **newMultipleGrowthDividendDiscountModel($stockVIR, $stockAnnualDividendValue, $stockAnnualDividendsGrowth)**

#### [StockDDMTypes](src/Constants/StockDDMTypes.php)

[](#stockddmtypes)

namespace `FinanCalc\Constants`

- *ZERO\_GROWTH* = 1
- *MULTIPLE\_GROWTH* = 2

---

### [StockInvestmentRatiosCalculator](src/Calculators/StockInvestmentRatiosCalculator.php)

[](#stockinvestmentratioscalculator)

namespace `FinanCalc\Calculators`

- **\_\_construct($totalDividends, $earningsAfterTaxes, $noOfStocks)**
    - *$totalDividends* = the sum of dividends per a period
    - *$earningsAfterTaxes* = the amount earned after taxes
    - *$noOfStocks* = the number of stocks (total if constant, average if fluctuating)

#### Setters

[](#setters-8)

- **setTotalDividends($totalDividends)** – sets the sum of dividends per a period
- **setEarningsAfterTaxes($earningsAfterTaxes)** – sets the amount earned after taxes
- **setNoOfStocks($noOfStocks)** – sets the number of stocks

#### Getters

[](#getters-8)

- **getTotalDividends()** – gets the sum of dividends per a period
- **getEarningsAfterTaxes()** – gets the amount earned after taxes
- **getNoOfStocks()** – gets the number of stocks
- **getDividendPerStock()** – gets the dividend per stock (DPS) value
- **getEarningsPerStock()** – gets the earning per stock (EPS) value
- **getPayoutRatio()** – gets the payout ratio (also referred to as "dividend payout ratio")
- **getDividendRatio()** – gets the dividend ratio (the payout ratio to the power of -1)
- **getRetentionRatio()** – gets the retention ("plowback") ratio
- **getResultAsArray(array $propResultArray = null)** – gets the array of the pertinent property values which you can specify (e.g., if you want only a specified subset thereof) via the optional argument
- **getSerializedResult(SerializerInterface $serializer)** – gets the serialized result, according to the passed SerializerInterface object

#### [StockInvestmentRatiosCalculatorFactory](src/Calculators/Factories/StockInvestmentRatiosCalculatorFactory.php) (*StockInvestmentRatiosCalculator's factory object*)

[](#stockinvestmentratioscalculatorfactory-stockinvestmentratioscalculators-factory-object)

namespace `FinanCalc\Calculators\Factories`

- **newCustomStocks($totalDividends, $earningAfterTaxes, $noOfStocks)**

---

Time values are primarily represented by individual instances of `TimeSpan` class. Its concept is (roughly) similar to [a structure of the same (unqualified) name in .NET Framework](https://msdn.microsoft.com/en-gb/library/system.timespan%28v=vs.110%29.aspx).

### [TimeSpan](src/Utils/Time/TimeSpan.php)

[](#timespan)

namespace `FinanCalc\Utils\Time`

To initialize the class, you should use one of its three static factory methods (the default constructor is declared as private and it is not advised to circumvent this measure).

- **asDuration($years, $months = 0, $days = 0)** – simple (rounded) time duration defined by numerical values of its time components
- **asDurationWithStartDate(DateTime $startDate, $years, $months = 0, $days = 0)** – simple (rounded) time duration defined by numerical values of its time components, keeping track of its starting date
- **asInterval(DateTime $startDate, DateTime $endDate)** – precise representation of a time duration specified by its starting and ending date

#### Setters

[](#setters-9)

- **setStartDate(DateTime $startDate)** – sets or re-sets the starting date
- **setEndDate(DateTime $endDate)** – sets or re-sets the ending date
- **clearStartEndDate()** – sets both the starting and ending date to null

#### Getters

[](#getters-9)

- **getStartDate()** – gets the starting date
- **getEndDate()** – gets the ending date
- **getYearsComponent()** – gets the "year" component of the underlying `DateInterval` object
- **getMonthsComponent()** – gets the "month" component of the underlying `DateInterval` object
- **getDaysComponent()** – gets the "day" component of the underlying `DateInterval` object
- **toYears()** – converts the entire time duration (i.e., accounting for all its components – year, month and day) to years
- **toMonths()** – converts the entire time duration (i.e., accounting for all its components – year, month and day) to months
- **toDays()** – converts the entire time duration (i.e., accounting for all its components – year, month and day) to days

---

If you ever need a convenient way to convert time units, feel free to make use of static methods of the `TimeUtils` class which is built for this purpose (it's also used internally within the library). It also takes into account the day count convention that's currently set in the library's configuration (i.e., the number of days in a year).

### [TimeUtils](src/Utils/Time/TimeUtils.php)

[](#timeutils)

namespace `FinanCalc\Utils\Time`

#### Getters

[](#getters-10)

- **getYearsFromDays($numberOfDays)** – converts the given number of days to years (taking into account the day count convention currently set in the configuration)
- **getYearsFromMonths($numberOfMonths)** – converts the given number of months to years
- **getYearsFromYears($numberOfYears)** – converts the given number of years to years (just a proxy method)
- **getMonthsFromDays($numberOfDays)** – converts the given number of days to months (taking into account the day count convention currently set in the configuration)
- **getMonthsFromMonths($numberOfMonths)** – converts the given number of months to months (just a proxy method)
- **getMonthsFromYears($numberOfYears)** – converts the given number of years to months
- **getDaysFromDays($numberOfDays)** – converts the given number of days to days (just a proxy method)
- **getDaysFromMonths($numberOfMonths)** – converts the given number of months to days (taking into account the day count convention currently set in the configuration)
- **getDaysFromYears($numberOfYears)** – converts the given number of years to days (taking into account the day count convention currently set in the configuration)
- **getCurrentDayCountConvention()** – gets the current day count convention
- **isDayCountConventionValid($dayCountConvention)** – checks whether a day count convention (passed in by the argument) is a valid day count convention

DISCLAIMER
----------

[](#disclaimer)

You are free to use/modify/extend the library as you please - for it to serve your purpose. As per the (un)license, the software is provided as is and the original author cannot be held liable for any losses/damages directly or indirectly resulting from using thereof. Attribution is welcome, but certainly not required.

**NOTE**The library is currently work-in-progress and it is certain that new features will be added in the process. Consider this, therefore, as a preview product prone to abrupt and extensive changes that may affect functionality of an external code adapted to a prior version(s) of the library. Always explore the provisional compatibility of the library with your project in case you upgrade to a new version of the library (by means of extensive testing of the code in which you are exerting the library's features).

**Be everything as it may, thank you for checking out FinanCalc ![:bowtie:](https://github.githubassets.com/images/icons/emoji/bowtie.png ":bowtie:")**

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity30

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 98.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~11 days

Recently: every ~36 days

Total

22

Last Release

3745d ago

PHP version history (2 changes)v0.1.0PHP &gt;=5.5.0

v0.3.12PHP &gt;=5.4.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/0d9fcd0e569b95325b5d202dc0276de0fe4ffff9fe00099463b2744e2b8e035b?d=identicon)[uruba](/maintainers/uruba)

---

Top Contributors

[![uruba](https://avatars.githubusercontent.com/u/4870410?v=4)](https://github.com/uruba "uruba (279 commits)")[![alloylab](https://avatars.githubusercontent.com/u/1416037?v=4)](https://github.com/alloylab "alloylab (2 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (1 commits)")[![smuriu](https://avatars.githubusercontent.com/u/1464605?v=4)](https://github.com/smuriu "smuriu (1 commits)")

---

Tags

annuitybondbond-yielddebtdividendmaturitymortgagemortgage-calculatorpaymenttimespancalculatormortgageannuitydebtamortization

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/uruba-financalc/health.svg)

```
[![Health](https://phpackages.com/badges/uruba-financalc/health.svg)](https://phpackages.com/packages/uruba-financalc)
```

###  Alternatives

[omnipay/paypal

PayPal gateway for Omnipay payment processing library

3156.8M53](/packages/omnipay-paypal)[eduardokum/laravel-boleto

Biblioteca com boletos para o laravel

626351.9k2](/packages/eduardokum-laravel-boleto)[tbbc/money-bundle

This is a Symfony bundle that integrates moneyphp/money library (Fowler pattern): https://github.com/moneyphp/money.

1961.9M](/packages/tbbc-money-bundle)[2checkout/2checkout-php

2Checkout PHP Library

83740.3k2](/packages/2checkout-2checkout-php)[vovke/loan-payments-calculator

PHP library for payment schedule calculations, using various strategies and configurations.

156.6k](/packages/vovke-loan-payments-calculator)[smhg/sepa-qr-data

Generate QR code data for SEPA payments

61717.2k5](/packages/smhg-sepa-qr-data)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
