Technical Article

Bond and Treasury Formulas in Delphi with HotXLS

A semiannual bond that matures on 15 November 2034 and settles on 31 March 2026 has accrued 136 days of coupon interest under the 30/360 US convention and 135 days under 30/360 European. Both counts are correct. The small integer at the end of a PRICE or COUPDAYBS call decides which one the workbook believes, and that choice flows straight into accrued interest, price, yield and duration

Five day-count conventions behind one basis argument

HotXLS evaluates the Excel bond and treasury functions inside its own formula engine, so a Delphi or C++Builder application can price a bond book on a server that has no Excel and no Analysis ToolPak add-in installed. The basis argument takes the same five values Excel uses: 0 for 30/360 US, 1 for actual/actual, 2 for actual/360, 3 for actual/365 and 4 for 30/360 European. A basis outside 0–4 returns #NUM!, and so does a coupon frequency other than 1, 2 or 4, or a settlement date that is not strictly before maturity

The two 30/360 variants only disagree at month ends. The US rule treats a start on the 31st or on the last day of February as the 30th, but leaves an ending 31 alone unless the start was already the 30th or later; the European rule clamps both ends to 30 unconditionally. In the opening example the last coupon fell on 15 November, so the US count runs to day 31 of March and the European count stops at day 30. The three actual-day bases count calendar days and then part ways on the year length they divide by: a fixed 360, a fixed 365, or the length of the real year. One day of accrual looks trivial until it sits on eight digits of face value

Since Excel 2007 these former Analysis ToolPak functions belong to the standard set and are stored bare in the file, without the _xlfn. prefix that genuinely newer functions carry. Whether such a workbook recalculates correctly depends only on whether the engine reading it knows the functions

Six primitives sit underneath everything else: COUPDAYBS (days from the previous coupon to settlement), COUPDAYS (days in the current coupon period), COUPDAYSNC (days from settlement to the next coupon), COUPPCD and COUPNCD (the previous and next coupon dates) and COUPNUM (coupons still to be paid). HotXLS counts the coupon schedule back from maturity in steps of 12 / frequency months, keeping maturity's day of the month (clamped in shorter months) and staying on month ends when maturity is itself a month end. COUPDAYS is the actual length of the period under basis 1, 365 / frequency under basis 3 and 360 / frequency otherwise. PRICE, YIELD, DURATION and MDURATION build their cash flows from that same schedule code. For identical inputs, the dates a DURATION cell discounts to are the dates COUPPCD and COUPNCD report

HotXLS coupon-date engine for Delphi: bond inputs and the selected day-count basis feed six COUP primitives shared by PRICE, YIELD, DURATION and MDURATION
All five day-count bases feed one coupon-date engine shared by every bond function in HotXLS, so PRICE and DURATION can never disagree about where the coupon dates fall

Pricing a bond in a Delphi workbook

The calling code is plain: inputs in cells, formulas, Recalculate, then each cell's Value. An analyst can open the same file in Excel and see which formula produced which number

uses
  SysUtils, Variants, lxHandleX;

var
  Book: TXLSXWorkbook;
  Sheet: TXLSXWorksheet;
  Row: Integer;
  V: Variant;
begin
  Book := TXLSXWorkbook.Create;
  try
    Sheet := Book.Sheets.Add('Bond');
    Sheet.Cells[1, 1].Value := EncodeDate(2026, 3, 31);   // settlement
    Sheet.Cells[2, 1].Value := EncodeDate(2034, 11, 15);  // maturity
    Sheet.Cells[3, 1].Value := 0.0425;                    // coupon rate
    Sheet.Cells[4, 1].Value := 0.0391;                    // yield
    Sheet.Cells[5, 1].Value := 100;                       // redemption per 100
    Sheet.Cells[6, 1].Value := 2;                         // semiannual
    Sheet.Cells[7, 1].Value := 0;                         // basis: 30/360 US

    Sheet.Cells[9, 1].Formula  := '=PRICE(A1,A2,A3,A4,A5,A6,A7)';
    Sheet.Cells[10, 1].Formula := '=DURATION(A1,A2,A3,A4,A6,A7)';
    Sheet.Cells[11, 1].Formula := '=MDURATION(A1,A2,A3,A4,A6,A7)';
    Sheet.Cells[12, 1].Formula := '=COUPNUM(A1,A2,A6,A7)';
    Sheet.Cells[13, 1].Formula := '=COUPDAYBS(A1,A2,A6,A7)';  // 136 under basis 0

    Book.Recalculate;

    for Row := 9 to 13 do
    begin
      V := Sheet.Cells[Row, 1].Value;
      // Suggested guard to add yourself: a #NUM! arrives as a Variant
      // error, and casting it to Double raises EVariantTypeCastError
      if VarIsError(V) then
        Writeln(Sheet.Cells[Row, 1].Formula, '  -> error')
      else
        Writeln(Sheet.Cells[Row, 1].Formula, '  = ', FloatToStr(Double(V)));
    end;
  finally
    Book.Free;
  end;
end;

Change A7 from 0 to 4 and recalculate: COUPDAYBS drops to 135, and price moves with it because the accrued fraction of the current coupon changed. Recalculate builds the dependency graph on its first call and afterwards re-evaluates only the formulas affected by values written since the previous pass, so a scenario loop that rewrites A4 hundreds of times leaves unrelated sheets alone

Dates go in as TDateTime values. Excel coerces a text date such as "2026-03-31" according to regional settings, a dependency a server batch should not inherit. The serial-number rules underneath, including workbooks saved with the 1904 date system, are covered in date serial numbers and the 1904 system

Why does YIELD cost more than PRICE?

PRICE is a single pass: discount each remaining cash flow at the given yield and add them up. YIELD runs that calculation backwards, and for a bond with more than one coupon left there is no closed-form answer, so it has to search. With a single coupon left, HotXLS solves the linear equation directly. Otherwise it first brackets the answer, starting from a zero yield and widening toward higher yields or toward the −frequency floor, where price grows without bound, and then bisects, repricing the bond on every round until the computed price matches the quote to about twelve significant digits

Every round is a complete pricing pass. Suppose a 30-year semiannual bond: PRICE discounts 60 cash flows once, while YIELD repeats those 60 discounts on every bracketing step and every bisection round. That is why yields belong in their own cell. If your feed delivers prices, compute YIELD once per position and point DURATION and MDURATION at that cell; nesting YIELD(...) inside each duration formula runs the search once per formula. If the feed delivers yields, keep them as inputs and let PRICE do the cheap direction

The two directions accept different ranges, the same way Excel does. A quoted price above what a zero yield implies gives YIELD a negative answer, while PRICE, DURATION and MDURATION return #NUM! when handed a negative yield. YIELD itself returns #NUM! for a price of zero or less, a negative coupon rate, an invalid frequency, basis or date order, or a search that cannot bracket or converge, so the cell never holds a half-finished guess. A wrong input that still produces a valid number is harder to spot, and a round trip catches most of those: feed the solved yield back into PRICE and compare it with the quote

// Quoted price per 100 face value, from the market data feed
Sheet.Cells[15, 1].Value := 101.25;
Sheet.Cells[16, 1].Formula := '=YIELD(A1,A2,A3,A15,A5,A6,A7)';
Sheet.Cells[17, 1].Formula := '=PRICE(A1,A2,A3,A16,A5,A6,A7)';
Book.Recalculate;

// Suggested check of your own: the solved yield has to reprice the bond.
// An error in A16 means the inputs have no yield; an error in A17 means the
// yield came out negative; a plain miss means an input (dates, frequency,
// basis) is not what the feed meant
if VarIsError(Sheet.Cells[16, 1].Value) or
   VarIsError(Sheet.Cells[17, 1].Value) or
   (Abs(Double(Sheet.Cells[17, 1].Value) - 101.25) > 1E-6) then
  raise Exception.CreateFmt('Yield round trip failed for %s',
    [Sheet.Name]);
In HotXLS on Delphi, PRICE is one direct discounted-cash-flow pass while YIELD has no closed form and is solved by a bisection loop that returns an error when no bracket exists
PRICE is one direct pass over the discounted cash flows, while YIELD has no closed form and is bracketed and bisected, returning an error rather than a wrong number when the inputs cannot be priced

Treasury bills and other discount securities

Bills pay no coupon and trade on a discount quote, so they have their own functions: TBILLPRICE, TBILLYIELD and TBILLEQ, each taking settlement, maturity and the discount rate (or the price, for TBILLYIELD). They count actual days and use a 360-day year for the discount: TBILLPRICE is 100 × (1 − discount × days / 360). For a bill settling on 31 March 2026 and maturing 91 days later on 30 June at a 3.85 percent discount, that works out to 99.0268, and TBILLEQ gives a bond-equivalent yield of about 3.942 percent

TBILLEQ has a seam at 182 days. Up to that point the conversion is a single expression, 365 × discount / (360 − discount × days). Beyond it the bill outlives one half-year coupon period of the bond it is being compared with, so the bond-equivalent yield comes from solving a quadratic. A test set that only holds three-month bills never touches the second formula

Running a bill through PRICE with a zero coupon and a frequency of 2 gives a different number, because PRICE divides by a yield factor (compounding only when more than one coupon period remains) while bill pricing subtracts a discount from face value. Neither number is wrong. The same reasoning covers DISC, INTRATE, RECEIVED, PRICEDISC and YIELDDISC, which handle other discount instruments and take an optional basis as their last argument. Write that basis out on every call. Left out, it defaults to 0, 30/360 US, exactly as in Excel, while most money-market paper is quoted actual/360, so an explicit 2 in the formula is usually the intended one and leaves nothing for the next reader to guess

Securities that pay all their interest at maturity have a third set: PRICEMAT and YIELDMAT for price and yield, ACCRINTM for the interest accrued between issue and settlement. All three need the issue date to fall before settlement and return #NUM! otherwise; ACCRINTM also wants a positive rate

// A 91-day bill at a 3.85 percent discount
Sheet.Cells[1, 3].Value := EncodeDate(2026, 3, 31);  // settlement
Sheet.Cells[2, 3].Value := EncodeDate(2026, 6, 30);  // maturity
Sheet.Cells[3, 3].Value := 0.0385;                   // discount rate
Sheet.Cells[5, 3].Formula := '=TBILLPRICE(C1,C2,C3)'; // 99.0268
Sheet.Cells[6, 3].Formula := '=TBILLEQ(C1,C2,C3)';    // about 0.03942

// Nominal 4.25 percent compounded monthly, and back again
Sheet.Cells[8, 3].Formula := '=EFFECT(0.0425,12)';    // 0.043338
Sheet.Cells[9, 3].Formula := '=NOMINAL(C8,12)';

// Three yearly rates applied in sequence to 10,000
Sheet.Cells[1, 5].Value := 0.03;
Sheet.Cells[2, 5].Value := 0.035;
Sheet.Cells[3, 5].Value := 0.04;
Sheet.Cells[11, 3].Formula := '=FVSCHEDULE(10000,E1:E3)'; // 11086.92

// Interest over the first two years of a 25-year monthly loan
Sheet.Cells[13, 3].Formula := '=CUMIPMT(0.0389/12,300,340000,1,24,0)'; // -25836.32
Sheet.Cells[14, 3].Formula := '=CUMPRINC(0.0389/12,300,340000,1,24,0)'; // -16741.10

// A price of 101 and 2/32 written in thirty-seconds notation
Sheet.Cells[16, 3].Formula := '=DOLLARDE(101.02,32)';  // 101.0625
Book.Recalculate;

Rate conversions, loan schedules and French depreciation

EFFECT and NOMINAL convert between a nominal annual rate and the effective rate it produces at a given compounding frequency; 4.25 percent compounded monthly is 4.3338 percent effective. Both need a positive rate and at least one period per year, and the period count is truncated to a whole number. It is the conversion most often botched by hand with a simple division

CUMIPMT and CUMPRINC take all six arguments with no defaults: rate per period, number of periods, present value, first and last period of the window, and payment timing (0 at the end of each period, 1 at the start). The window is 1-based and has to sit inside the loan term, and the rate and present value have to be positive; anything else is #NUM!. Results carry the payment sign, so the 340,000 loan above pays −25,836.32 in interest and −16,741.10 in principal over its first 24 months. Convert rate and term to the same period unit, as above; the functions cannot tell which unit you meant

FVSCHEDULE applies a series of rates in order to a starting principal. The schedule can be a cell range, an array constant such as {0.03;0.035;0.04} or a single rate, and blank cells in a range count as zero; the sequence in E1:E3 turns 10,000 into 11,086.92. DOLLARDE and DOLLARFR convert between decimal prices and fractional quotes, reading the digits after the point as a numerator, so DOLLARDE(101.02,32) is 101 and 2/32, or 101.0625, and DOLLARFR(101.0625,32) gives 101.02 back. AMORLINC and AMORDEGRC implement the linear and declining-balance methods of the French accounting system: the first period is prorated from the purchase date, the declining-balance coefficient grows from 1 to 2.5 with the asset life implied by the rate, and basis 2 is rejected with #NUM!

Checking the engine against Excel's own numbers

Financial output is plausible by construction, and a day-count slip shifts a price by too little to notice and too much to accept. The test that works is differential: let Excel compute a reference workbook once, then have HotXLS recompute every formula in it and compare

An .xlsx saved by Excel caches the value Excel calculated for each formula. TXLSXWorkbook.CalculateAndVerify re-evaluates every formula cell that has a cached value and that HotXLS can compute, compares the result with the cache and returns the number of cells that disagree, or −1 when the dependency graph cannot be built. A cell that evaluates to an error is left out of the comparison. Numbers match when they are within 0.000001 of each other, and volatile formulas such as NOW, TODAY and RAND are skipped because their results are supposed to change. The out-parameter overload returns a TXLSVerifyMismatch record per miss, with sheet, row, column, formula, expected and actual value

uses
  SysUtils, Variants, lxCalc, lxHandleX;

var
  Book: TXLSXWorkbook;
  Misses: TArray<TXLSVerifyMismatch>;
  M: TXLSVerifyMismatch;
  Count: Integer;
begin
  Book := TXLSXWorkbook.Create;
  try
    // Reference workbook built and last saved in Excel
    if Book.Open('bond-reference.xlsx') <> lxOk then
      raise Exception.Create('Cannot open the reference workbook');
    Count := Book.CalculateAndVerify(Misses);
    if Count < 0 then
      raise Exception.Create('Dependency graph could not be built');
    if Count > 0 then
    begin
      for M in Misses do
        Writeln(Format('%s!R%dC%d  %s  Excel=%s  HotXLS=%s',
          [M.SheetName, M.Row, M.Col, M.Formula,
           VarToStr(M.Expected), VarToStr(M.Actual)]));
      Halt(1);  // fail the build
    end;
  finally
    Book.Free;
  end;
end;

The rows matter more than their number. One bond per basis value, 0 through 4. A settlement on the 31st of a month, which is where the two 30/360 rules split. A coupon period that contains 29 February. A position that settles exactly on a coupon date, so COUPDAYBS is zero. One bill of 181 days and one of 183, to cover both sides of the TBILLEQ seam. Rows that are meant to fail, such as a frequency of 3, need their own assertion: read the cell after Recalculate and test it with VarIsError, as in the first example

Differential validation set for the HotXLS bond and treasury functions in Delphi: representative instruments including leap-year and month-end cases are computed once in Excel and asserted after every library upgrade
A differential suite prices representative instruments once in Excel, stores the values as expectations and asserts them after every HotXLS upgrade, so basis-point drift cannot hide behind plausible output

Keep the reference file in version control next to the test and run it on every build. For workbooks that grow beyond a single pricing sheet, the recalculation side is covered in incremental recalculation and the dependency graph, and risk models that also lean on probability work are covered in statistical distribution functions

Bond and bill pricing, statistics, engineering functions and the recalculation engine all ship in the same Delphi and C++Builder library, and the HotXLS Delphi spreadsheet component page lists the rest of the function coverage