webcab bonds for .net v2 · preface this documentation accompanies the webcab bonds .net service....

141
WebCab Bonds for .NET v2.0

Upload: others

Post on 30-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

WebCab Bonds for .NET v2.0

Page 2: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Preface

This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the pricing and risk analysisof interest rate instruments. In particular we cover fundamental topics from the theory ofbonds, fixed interest bonds and interest based calculations.

The first chapter of this documentation contains a brief introduction to the most importantimplemented features and related system requirements. In chapter two we let the developerquickly get started with deploying the component by detailing deployment techniques onthe most widely used deployment environments. The third, fourth and fifth chapters con-tains the mathematical documentation, which represents the theoretical background of thiscomponent’s implemented features. Chapter six until ten, contains the programmer’s guidedetailing a road map for developers to take advantage of every feature and capability ofthis component in a number of deployment environments. In chapter ten we provide someexamples to illustrate how features detailed within the programmer’s guide can be appliedin practice. Finally, we introduce WebCab Components, its philosophy and approach toserving the .NETTM development community with robust and powerful Components.

If you have any questions or queries concerning the use of this component then pleasefeel free to contact us via our support forum at:

http://www.webcabcomponents.com/support/index.php

Good luck with your project and thank you for your interest in our component.

The WebCab Components Team

i

Page 3: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Contents

Preface i

1 Introduction 11.1 Product Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.1.2 Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.2 Package Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.3 Prerequisites and Compatibility . . . . . . . . . . . . . . . . . . . . . . . . 5

1.3.1 System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . 51.3.2 Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Where do I Start? 62.1 What Type of User Are You? . . . . . . . . . . . . . . . . . . . . . . . . . 62.2 What Do I Need to Install and Where Can I Get It? . . . . . . . . . . . . 7

2.2.1 Installing the IIS Web server . . . . . . . . . . . . . . . . . . . . . . 82.2.2 What Do I Need if I am Using Windows 2003? . . . . . . . . . . . . 9

2.3 Deploying the .NET Service . . . . . . . . . . . . . . . . . . . . . . . . . . 112.3.1 Deploying a Component . . . . . . . . . . . . . . . . . . . . . . . . 112.3.2 Deploying an XML Web Service . . . . . . . . . . . . . . . . . . . . 12

2.4 Using the DLLs inside an IDE . . . . . . . . . . . . . . . . . . . . . . 142.4.1 Using the DLL within a Visual Studio .NET project . . . . . . . . . 142.4.2 Using the DLL within a Borland’s C# Builder project . . . . . . . . 14

2.5 Client Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.5.1 Running the Console Client Example . . . . . . . . . . . . . . . . . 152.5.2 ASP.NET Client Example . . . . . . . . . . . . . . . . . . . . . . . 162.5.3 XML Web service examples . . . . . . . . . . . . . . . . . . . . . . 16

2.6 Testing the Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182.6.1 Accessing the Online ASP.NET Demo . . . . . . . . . . . . . . . . 182.6.2 Online XML Web service examples . . . . . . . . . . . . . . . . . . 192.6.3 Using .NET Web Service Studio . . . . . . . . . . . . . . . . . . . . 20

3 Fundamental Theory of Bonds 233.1 Types of Rates and pricing . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

3.1.1 Types of Rates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

ii

Page 4: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

CONTENTS CONTENTS

3.1.2 Bond Pricing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243.1.3 Zero Rates, Bootstrapping and the Constructing the Zero Rate Curve 25

3.2 Forward Rates and Forward-Rate Agreements . . . . . . . . . . . . . . . . 263.2.1 Evaluating the Forward Rate . . . . . . . . . . . . . . . . . . . . . 263.2.2 Forward-Rate Agreements . . . . . . . . . . . . . . . . . . . . . . . 27

3.3 Duration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.3.1 Price and Duration of a Bond . . . . . . . . . . . . . . . . . . . . . 283.3.2 Duration of a Bond Portfolio . . . . . . . . . . . . . . . . . . . . . . 283.3.3 Rescaling the Duration . . . . . . . . . . . . . . . . . . . . . . . . . 293.3.4 Duration in a general setting . . . . . . . . . . . . . . . . . . . . . . 293.3.5 Duration Based Hedging and Convexity . . . . . . . . . . . . . . . 29

4 Yield of Fixed-Interest Bonds on Interest Payment Dates 324.1 Simple Yield to Maturity (for Japanese Government Bonds (JGB)) . . . . 324.2 Gross Redemption Yield and Current Price . . . . . . . . . . . . . . . . . . 334.3 Net Redemption Yield (excluding CGT) . . . . . . . . . . . . . . . . . . . 344.4 Holding Period Return (US and UK) . . . . . . . . . . . . . . . . . . . . . 354.5 Bisection and Newton Raphson . . . . . . . . . . . . . . . . . . . . . . . . 36

4.5.1 Bracketing One Dimensional Equations . . . . . . . . . . . . . . . . 364.5.2 Bisection Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374.5.3 Newton-Raphson Method . . . . . . . . . . . . . . . . . . . . . . . 37

5 Interest Calculations 395.1 Preliminaries and Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

5.1.1 Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395.1.2 Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

5.2 Simple Interest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415.2.1 Basic formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415.2.2 Real worth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415.2.3 Real return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

5.3 Compound Interest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425.3.1 Accumulated values . . . . . . . . . . . . . . . . . . . . . . . . . . . 425.3.2 Real worth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425.3.3 Real return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435.3.4 Depreciation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435.3.5 Force of interest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

5.4 Effective and Nominal Interests . . . . . . . . . . . . . . . . . . . . . . . . 445.4.1 Effective rate of interest . . . . . . . . . . . . . . . . . . . . . . . . 445.4.2 Real return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455.4.3 Nominal rate of interest . . . . . . . . . . . . . . . . . . . . . . . . 45

5.5 Net Present value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455.6 Annuities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

5.6.1 Accumulated Values of an Annuity . . . . . . . . . . . . . . . . . . 465.6.2 Present Value of Annuities . . . . . . . . . . . . . . . . . . . . . . . 47

iii

Page 5: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

CONTENTS CONTENTS

5.6.3 Series of multiple payments per interval in arrears . . . . . . . . . . 485.7 Yield (internal rate) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

5.7.1 Finding the yield . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485.7.2 The relationship between real and nominal yield . . . . . . . . . . . 49

5.8 Repo agreements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

6 Programmer’s Guide for Microsoft Office 506.1 Developing with VBA from Office . . . . . . . . . . . . . . . . . . . . . . . 50

6.1.1 Open the Visual Basic Editor . . . . . . . . . . . . . . . . . . . . . 516.1.2 Add a Code Module . . . . . . . . . . . . . . . . . . . . . . . . . . 516.1.3 Declare a Subroutine . . . . . . . . . . . . . . . . . . . . . . . . . . 516.1.4 Add a Reference to This Product . . . . . . . . . . . . . . . . . . . 526.1.5 Declare a Class Instance Variable . . . . . . . . . . . . . . . . . . . 546.1.6 Create a Class Instance . . . . . . . . . . . . . . . . . . . . . . . . . 546.1.7 Call a Class Method . . . . . . . . . . . . . . . . . . . . . . . . . . 556.1.8 Display the Method Result . . . . . . . . . . . . . . . . . . . . . . . 556.1.9 Run the Subroutine . . . . . . . . . . . . . . . . . . . . . . . . . . . 556.1.10 A Generic VBA Example for Office . . . . . . . . . . . . . . . . . . 58

6.2 Integrating with Microsoft Excel . . . . . . . . . . . . . . . . . . . . . . . . 596.2.1 Open the Visual Basic Editor . . . . . . . . . . . . . . . . . . . . . 596.2.2 Add a Code Module . . . . . . . . . . . . . . . . . . . . . . . . . . 596.2.3 Declare a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 606.2.4 Add a Reference to This Product . . . . . . . . . . . . . . . . . . . 606.2.5 Declare a Class Instance Variable . . . . . . . . . . . . . . . . . . . 606.2.6 Create a Class Instance . . . . . . . . . . . . . . . . . . . . . . . . . 616.2.7 Call a Class Method . . . . . . . . . . . . . . . . . . . . . . . . . . 616.2.8 Store the Method Result as a Function Return Value . . . . . . . . 616.2.9 Insert the Function in your Worksheet . . . . . . . . . . . . . . . . 62

7 Programmer’s Guide for Visual Studio 6 667.1 Developing with Visual Basic 6 . . . . . . . . . . . . . . . . . . . . . . . . 66

7.1.1 Add a Reference to This Product . . . . . . . . . . . . . . . . . . . 667.1.2 Declare a Class Instance Variable . . . . . . . . . . . . . . . . . . . 677.1.3 Create a Class Instance . . . . . . . . . . . . . . . . . . . . . . . . . 687.1.4 Call a Class Method . . . . . . . . . . . . . . . . . . . . . . . . . . 697.1.5 Provide Functions for the Pricing Module . . . . . . . . . . . . . . 69

7.2 Illustrating Visual Basic Examples . . . . . . . . . . . . . . . . . . . . . . 727.2.1 Calling the Real Return method which takes and returns doubles . 747.2.2 Calling the WeightOfBonds method which takes and returns double

arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757.3 Developing with Visual C++ 6 . . . . . . . . . . . . . . . . . . . . . . . . 77

7.3.1 Open a New or Existing Project . . . . . . . . . . . . . . . . . . . . 777.3.2 Add All COM Specific ’include’ Declarations . . . . . . . . . . . . . 817.3.3 Call ”CoInitialize” . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

iv

Page 6: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

CONTENTS CONTENTS

7.3.4 Import the Type Library for this Product . . . . . . . . . . . . . . 827.3.5 Connect to a COM Server . . . . . . . . . . . . . . . . . . . . . . . 827.3.6 Declare the Parameter Types and Values . . . . . . . . . . . . . . . 837.3.7 Declare the Return Type . . . . . . . . . . . . . . . . . . . . . . . . 857.3.8 Call the Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 857.3.9 Call ”CoUninitialize” . . . . . . . . . . . . . . . . . . . . . . . . . . 867.3.10 A Generic Visual C++ Example . . . . . . . . . . . . . . . . . . . . 87

8 Programmer’s Guide for Borland C++ Builder 908.1 Developing with Borland C++ Builder . . . . . . . . . . . . . . . . . . . . 90

8.1.1 Open a New or Existing Project . . . . . . . . . . . . . . . . . . . . 918.1.2 Add all COM Specific ”Include” Declarations . . . . . . . . . . . . 938.1.3 Call ”CoInitialize” . . . . . . . . . . . . . . . . . . . . . . . . . . . 938.1.4 Create a Class Instance . . . . . . . . . . . . . . . . . . . . . . . . . 948.1.5 Obtain a Method ID . . . . . . . . . . . . . . . . . . . . . . . . . . 958.1.6 Declare the Parameter Values and Types . . . . . . . . . . . . . . . 958.1.7 Declare the Return Type . . . . . . . . . . . . . . . . . . . . . . . . 968.1.8 Call the Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 968.1.9 Call ”CoUninitialize” . . . . . . . . . . . . . . . . . . . . . . . . . . 978.1.10 A Generic Borland C++ Builder Example . . . . . . . . . . . . . . 97

9 Programmer’s Guide for .NET 1009.1 Developing with .NET Class Libraries . . . . . . . . . . . . . . . . . . . . . 100

9.1.1 Stand-alone C# .NET Applications . . . . . . . . . . . . . . . . . . 1009.2 Developing with XML Web Services . . . . . . . . . . . . . . . . . . . . . . 102

9.2.1 Deploying the XML Web Services . . . . . . . . . . . . . . . . . . . 1029.2.2 Writing XML Web Service Clients . . . . . . . . . . . . . . . . . . . 1029.2.3 Writing Console XML Web Service Clients . . . . . . . . . . . . . . 1039.2.4 Importing Web services into Visual Studio .NET projects . . . . . . 105

9.3 Connecting to a Database with our .NET Libraries . . . . . . . . . . . . . 1069.3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1069.3.2 The ADO Mediator . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

10 Examples 11210.1 Question and Answer (QA) Client Examples . . . . . . . . . . . . . . . . . 112

10.1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11210.1.2 Structure of QA Examples Directory . . . . . . . . . . . . . . . . . 11210.1.3 Quick Start Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . 11410.1.4 Explanation of the QA Directory Structure and its files . . . . . . . 11410.1.5 Remarks on .NET compilers . . . . . . . . . . . . . . . . . . . . . . 116

10.2 Custom Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11610.3 Fundamental Theory of Bonds . . . . . . . . . . . . . . . . . . . . . . . . . 116

10.3.1 Zero Rates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11710.3.2 Forward Rates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

v

Page 7: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

CONTENTS CONTENTS

10.3.3 Treasury Price . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11810.3.4 Duration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12210.3.5 Database Example with JDBC Mediator . . . . . . . . . . . . . . . 127

10.4 Yield of Fixed-Interest Bonds on Interest Payment Dates . . . . . . . . . . 12810.4.1 Gross Interest Yield . . . . . . . . . . . . . . . . . . . . . . . . . . 12810.4.2 Gross Redemption Yield . . . . . . . . . . . . . . . . . . . . . . . . 12810.4.3 Holding Period Return . . . . . . . . . . . . . . . . . . . . . . . . . 129

10.5 Interest Investments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12910.5.1 Compound Interest . . . . . . . . . . . . . . . . . . . . . . . . . . . 12910.5.2 Effective Rate of Interest . . . . . . . . . . . . . . . . . . . . . . . . 12910.5.3 The accumulated value . . . . . . . . . . . . . . . . . . . . . . . . . 13010.5.4 Present Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13010.5.5 Yield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13010.5.6 Repo agreements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131

11 Guide to WebCab Components 13211.1 The Company . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13211.2 Presentation of Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13211.3 Supported Clients, IDEs, Containers and DBMSs . . . . . . . . . . . . . . 13211.4 Transparent Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . 13311.5 Company Culture and Activity . . . . . . . . . . . . . . . . . . . . . . . . 13311.6 Product Life cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13311.7 Support, Warranty and Upgrades . . . . . . . . . . . . . . . . . . . . . . . 133

vi

Page 8: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Chapter 1

Introduction

1.1 Product Description

1.1.1 Overview

General Interest derivatives pricing framework: set contract, set vol/price/interest models andrun MC. We also cover: Treasury’s, Price/Yield, Zero Curve, Fixed-Interest bonds, Forwardrates/FRAs, Duration and Convexity.

1.1.2 Details

WebCab Bonds implements the following functionality:

General Interest Derivatives Pricing Framework

General Pricing Framework offers the following predefined Models and Contracts:

� Contracts: Asian Option, Binary Option, Cap, Coupon Bond, Floor, Forward Startstock option, Lookback Option, Ladder Option, Vanilla Swap, Vanilla Stock Option,Zero Coupon Bond, Barrier Option, Parisian Option, Parasian Option, Forward andFuture.

� Interest Rate Models: Constant Spot Rate, Constant (in time) Yield curve, Onefactor stochastic models (Vasicek, Black-Derman-Toy (BDT), Ho Lee, Hull andWhite), Two factor stochastic models (Breman Schwartz, Fong Vasicek, LongstaffSchwartz), Cox-Ingersoll-Ross Equilibrium model, Spot rate model with automaticyield (Ho Lee, Hull White), Heath-Jarrow-Morton forward rate model, Brace-Gatarek-Musiela (BGM) LIBOR market model.

� Price Models: Constant price model, General deterministic price model, Lognormalprice model, Poisson price model.

� Volatility Models: Constant Volatility Models, General Deterministic Volatilitymodel, Hull White Stochastic model of the Variance, Hoston Stochastic Volatilitymodel.

1

Page 9: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Introduction Chapter 1

Once the contract and the price/interest/vol model combination has been set you able torun the Monte Carlo Princing Engine which allows:

� Evaluate Price: Evaluate price estimate accordance to number of iterations ormaximum expected error

� Estimate Error: Evaluate the standard deviation of the price estimate, and theminimum/maximum expected price for a given confidence level.

Fundamental Theory of Bonds

� Pricing and Yield

– Pricing - Discounted cash flows model in accordance with the risk free interestrate

– Yield to Maturity (YTM) - the YTM (also known as the Internal rate ofReturn (IRR) can be evaluated for any bond where the market price and thecoupon payments until maturity are known.

– Treasury Price - evaluate the price of a Treasury bond from the Treasury zerorates.

– Bond Yield - returns the yield of a Treasury bond when the price and couponsare known.

– Par Yield - we provide methods for calculating the Par Yield where the numberof yearly payments and the annuity may vary.

� Constructing the Zero Rate Curve - using the technique known as bootstrappingand linear interpolation we our able to construct the zero rate curve.

� Forward Rates and FRAs

– Evaluation of Forward Rates - the forward rate for a given period can beevaluated from the zero rates at the start and end of that period.

– Forward Rate Agreements (FRAs) - we provide a method which shows tovalue of a FRA and the cash flows when the contract is settled.

� Duration and Convexity

– Duration - the Duration of a bond, bond portfolio, interest rate future and therescaling of Duration according to different interest compounding conventions.

– Duration based hedging - Duration-Hedge Ratio, Convexity and its use inhedging interest rate risk.

2

Page 10: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Introduction Chapter 1

Yield of Fixed-Interest Bonds on Interest payment dates

� Simple Yield to Maturity - As used in Japanese bond markets to calculate theyield to maturity (simple yield to maturity) rather than the usual compound interestmethod (redemption yield).

� Gross Redemption Yield - For an interest payment date the gross redemptionyield is given. We follow the convention in the US and UK to calculate and expressredemption yield as a yield per annum, convertible half-yearly.

� Net Redemption Yield - The gross redemption yield on an interest payment datetaking into account the investors income tax position.

� Holding period return - The yield over the period the stock was held by theinvestor according to US and UK interest payment conventions.

� Rate of Payments - Knowing the series of payments of one per interval payable inarrears for a number of intervals.

� Series of Payments - Knowing the rate of interest per interval and the number ofintervals.

In implementing the above procedures it has often be necessary to find solutions of poly-nomial equations. In order to find these solutions we have used the following techniques:

� Interval Bisection Method - A robust method that always finds a solution or asingularity inside a bracketed interval.

� Newton-Raphson Method - Given a first approximation to a root and the differ-ential of the function this procedure will always produce a solution. We implementthis procedure for polynomial functions of one variable.

Interest Calculations

� Exponents and Series - Law of Exponents, Arithmetic Progression, Finite/InfiniteGeometric Series

� Simple interest - a deposits value, Real worth, Real return

� Compound interest - Accumulated values, Real worth, Real return, Depreciation

� Effective and nominal interest - Real return, Force of interest

� Accumulated values of annuity-certain - Accumulated annuity certain in ar-rears, Accumulated annuity certain in advance

� Present values

� Present value of annuity-certain

3

Page 11: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Introduction Chapter 1

� Yield - Internal rate, Real and nominal

� Real returns - Bonds, Rate of return

Technology Aspects

This product also has the following technology aspects:

� 3-in-1: .NET, COM, and XML Web services - Three DLLs, Three API Docs,Three Sets of Client Examples all in 1 product. Offering a 1st class .NET, COM,and XML Web service product implementation.

� Extensive Client Examples - Multiple client examples including .NET (C#, VB.NET,C++.NET), COM and XML Web services (C#, VB.NET)

� ADO Mediator - The ADO Mediator assists the .NET developer in writing DBMSenabled applications by transparently combining the financial and mathematicalfunctionality of our .NET components with the ADO.NET Database Connectivitymodel.

� Compatible Containers - Visual Studio 6 (incl. Visual Basic 6, Visual C++ 6), Vi-sual Studio .NET (incl. Visual Basic .NET, Visual C#.NET, and Visual C++.NET),Borland’s C++ Builder (incl. C++Builder, C++BuilderX, C++ 2005), BorlandDelphi 3 - 2005, Office 97/2000/XP/2003.

� ASP.NET Web Application Examples - We provide an ASP.NET Web Appli-cation example which enables you to quickly test the functionality within this .NETService.

� ASP.NET Examples with Synthetic ADO.NET - we use a ASP.NET service toperform component calculations on SQL database columns from a remote DBMS. Weapply a component’s function to certain rows from the database and list the output inHTML format. This is a powerful feature since it allows you to perform calculationsin a DBMS manner without having to code the C# to SQL database transactionyourself as it is all done by the ASP within the .NET Framework managed serverside environment.

1.2 Package Details

This .NET Service package contains the following:

� Introductory Text File (README.TXT)

� License Agreement

� Documentation in PDF Format

– Product Description

4

Page 12: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Introduction Chapter 1

– System Requirements

– Compatibility Issues

– Deployment Guide (How to get started?)

– Mathematical Documentation

– Programmer’s Guide

– Examples

– Guide to WebCab Components

� Class Documentation

– Class Descriptions

– Methods Descriptions

� Deployment Files (DLLs)

� Examples and Related Source Code Files

� WebCab Components Brochure

1.3 Prerequisites and Compatibility

1.3.1 System Requirements

� Microsoft Windowsr

XP/2000/2003 family

� Pentium III 500 MHz

� 64MB RAM

� .NET Framework 1.0 (or higher)

1.3.2 Compatibility

Component Type

� ASP.NET XML Web service

� .NET Class Library

� COM Component

Built Using

� Microsoft .NET Framework SDK

5

Page 13: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Chapter 2

Where do I Start?

Start using the Bonds for .NET v2.0 .NET Service right away by following the few quick andsimple steps described in this chapter. If you require additional information or have problemswith the installation and use of this .NET Service then please do not hesitate to contact us viaour support forum at: http://www.webcabcomponents.com/support/index.php

2.1 What Type of User Are You?

.NET Components or XML Web Services

The prerequisite Windows operating system components you will need to have installed onyour local machine will depend on the way in which you intend to use our .NET Service.In particular, there are two distinct deployment architectures in which our product can beused:

� Class Library - those wishing the use our .NET Components functionality directlywithin there .NET Applications. This category includes those who wish to use ourcomponent within Microsoft’s Visual Studio .NET or Borland’s C#Builder projects,or those who simply want to register the DLL class library onto there local machinefor consumption by local or remote applications.

� XML Web service/ASP.NET - those wishing to deploy either an ASP.NET basedClient server application and an XML Web service.

Chapter Overview

Within the remainder of this chapter we will detail how to install and configure the nec-essary Windows components, deploy the .NET Components or XML Web Services andfinally how to run examples associated within these two deployment scenarios1.

1Later within this PDF documentation within the Programmers Guide we will cover developmenttechniques which can be employed for either composing larger applications or building clients for thesedeployed components and Web services

6

Page 14: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

The remainder of this chapter is structured in the following way, please feel free to skipany sections which are not relevant to you:

1. Configuration - Describes how to configure the Windows deployment/developmentplatform for .NET based applications, including Web Services.

2. Deployment - Details the deployment of the .NET Service as a .NET Componentor as a XML Web Service.

3. Using the DLLs inside an IDE - We detail here how to import the .NET ClassLibraries DLLs into Microsoft’s Visual Studio .NET and Borland’s C# Builder.

4. Clients - Explains client examples provided with this .NET Service

5. Live Demos - Details the functionality of the Online Web Application Demos.

2.2 What Do I Need to Install and Where Can I Get

It?

In order to deploy and then use a .NET Component within your applications you are re-quired to have (or install) the following Windows component onto your Windows operatingsystem:

� .NET Framework

If you wish to deploy either ASP.NET or XML Web services then you will also be requiredto install:

� Microsoft’s Internet Information Server (IIS)

In order to develop .NET based applications (i.e. compile C#.NET source code) you willalso need to have the following Windows Components installed:

� .NET Framework SDK

Getting the .NET Platform

The .NET Framework’s installation package comes in the following two flavors:

� .NET Framework SDK (approx. 110MB)

� .NET Framework, Redistribution package (approx. 23MB)

Those wishing to develop applications using the .NET Framework will require the .NETFramework and the .NET Framework SDK installed onto the development machine. Whereasthose who only wishing to deploy .NET Applications and Services will require only the.NET Framework (also known as the .NET Framework Redistribution package). The latestversion of these packages can be downloaded from http://msdn.microsoft.com/downloads.

In order to run our ASP.NET and Web service demos you are also required to have Mi-crosoft’s IIS Web server installed and started.

7

Page 15: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

Installing the .NET Framework

Through the Add/Remove Programs feature of the Control Panel you are able to dis-cover which version (if any) of the .NET Framework you are currently running. If youintend to upgrade to a later version of the .NET Framework then you are presently run-ning then we strongly suggest that you first uninstall all previous versions of the .NETFramework first. This is due to the fact that some applications will use the earliest in-stalled version of the .NET Framework rather than the latest edition.

You can then proceed to install the latest version of the .NET Framework by just exe-cuting the .NET Framework installation package by following through the dialog withinthe installation program.

Remark Please note that Microsoft will ensure backward compatibility of the .NETFramework. That is, application developed under v1.0 for example will run and behave ina similar fashion under later releases of the .NET Framework.

2.2.1 Installing the IIS Web server

In order to deploy and run ASP.NET or XML Web services you are required to have therelevant pieces of the “Applications Server” stack installed onto the deployment Windowsmachine. The key piece of this infrastructure stack is Microsoft’s IIS Web server.

On any Windows machine you can check to see whether the IIS Web server is installed andrunning by opening the following page within a web browser http://localhost. If the IISWeb server is installed and running then you will be presented with either a placeholderpage similar to the following:

8

Page 16: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

If you already have a web site deployed into the root directory of the IIS Web server thenthe home page of this web site will be displayed.

Remark By requesting the page http://localhost, the local IIS Web server will be auto-matically restarted if it is not already running.

Installation Process

If the IIS Web server is not installed onto your local machine then you may install itthrough using the Windows Program installation tool. To access this tool select:

Settings > Control Panel > Add or Remove Programs

Now click on the button, Add\Remove Windows Components. A window should pop-up in which a number of Windows components are listed, one of these items should readInternet Information Services (IIS). You should select the click box for this serviceand install it by clicking the Next button.

2.2.2 What Do I Need if I am Using Windows 2003?

Microsoft’s Windows 2003 is the first Windows operating system that has been designed ex-plicitly to host .NET Applications. Though, Windows 2003 has the .NET Framework v1.1embedded within the operating system you will still need to configure the IIS Web serveror the .NET Framework SDK if you intend to either deploy ASP.NET based Applicationsor use the Windows 2003 machine to develop .NET based Applications and Services.

9

Page 17: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

Installing the IIS Web server onto Windows 2003

The IIS Web server for the Windows 2003 operating system is not installed by default.Therefore, if you did not explicitly request the deployment of the system component knownas ‘Application Server’ during the installation of Windows 2003. You will need to manu-ally install this Windows 2003, component if you wish to deploy ASP.NET or XML Webservices to your local machine. For all Windows platforms the deployment process of theIIS Web server proceeds in a similar fashion via the control panel interface.

In order to deploy the ‘Applications Server’ components first select Add/Remove Win-dows Components from the Add/Remove Programs control panel interface.

Once the ‘Application Server’ is selected by clicking on the Details button you will bepresented with:

10

Page 18: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

Remarks

� As you can see from the above screen shot by default the ASP.NET, Enable net-work COM+ access and Internet Information Services (IIS) have been se-lected which is sufficient for the deployment of nearly all .NET Framework basedApplications and Services.

� The Windows 2003 platform contains a thoroughly updated infrastructure stack con-cerning the delivery of ASP.NET and XML Web services. This includes a newASP.NET container which is closely integrated with the IIS Web server. This updatecontains several enterprise level .NET related features concerning the managementof services (automatic startup, shutdown of services and the server itself), security(lockdown of ports and unused services), scalability (load balancing) and easier man-agement (Component services and IIS management console). In our opinion theWindows 2003 platform offers a significantly more robust platform than early ver-sions of the Windows platform in which to deploy .NET Applications and Services.

2.3 Deploying the .NET Service

If you installed this product using the MSI installer then the .NET Class Libraries DLLsshould already be registered within your global assembly cache. In order to use the corre-sponding XML Web Service implementation you will need to follow the deployment guidebelow.

In case you installed using a Zip package or wish to install the .NET Class Librariesonto another Windows machine we explain below how to manually deploy our .NET ClassLibraries.

2.3.1 Deploying a Component

Once the .NET Framework has been installed onto the deployment machine the component(i.e. the DLL), can be deployed and registered. By registering the component it will becomeavailable to local and remote .NET Applications and Services.

Making your components (locally) available

The easiest and quickest means to deploy the DLL component files, is to simply copy themto one of the following two directories on your Windows machine:

� WINDOWS\System

� Application directory - the directory in which the .NET Application which willconsume the component is located.

When your Application is executed Windows will automatically look in one of these loca-tions for the DLL file with it wishes to import.

11

Page 19: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

Making the Components Globally available?

The above deployment technique is straightforward but has the restriction that is does notallow for any custom configuration of the deployment environment which may be requiredby the .NET Application which will consume the component. Moreover, such deploymenttechniques do not allow the components (i.e. DLL’s) to be effectively shared between twoor more applications. In order to allow the components to be used by several applicationsyou must deploy the components within the Global Assembly Cache.

Remark The Global Assembly Cache within the .NET Framework plays a similarrole to that of the CLASSPATH environment variable within the Sun Java platform.

A Component can be deployed to the Global Assembly Cache in one of two ways:

� Microsoft Windows Installer 2.0 - Recommended for use on production servers.

� Global Assembly Cache tool (Gacutil.exe) - Recommended only for use on develop-ment or test servers.

Please note, in order to use the Assembly Cache tool you are required to have the .NETFramework SDK installed and to create a Windows installer you will need the WindowsInstaller SDK v2.0. For further details concerning the Windows Installer technology werefer the interested reader to the Visual Studio .NET documentation or the MSDN sectionof Microsoft’s website.

The Global Assembly Cache Tool is run from the DOS command prompt. In order todeploy the assembly WebCab.Libraries.BondsDemo.dll, contained within the present di-rectory you must input the command:

Gacutil.exe /i WebCab.Libraries.BondsDemo.dll

Using the DLL within your own Applications

Within the Library directory of the installation package you will find the class libraryassembly (DLL) for Bonds. There are several ways you may choose to use this DLL withinyour applications.

2.3.2 Deploying an XML Web Service

Once the .NET Framework and the IIS related infrastructure is installed the actual deploy-ment of an ASP.NET Application or an XML Web service just involves copying a DLL fileand several ASMX files into given directories within the IIS Web server root file directory.

Installation Process

12

Page 20: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

Within the XML Web service folder within this installation package are the resourcesfor deploying the Web service of the Bonds. In order to install and start using the XMLWeb service functionality you will need to perform the following steps:

� Deploy the XML Web service assembly (DLL) onto your local IIS Web server. Thisis accomplished by copying the contents of the ‘bin’ folder of the current directoryto the ‘bin’ folder of the local IIS root directory, which under the default installationis C:\Inetpub\wwwroot.

� Deploy all .asmx pages inside the IIS Web server, by copying all the folders locatedunder the XML Web service folder located under the current directory to the IISroot directory.

� Run the WSDL tool in order to generate all XML Web service proxies. This is doneby running the following line at the command prompt:

wsdl http://localhost/<directory name>/<XML Web service>.asmx

where <directory name> is the name of the subdirectory of the IIS root in whichthe XML Web service is deployed and <XML Web service> is the name of the Webservice which you wish to generate a proxy for.

Remarks

� All generated proxies are used as described in the CHM documentation of this prod-uct.

� If the Web service is not being locally run then the ‘localhost’ should be replacedwith the host name of the computer where the Web service is deployed and running.

� You may be using another equivalent ASP.NET Web server, in which case the abovedeployment procedure may differ slightly in detail but will still involve the same basicsteps.

Testing the Deployment

You can easily test an XML Web service deployment by using any compatible web browser.That is, to test the deployment open a compatible web browser (for example Internet Ex-plorer) and open the following page:

http://localhost/<directory name>/<filename>.asmx

where <directory name> is the name of the subdirectory of the IIS directory root wherethe Web services are located and <filename> is the name of one of the .asmx files locatedinside the <directory name> folder. As soon as the browser displays the page correctlyyou are sure that the corresponding XML Web service has been properly installed.

13

Page 21: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

2.4 Using the DLLs inside an IDE

2.4.1 Using the DLL within a Visual Studio .NET project

If you are developing a Visual Studio .NET project and wish to use our DLLs componentsfunctionality then you may add the DLL to the project reference. This is performed byusing the Project > Add Reference... menu item.

2.4.2 Using the DLL within a Borland’s C# Builder project

If you are developing a C#Builder project and wish to use our DLLs components function-ality then you may deploy and then add the assembly to your project solely from withinC# Builder.

To deploy the DLL select from the menu, Component > Installed .NET Components Thenclick on the ‘Select an Assembly’, to select the DLL from the file system.

Once the DLL component is deployed you may add the DLL to your C# project by rightclicking on your project within the “Project Manager” and selecting “Add reference” asshow below:

14

Page 22: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

Alternatively, you could use the equivalent link with the menu, Project > Add Reference.

Now an ‘Add reference’ window will pop-up, in which you should select the assemblyyou wish to add to your project and then click OK.

2.5 Client Examples

Within this section we describe the clients which have been provided with this .NETService. In particular, we will describe:

1. Console Client Examples

2. ASP.NET Client Examples

3. Web Service Client Examples

2.5.1 Running the Console Client Example

In order to run the console demonstration examples you must start a DOS CommandPrompt. On a Windows XP machine this can be achieved by:

START > Programs > Accessories > Command Prompt

Once the command prompt is started you should navigate to the Librares\Client sub-directory of the installation directory2 using the cd command. The Client subdirectoryis structured into subdirectories corresponding to client examples. Every client exampleshould be accompanied by a compile.cmd file, which when run will compile its corre-sponding client. After compilation, the only thing left to do is launch into execution thegenerated executable file(s).

For further technical details you should read the README.TXT files located insidethe Client subdirectories.

2Usually C:\Program Files\WebCab Components\Bonds.

15

Page 23: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

2.5.2 ASP.NET Client Example

Within the \NET Libraries\ASP.NET Examples, folder of this package we have pro-vided a set of tailor made ASP.NET examples for the WebCab Bonds for .NET v2.0 .NETService.

In order to start using these ASP.NET examples, please go through the following steps:

1. Deploy the ASP.NET Pages and Resources

(a) Copy the contents of the ‘Bonds ASP.NET Examples’ folder located in thecurrent directory to a location under your IIS (or another compatible ASP.NETweb server) root directory. This is usually ‘C:\Inetpub\wwwroot’ or a similarpath with a different drive letter.

(b) Secondly, copy the contents of the ‘bin’ subfolder of the current directory to the‘bin’ subfolder of your IIS root directory. If the ‘bin’ directory does not existinside the IIS root directory, you will be required to create it.

2. Run the ASP.NET Examples

(a) Open an Internet browser3 and type in the following address:

http://localhost/Bonds ASP.NET Examples/index.html

In case you chose to copy the ‘Bonds ASP.NET Examples’ directory to a sub-directory of your IIS root directory, you will need to include the full path toit inside the above URL. Also, if you have deployed these ASP.NET examplesto another .NET machine, you should replace ‘localhost’ with the name of thatmachine.

Remark An online version of these ASP.NET examples can be found at:

webcabcomponents.com/dotNET

Using the Example

Further explanation regarding the use of this example can be found within the ‘Accessingthe Online Demo’, section of this guide which details the use of the online version of thisASP.NET example.

2.5.3 XML Web service examples

Within the directory \XML Web Services\Client\, you will find C# application clientexamples which make use of the financial and mathematical functionality provided by theXML Web services implementation of the WebCab Bonds .NET Service.

3E.g. Internet Explorer, Opera, Mozilla.

16

Page 24: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

Remark In order to run and access the Web service examples it is necessary to havethe IIS web server and a compatible internet browser (for example Internet Explorer 5 orhigher) installed onto your local machine.

Please go through the following steps in order to test these client examples:

1. Before running or even compiling these XML Web service client examples you willhave to deploy all Bonds XML Web services located one directory level above to yourlocal IIS server or an IIS server your machine can connect to. This is accomplishedby copying the contents of the ‘bin’ folder, located one level above in the directorystructure, to the ‘bin’ folder of the IIS root directory, usually C:\Inetpubwwwroot.You will also need to copy the ‘BondsDemo’ folder to the IIS root directory.

2. Browse through each subfolder of the current directory and locate every ‘compile.cmd’compilation script file. There is one compilation script for every client example. Everyclient example requires certain XML Web services to connect to, which you maydetermine by running the compilation script. The reported errors should correspondto the XML Web services the client example requires.

3. Run the WSDL tool in order to generate XML Web service proxies for every XMLWeb service required by each client example. This is done by running the followingline at command prompt:

wsdl http://localhost/BondsDemo/<XMLWebservice>.asmx

where <XMLWebservice> is the name of the required XML Web service and ‘localhost’should is the host name of the computer where the IIS server is running, in case it’snot this machine.

Make sure you are running this command from directory containing the compila-tion script.

4. Run the ‘compile.cmd’ compilation script file again. If the right XML Web serviceproxies have been generated for its client examples, the compilation script will com-pile all source code files and generate a .NET executable file (.exe). If the script stillresults in an error, please go through the previous step again, making sure you gener-ate the XML Web service proxy classes required by the client example correspondingto this compilation script.

5. Run the generated executable files. Running the executable files will allow you totest the client examples.

You may compile the client examples (after having generated the XML Web service prox-ies) and run their executable files as you go through each subfolder, since every clientexample is independent of each other.

17

Page 25: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

If you wish to customize a particular client example after having run it, please feel free toadapt its source code files accordingly and run the compilation script again. Note that youwill not need to regenerate the XML Web service proxy classes.

2.6 Testing the Component

2.6.1 Accessing the Online ASP.NET Demo

By far the easiest way to test the functionality of this .NET Service is to view the on-line demo. The online demo can be accessed from our .NET Homepage by clicking the‘[ASP.NET]’ link corresponding to this Application. Once you click on the link the follow-ing pop-up Window will appear:

Fig: Interface of the ASP.NET online Web Application

Compatible Web Containers

This demo runs inside an online web container and demonstrates the ASP.NET technology.The demo can be accessed through a web browser and is compatible with Internet Explorer5, Netscape Navigator 4, Netscape 6, Opera 5 and higher.

18

Page 26: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

Selecting a method to test

After clicking on the ‘[ASP.NET]’ link for this application from our home page the Webdemo will launch within a new browser window. To order to select a method from thisapplication use the drop-down menu on the left hand side of the screen to navigate throughall implemented functions. The menu lists all the components on the first level and theircorresponding functions on the second and third level. Click on the plus icon in order toexpand the component menu and then click a function item to select it.

Inputting data

The selected function will be displayed on the right hand panel of the new window accom-panied by its description and parameter characterization. Once the nature of the method isclear you may test the method by inputting the parameters within the text boxes providedor associating a database table field using our database management tool.

Running the demo using text boxes

Please input the value of each parameters in to the corresponding text box while payingattention to each parameter description. When all the parameters has been input, pressthe “Get Result” button on the right-hand side and towards the bottom of the screen inorder to request the solution from the server-side component. If by chance any parametersare out of range you will be prompted to enter a correct value before proceeding.

2.6.2 Online XML Web service examples

The XML Web Services contained within this package have also been deployed online. TheWeb service demo is accessed through our .NET Homepage by clicking on the ‘[WSDL]’link corresponding to this Service. Once you click on the link the following pop-up Windowwill appear:

19

Page 27: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

Fig: Interface of the Online Web Services

Remark In order to view the online demos you will require a compatible internet browser(for example Internet Explorer 5 or higher) with JavaScript enabled.

2.6.3 Using .NET Web Service Studio

You may wish to test the functionality of our XML Web services by using one of Mi-crosoft’s .NET tools made for testing XML Web services, .NET Web Service Studio2.0. A link to where you can directly download this tool is available on our onlineweb site at webcabcomponents.com/dotNET. Download and unzip the pack and run theWebServiceStudio\build.bat file. In order to start up the tool double-click the generatedWebServiceStudio.exe .NET executable file.

Deciding on an XML Web service

Click here in order to open the .NET Homepage of our web site. At the bottom of thepage you will notice a list of Online .NET Web Services with their corresponding ASP.NETExample page and their WSDL description page links. Click on the WSDL link next to:fullnamewithoutdotnet:. Move your mouse pointer above the left hand SIDE MENU andclick on an XML Web service name.

20

Page 28: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

A new browser window will open and present you with the default IIS 6.0 ASP.NETXML Web service page. Inside the ‘Address’ bar of your browser you will be able to seethe fully qualified URL to the online WSDL for the corresponding XML Web service.

Connecting to an XML Web service

Copy from your browser’s Address bar the WSDL URL to the XML Web service you havechosen to test and paste it into the WSDL EndPoint text field inside WebService Studio.Click the Get button next to this text field and wait for the tool to establish a connectionto the XML Web service.

As soon as the connection has been established, you can start going through every availablewebmethod our XML Web service has to offer by clicking on the items in the left hand sideof the tool’s window. After clicking a web method’s name, look inside the Input panel forrequired parameters. You may recognize these parameters from the available API CHMdocumentation we have included inside this package4.

Sending in Web Method Parameters

Inside the Body tree of the Input panel you may click on every parameter type and thenset its value inside the Value panel to its right. This is accomplished by editing the rightside of the Value column in the right hand side Value panel.

If you are dealing with parameters of an array type (say a Double[] array), you will firstset its Length in the Value panel and then go through every of its tree children inside theInput panel and set their Value field back into the Value panel. The following two screenshots explain this process.

WebService Studio: Setting the Length of a Double Array to 4

4Browse the API Reference by double-clicking the CHM file located inside the Documentation direc-tory of this Package.

21

Page 29: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Where do I Start? Chapter 2

WebService Studio: Setting the Value of its First Element to 12

Invoking a Web Method

After having sent in the right parameter values5 click the Invoke button right below theValue panel on the right hand side of the window.

The Output panel below the Input panel will present you with the results of invokingthe corresponding Web Method of our online XML Web service over the Internet.

5You should refer to the corresponding API HTML Help documentation even when running this testtool. You could however send in some arbitrary values just to try out some of our simpler Web Methods.

22

Page 30: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Chapter 3

Fundamental Theory of Bonds

Within this chapter we detail the fundamental parts of the theory of bonds including zerorates, pricing, forward rates, duration, simple hedging strategies and convexity.

3.1 Types of Rates and pricing

3.1.1 Types of Rates

As we have seen in the previous chapter the yield of an interest bearing investment can bequoted in a number of ways. Moreover, each type of interest based product for examplemortgages, deposits, loans will each have there own conventions and each of the local mar-kets on which these products are traded will also introduce another layer of conventions.Within the bond market for example there are a number of ways in which the ‘yield’ of abond may be quoted. The particular convention which is used will depend in the type ofbond and the market in which it is traded.

For interest rate derivative products the three following examples are of particular im-portance:

� Treasury Rates - this is the rate at which a government can borrow money in itslocal currency

� LIBOR Rates - LIBOR stands for ‘London Interbank Offer Rate’ and is the rateat which one large international bank will lend money to another large internationalbank. Generally, LIBOR is quoted as the ‘overnight rate’ in US dollars.

� Repo Rate - the implied rate from a repurchase agreement. Securities are soldfor the exchange of cash and repurchased at a prior agreed rate. The Repo rate isnegotiated between the two parties.

� n-year zero rate - the rate of interest earned on an investment over n years wherethe principle and interest payments are only realized after n years.

23

Page 31: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Fundamental Theory of Bonds Chapter 3

3.1.2 Bond Pricing

The price of a government bond (i.e. assuming no default risk) is determined by discountingthe future cash flows. A corresponding corporate bond (i.e. with default risk) will have alower market price since investors will demand a yield premium to make allowance for thedefault risk.

Implemented Methods

Within our class we offer following general bond pricing functionality:

� TreasuryPrice.priceOfBond - A general method which allows a government backedbond to be priced by discounting according to the continuously compounded zerorates.

� TreasuryPrice.tbondPrice - A general method which allows a government backedbond to be priced by discounting according to the risk free interest rate.

� TreasuryPrice.zeroTBondPrice - Evaluates the price of a zero Treasury bond is dis-counting according to the risk free interest rate.

We also offer methods by which the yield to maturity. In each case we deduce to yield tomaturity from the market price of the bond and the coupon payments until maturity. Inparticular, we offer:

� TreasuryPrice.yieldTomaturity - Calculates the yield to maturity (YTM) (also re-ferred to as the internal rate of return (IRR)) for a general bond investment.

� TreasuryPrice.zeroYieldToMaturity - Calculates the zero to maturity of the zerocoupon bond.

� TreasuryPrice.yieldToMaturityFromPrice - The yield to maturity is derived from theprice of the bond and future payments of coupons and principle sum.

Remarks

1. Note that the yield to maturity for non-government backed bonds will be greaterthan the risk free rate in the relevant currency because of the bonds default risk willneed to be reflected within its price. Therefore, the price and yield to maturity forthe Treasury bond will act as a lower respectively upper bound on the price and yieldto maturity of a similar non-government backed bonds (i.e. a corporate bond).

2. In order to evaluate the yield to maturity we where required to solve polynomialequations of one variable relating the yield, price and cash flows. In each case wesolved these polynomial expression by applying the Newton-Raphson method.

Finally, a method for evaluating the Par yield of a Treasury bond is provided:

� TreasuryPrice.parYield - The Par yield is evaluated for a Treasurty bond where thenumber of yearly payments and the abbuity can very.

24

Page 32: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Fundamental Theory of Bonds Chapter 3

3.1.3 Zero Rates, Bootstrapping and the Constructing the ZeroRate Curve

We offer functionality which allows the zero rates to be deduced from zero coupon bondsand then by an itterative procedure known as bootstrapping from coupon paying bonds.Once a set of zero rates for various maturities is known we are able to construct viathe linear interopation approach the zero coupon curve for all maturities. We offer thisfunctionality with the following methods:

� CalculatingZeroRates.zeroRateFromZeroBond - Evaluation of the zero rate for agiven maturity from the corresponding zero bond.

� CalculatingZeroRates.zeroRateBootStrap - Bootstrap method allows the zero ratefor the maturity of a coupon paying bound to be deduced by an itterative procedurefrom coupon paying bonds when the zero rates of the maturities equal to the timeuntil the coupons are paid are known.

� CalculatingZeroRates.zeroRateCurve - Construction of the zero rate curve from afinite set of zero rates of differing maturities in accordance to the convention that thezero rate curve is linear between the given zero rates and constant outside the rangeof maturities.

Application of the Zero Curve

There will be instances when you will require to know the zero rate for a maturity whichcannot be deduced from traded zero coupon and coupon paying bonds. However withinmost interest rate markets there is the range of zero and coupon paying bonds which willallow the deduction of the exact zero rates for a range of maturities.

To solve this problem we can use these maturity to construct what is know as the ‘zerocurve’, by interpolating a curve around the finite number of known zero rates which havebeen explicitly calculated. It is customary for the zero curve to be constructed using lin-ear interpolation between the know zero rates. It is also the custom that the constructedzero curve is assumed to be ‘flat’ (or constant) between the zero maturity and the lowestmaturity explicitly calculated, and above the highest maturity.

Example

If we know the following set of (present) zero rates of US Treasury bonds:

________________________________________________________________________

|Maturity (in years)| 0.25 | 0.5 | 0.75 | 1 | 1.25 | 1.5 | 1.75 | 2 |

+-------------------+------+-----+------+-----+------+-----+------+-----+

|Zero rate (in %) | 6 | 7 | 7.5 | 8 | 8 | 8.6 | 8.7 | 8.8 |

-------------------------------------------------------------------------

25

Page 33: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Fundamental Theory of Bonds Chapter 3

then by using the linear interopation technique for the construction of the zero rate curvewe have:

Once we have constructed the zero rate curve we can read off values for all intermediatevalues.

Remark The above constructed zero rate curve is constant between maturities of 0and 0.25 years, and for maturities larger than 2 years.

3.2 Forward Rates and Forward-Rate Agreements

3.2.1 Evaluating the Forward Rate

The forward rate for a given period (and compounding convention) is the interest ratewhich is implied from the current zero rates. To illustrate forward rates we will considertwo straightforward examples, one where the interest is compounded continuously (Exam-ple 1) and the other where it is compounded over two discrete periods (Example 2).

Example 1: We wish to find the nth year annual forward rate where the interest iscompounded continuously. The (n− 1)th and nth year zero rates is known to be a% andb%. Now since total payments due from the continuously compounded interest of a% perannum on a principle sum of $M after one year is:

(exp a)M

26

Page 34: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Fundamental Theory of Bonds Chapter 3

and hence the payment due after the second year (when we will earn a rate of b%) is goingto be:

exp b ((exp a)M) = (exp a + b)M =

(exp

(a + b

2

)2

)M

Or put another way, the forward rate (per annum) over the period is a+b2

, or the arithmeticaverage of the two rates.

Example 2: Say now that in the above example the interest is compounded once perannum. Now the interest payments after one and two years is ((100 + a)M) /100, and((100 + b)(100 + a)M) /1000. Which leads us to the following equation:

(100 + b)(100 + a)M

1000=

(100 + c)2M

1000

where c is the zero rate (in accordance with the definition). Simplifying this expressiongives us a value for c of:

c =

√(100 + a)(100 + b)

100

This is precisely the forward rate, that is, the unique (expected) rate at a future date whichis implied by the current zero rates.

Remark The continuously compounded case will always imply a higher forward ratethan the discretely compounded case. Since the interest payments will be compounded“much more often”. Saying this, the continuously compounded case and discretely com-pounded case often do not differ by a large margin. For example if a = 5%, and b = 6% inthe above examples in the continuous case the two year forward rate is 5.5%, whereas theannually compounded case the forward rate is 5.4988%.

Implementation

We have implemented within the forwardRate method within the ForwardRates classa general method which allows the forward rate to be evaluated for any period betweentwo points where the corresponding zero rates are known.

3.2.2 Forward-Rate Agreements

A Forward-Rate Agreement (FRA) is an agreement between two parties to pay an agreedlevel of interest on a given principle sum within a given period. Generally speaking, whenthe FRA is set up for a given period the forward rate and the agreed rate are usually thesame. Since an institution can obtain the forward rate on a sum without cost the initialFRA does not have any value and hence no cash will change hands at its instigation. More-over, it is usually the case that the FRA is settled in cash at the beginning of the interestperiod. By the present value of the cash flows due from the agreement being evaluated thecorresponding payment exchanged between the parties.

27

Page 35: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Fundamental Theory of Bonds Chapter 3

Implementation

Within our component we have implemented the forwardRateAgreement method withinthe ForwardRates classes which evaluates the value of the FRA to the holder. We alsooffer a settlement method of the ForwardRates class which calculates the settlement ofthe FRA in the beginning of the interest rate period.

3.3 Duration

3.3.1 Price and Duration of a Bond

The duration can be thought of as the weighted average of the times when payments aremade. Formerally, say a bond provides the holder with payments pi at time ti (1 ≤ i ≤ n).The bonds price, B, and its continuously compounded yield, y, are related by:

B =n∑

i=1

pi exp (−yti)

The duration, D, of the bond is defined as:

D =

∑ni=1 tipi exp (−yti)

B

Remark For a zero-coupon bond that matures in n years the duration is n.

The reason why the duration plays an important role in the hedging and risk analysisof interest rate instruments is because of the following relation:

∆B

B= −D∆y

where ∆y represents a small parallel shift in the interest rate curve and ∆B represents thecorresponding change in the price of the bond. That is, the percentage change in the bondprice is equal to the duration multiplied by the size of the parallel shift in the yield curve.

3.3.2 Duration of a Bond Portfolio

The natural way to define the duration of a portfolio of bonds is as the weighted average ofthe duration of the individual bonds in the portfolio with the weights being proportionalto the bond prices. Though each individual bond may depend on differing yield curves ifwe assume that each of these curves experiences a parallel shift ∆y, then the change in theprice of the bond portfolio is given by the product of the duration of the portfolio and thesize of the parallel shift.

28

Page 36: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Fundamental Theory of Bonds Chapter 3

3.3.3 Rescaling the Duration

Naturally by rescaling the notion of duration according to different interest compoundingconventions. We are able to evaluate the duration when the yield is not expressed ascontinuously compounded interest rates but as the interest rate with respect to anothercompounding convention (e.g. semi-annual). We provide methods which allow the durationand the associated change in the portfolio to be calculated in such instances.

3.3.4 Duration in a general setting

It is important to note that the notion of duration can be used for assets other thanbonds. In fact any instrument which depends on interest rates has a corresponding notionof duration with respect to the interest rate it depends on. The interest rate risk at leastfor small parallel shifts of the relevant interest rate curve can be calculated by using thecorresponding notion of duration. Further, as we will see duration based hedging techniquescan also be applied to such situations.

3.3.5 Duration Based Hedging and Convexity

Duration Based Hedging

As we have seen the duration relates the change in the yield of an interest based investmentwith the change in the price of the same instrument. By applying the duration measurewe can deduce the number of interest rate futures contracts required to hedge an interestrate investment for small parallel shifts.

Duration-Hedge Ratio

We consider the duration-hedge ratio (also referred to as the price sensitivity hedge ratio)of an interest rate dependent asset such as a bond portfolio or a money market security.The hedge ratio calculates the number if relevant interest rate futures contracts which needto be brought (or sold) in order to hedge against price changes resulting from small parallelshifts in the interest rate curve.

Problems with Duration based hedging

The notation of duration provides a simple approach to the hedging of interest rate basedassets. However, the hedge produced is often far from perfect since the duration measureonly takes into account the ‘linear’ part of the pricing function and further assumes thatthe shifts in the interest rate curve will always be parallel. In an attempt to deal withthe ‘non-linear’ part of the pricing function the notion of convexity will be introduced.Non-parallel shifts of the interest rate curve are usually handled by breaking the curve intodifferent time segments and hedging the interest rate risk on each of these segments. Suchan approach is sometimes referred to as GAP management.

29

Page 37: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Fundamental Theory of Bonds Chapter 3

Remark The use of the hedge ratio for bonds an analogous to ‘delta hedging’ for equi-ties. That is, it hedges the linear (or parallel) risk associated with the interest rate curveand does not take into effect the non-linear dependency of the assets on the underlyinginterest rate(s). Hence, in practice the hedge generated from the hedge ratio will need tobe continually monitored and rebalanced accordingly.

Another issue which effects the performance of duration based hedging is when the con-tract can to settled using a number of underlying interest rate assets. One such instance isthe hedging of US Treasury futures. In such a case the hedger needs to estimate which ofthe available bonds is likely to be the cheaper to delivery at expiry. With this assumptionthe hedge can be evaluated in a normal fashion. If before the expiry of the contract theinterest rate environment changes such that a different bond is likely to be delivered thenthen hedge will need to be adjusted accordingly.

Convexity

Duration based hedging though straight-forward to apply will not lead to a perfect hedge.Further, the hedge produced will strictly only apply to parallel shifts in the interest ratecurve. For non-parallel shifts of the interest rate curve duration based methods will give agood approximation for small shifts of the interest rate. For larger shifts non-linear effectsof the interest rate curve will render the duration an impractical guide for effective evalu-ation and hedging applications.

For exactly the same reason as the gradient of a smooth functions tangent is locally agood approximation for the function itself. The price of an interest dependent instrumentfor small (parrallel) shifts of the interest rate curve depends almost entirely on the dura-tion. But for larger shifts or non-linear shifts in the interest rate curve the duration willnot account even approximately for the total change in the bonds price. In order to betterdeal with should instances the notion of convexity is introduced.

In order to deal with larger shifts or non-linear shifts in the interest rate curve we considerthe ’next term of the expansion’ of a bonds price function and introduce the notion knownas convexity. The convexity is formally given by:

C =1

B

∂2B

∂y2=

∑ni=1 pit

2i exp(−yti)

B

where B is the assets price, pi is the ith interest payments at time ti and y is the yield ofthe investment. Then the percentage change in the interest dependent asset price of shiftsof the interest rate curve taking into account the convexity of the asset is given by:

∆B

B= −D∆y +

1

2C∆y2

Below we illustrate the effect which differing convexities can have on the bonds price/yieldratio.

30

Page 38: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Fundamental Theory of Bonds Chapter 3

Two bonds X and Y with differing convexities

31

Page 39: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Chapter 4

Yield of Fixed-Interest Bonds onInterest Payment Dates

Within this chapter we consider various bond metrics of Fixed-Interest Bonds which ex-hibit closed formulae. A Fixed-Interest bond is a bond which pays a fixed income (knownas the coupon or interest payment) usually at regular intervals during the life of the bond.

We cover simple yield to maturity (JGB), gross/net redemption yield, current price, hold-ing period return (US and UK), duration and yield curves according to expectation theory.To simplify our treatment we assume where appropriate that bond metrics are evaluatedon interest payment dates.

Remark In order to evaluate many of the bond metrics within this section it has beennecessary to solve a rational polynomial expression. In order to solve these expressions weapply the Bisection and Newton Raphson methods (Click here for more details).

4.1 Simple Yield to Maturity (for Japanese Govern-

ment Bonds (JGB))

In Japanese bond markets, the concept of simple interest is used when calculating the yieldto maturity (simple yield to maturity) rather than the usual compound interest method(redemption yield). The simple yield to maturity is given by:

Simple yield to maturity =D

P+

(100− P

P× 1

n

)(4.1.1)

where,

� P = current price (including accrued interest)

� D = annual coupon payable in half-yearly installments

� n = outstanding term to redemption in years expressed in decimal format (i.e. 3years 6 months = 3.5)

32

Page 40: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Yield of Fixed-Interest Bonds on Interest Payment DatesChapter 4

Our Implementation

Within our class we implemented the Simple Yield to maturity within:

� FixedInterestBonds.simpleYieldToMaturity(double,double, double)

Notation Suppose that the rate of interest is i per interval. Then the present value an,of this series of payments is given by:

an =1

(1 + i)+

1

(1 + i)2+ · · ·+ 1

(1 + i)n=

1− (1 + i)−n

i(4.1.2)

From now on we denote by an, a series of payments of one per interval payable in arrearsfor n intervals.

4.2 Gross Redemption Yield and Current Price

Using the same notation as above, for an interest payment date the gross redemption yieldis defined as 2i where:

2i =D

P+

(100− P

P× 2i

(1 + i)2n − 1

)(4.2.3)

Remark It is usual in the US and the UK to calculate and express redemption yield asa yield per annum, convertible half-yearly.

If there is less than half a year to the next coupon payment, then the equation of value atthe present time is:

P =1

(1 + i)2l

(D1 +

D

2a2m +

100

(1 + i)2m

)(4.2.4)

where, D1 is the next interest payment, D is the annum coupon paid in half-yearly install-ments, l is the period to next payment (in years), m is the period from the next interestpayment to the redemption date (in years) and a2m is given by (4.1.2).

Remark For a UK gilt which are ex-dividend, we can set D1 = 0, because the nextinterest payment will not be received by a buyer.

Algorithm used to solve these equations

In order to find the solutions 2i, respectively i of the above equations (4.2.3), (4.2.4);we have used a combination of the Bisection and Newton-Raphson methods for finding theroots of an equation of one variable. After choosing an interval in which i lies (in almostall instances i will lie in the interval (0, 1)), our algorithm takes a Bisection step wheneverNewton-Raphson would take the solutions out of the chosen bounds, or whenever Newton-Raphson “doesn’t converge rapidly enough”.

33

Page 41: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Yield of Fixed-Interest Bonds on Interest Payment DatesChapter 4

Our Implementation

Within our implementation we have implemented methods by which the above two for-mulea can be solved (and hence the yield found) by application of a combination of theBisection and Newton-Raphson methods. In particular, we have provided the following:

� FixedInterestBonds.grossRedemptionYield(double, double, int) - Calculates the grossredemption yield of a fixed-interest bond on an interest payment date with an in-teger number of years until maturity by solving the equation (4.2.3) by applying acombination of the Bisection and Newton-Raphson methods. That is, we evaluatethe total (annual) yield of the fixed interest bond from now until maturity where thetax implications of the investor are not taken into account.

� FixedInterestBonds.grossRedemptionYield(double, double, int, double, double) - Of-fers the same functionality as the method listed directly above except that here weare able to specify the algorithm specific equation solving parameters such as theupper bound of the solution and the precision used.

� FixedInterestBonds.grossRedemptionYield(double, double, double, int, double) - Cal-culates the gross redemption yield if there is less than half a year to the next couponpayment of the fixed interest bond by solving the equation (4.2.4) via a combinationof the Bisection and Newton-Raphson methods.

� FixedInterestBonds.grossRedemptionYield(double, double, double, int, double, dou-ble, double) - Offers the same functionality as the method listed directly above exceptthat here we are able to specify the algorithm specific equation solving parameters,namely the upper bound of the solution and the precision by which the result isreturned.

We also implement a formulae which relates the gross redemption yield to the price of afixed interest bond, namely the method:

� FixedInterestBonds.currentPrice(double,double,int)

4.3 Net Redemption Yield (excluding CGT)

For an interest payment date, the net redemption yield is 2i where i is a solution of thefollowing equation:

P = (1− t)D

2a2n +

100

(1 + i)2n(4.3.5)

where t is the investor’s rate of tax on income expressed in decimal format (i.e. 1 percent= 0.01), D is the annual coupon paid in half-yearly installments and an is given by (4.1.2).

Remark In short, the net redemption yield is just the gross redemption yield minus

34

Page 42: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Yield of Fixed-Interest Bonds on Interest Payment DatesChapter 4

the effect of the investors income tax on the investment income.

Algorithm used to solve these equations

In order to find the solution 2i, respectively i of the equation (4.3.5) we have used acombination of the Bisection and Newton-Raphson methods for finding the root of anequation of one variable. After choosing an interval in which i lies (in almost all instancesi will lie in the interval (0, 1)), our algorithm takes a Bisection step whenever Newton-Raphson would take the solutions out of the chosen bounds, or whenever Newton-Raphson“doesn’t converge rapidly enough”.

Our Implementation

Within our implementation we have implemented methods by which the above formulacan be solved (and hence the yield found) by application of a combination of the Bisectionand Newton-Raphson methods. In particular, we have provided the following:

� FixedInterestBonds.netRedemptionYield(double, double, int) - Calculates the net re-demption yield of a fixed-interest bond on an interest payment date with an integernumber of years until maturity by solving the equation (4.2.3) via a combinationof the Bisection and Newton-Raphson methods. That is, we evaluate the total (an-nual) yield of the fixed interest bond from now until maturity where the income taximplications from the investor are taken into account.

� FixedInterestBonds.netRedemptionYield(double, double, int, double, double) - Of-fers the same functionality as the method listed directly above except that here weare able to specify the algorithm specific equation solving parameters, namely theupper bound of the solution and the precision by which the result is returned.

4.4 Holding Period Return (US and UK)

The holding period return is the yield over the period that the bond was held by theinvestor. Here we are able to evaluate the holding period return on an coupon paymentdate. That is, on an interest payment date the holding period half-yearly return j is givenby the following equation:

P =D

2

(1− (1 + j)−2n

j

)+

S

(1 + j)2n(4.4.6)

where P is the purchase price, D is the annual coupon payable in half-yearly installments,n is the (whole) number of years for which the bond is held and S is the market price atwhich the investor can sell the bond.

Remark The holding period return is used widely within the UK and US bond mar-kets.

35

Page 43: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Yield of Fixed-Interest Bonds on Interest Payment DatesChapter 4

Algorithm used to solve these equations

In order to find the solution j, of the equation (4.4.6) we have used a combination ofthe Bisection and Newton-Raphson methods for finding the root of an equation of onevariable. After choosing an interval in which j lies, our algorithm takes a Bisection stepwhenever Newton-Raphson would take the solutions out of the chosen bounds, or wheneverNewton-Raphson “doesn’t converge rapidly enough”.

Our Implementation

Within our implementation we have implemented methods by which the above formula(4.4.6), can be solved (and hence the holding period return found) by application of a com-bination of the Bisection and Newton-Raphson methods. In particular, we have providedthe following:

� FixedInterestBonds.holdingPeriodReturn(double, double, double, int) - Calculatesthe (half-yearly) holding period return of a fixed-interest bond on an interest paymentdate when the bond is held for a (whole) number of years by solving the equation(4.4.6) via a combination of the Bisection and Newton-Raphson methods.

� FixedInterestBonds.holdingPeriodReturn(double, double, double, int, double, dou-ble) - Offers the same functionality as the method listed directly above except thathere we are able to specify the algorithm specific equation solving parameters, namelythe upper bound of the solution and the precision by which the result is returned.

4.5 Bisection and Newton Raphson

Throughout our treatment of fixed-interest bonds we have been required to find solutionsto polynomial equations. Generally speaking, this cannot be done analytically and so wehave relied upon the Bisection and Newton-Raphson methods which are detailed below.First we briefly remark on bracketing a solution to an equation.

4.5.1 Bracketing One Dimensional Equations

If you are given an arbitrary function then there is no certain way of deciding a range inwhich a solution exists or even of determining if it has roots at all.

Notation We say that a root is bracketed in the interval (a, b) if f(a) and f(b) haveopposite signs.

If the function is continuous then within a bracketed region there must exist at least oneroot by the intermediate value theorem. For a discontinuous function we cannot guaranteethe existence of a root but from a numerical point of view the behavior is indistinguishable

36

Page 44: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Yield of Fixed-Interest Bonds on Interest Payment DatesChapter 4

from the continuous case. That is singular points where the function changes sign areidentical to real roots for a computer based algorithm.

Remarks

� To find a bracketed interval we proceed by taking different points and just evaluatingthe function. Naturally, for a given problem the bracketed interval may be known apriori.

� Once we know an interval in which a solution is known to exist we can apply severalclassical procedures which should converge to a root. These proceed with variousrates and sureness to a root.

4.5.2 Bisection Method

Given a bracketed interval the bisection method will always converge to a solution. Givenan interval (x1, x2) we choose a point halfway between x1 and x2, and evaluate the func-tion. We replace either x1 or x2 depending upon which point given the same sign whenthe function is evaluated there. And so on...

Clearly after n iterations the root is known to be within an interval of size εn where:

εn =|x1 − x2|

2n(4.5.7)

Thus, we have:

n = log2

|x2 − x1|ε

(4.5.8)

where ε is the desired ending tolerance.

4.5.3 Newton-Raphson Method

The Newton-Raphson method is the best known method for finding the roots of an equa-tion. This procedure can be generalized in various directions, in particular it can be appliedto finding solutions of non-linear equations. The reader should note that the assumptionsrequired by the Newton-Raphson method differ from the Bisection method in the followingways:

� The solution does not need to be bracketed but a point sufficiently close to a solutionmust be chosen

� The derivative of the interpolated function needs to be evaluated at a sequence ofpoints

� The method may not converge if the initial point is not sufficient close to a solutionor the interpolated function has certain pathological features such as it oscillates veryquickly close to a solution

37

Page 45: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Yield of Fixed-Interest Bonds on Interest Payment DatesChapter 4

Assuming that an initial estimate x0 of the solution to an equation f(x) = 0 is known, theNewton-Raphson method will produce a sequence of values {xn : n ∈ N}, which will shouldconverge. In particular, when f(x) is a rational function and x0 is chosen sufficiently wellthis sequence will always converge. If the algorithm fails to give a solution which in thecase of polynomials means xn → ±∞ or the sequence is stuck in something like a loop, thenwe repeat the process with another initial point. By calculating the derivative f ′(x)|x=x0

at the point x0, we draw the tangent to the curve at x0 and then trace this line down tothe x-axis which will give us our second point x1. Repeating this process will result in thedesired convergent sequence. In short, we use this iterative formula:

xn+1 = xn −f(xn)

f ′(xn), n ≥ 0 (4.5.9)

38

Page 46: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Chapter 5

Interest Calculations

Since calculations related to interest payments play such a fundamental role in the theoryof bonds we have decided to include an entire chapter (and corresponding software module)which covers various topics related to interest calculations. Within this chapter we detailthe functionality relating to the interest bearing investments which has been implementedwithin the interest module.

5.1 Preliminaries and Notation

5.1.1 Preliminaries

The notions of compound and simple interest form the foundations of investment math-ematics. These notion are so central because money has a ‘time value’ because it earnsinterest. That is, if left to compound the money earns interest on the principal sum andalso interest on the interest.

The related mathematical objects to interest are those of exponents, arithmetic seriesand geometric series. Below we summarize the essential formulae of exponents, arithmeticseries and geometric series so that a developer may more modify our interest relations ifthey do not fit your exact requirements.

Exponents

Given any positive numbers x, y, and real numbers n, m, we have the following law ofexponents:

� x0 = 1, (−x)0 = 0

� (−x)n = (−1)nxn

� xnxm = xn+m

� xm

xn = xm−n

39

Page 47: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Interest Calculations Chapter 5

� (xm)n = xmn

� (xy)n = xnyn

(xy

)n

= xn

yn

Arithmetic Series

An arithmetic series An, is given by:

An = a + (a + b) + (a + 2b) + . . . + (a + (n− 1)b) (5.1.1)

where a ∈ R, R ∈ R the common difference and n ∈ N is the number of term in the series.By induction it follows that the sum of this series is given by:

An = an +n(n− 1)b

2(5.1.2)

Geometric Series

A finite geometric series Sn, is given by:

Sn = b + bR + bR2 + bR3 + . . . + bRn−1 (5.1.3)

where b ∈ R, R ∈ R the common ratio and n ∈ N is the number a terms in the series. Byinduction it follows that the sum of this series is:

Sn =b(1−Rn)

(1−R)(5.1.4)

An infinite geometric series is an indefinite sum of terms is denoted by:

S = b + bR2 + bR3 + . . . (5.1.5)

where ‘. . .’ denotes that the sum extends in a similar fashion indefinitely. If the modulus(i.e. absolute value) of R, is greater than one then the series does not have a finite sumand is said to diverge. If the modulus a R is strictly less than one then the infinite sumwill converge to some finite value. That is, the sum will get closer and closer to some finitevalue as we sum more and more terms. The sum of such an infinite series is given by:

S =b

1−R(5.1.6)

5.1.2 Notation

Throughout this documentation we will use the following notation:

� p = number of periods of time

40

Page 48: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Interest Calculations Chapter 5

� d(0) = initial deposit or investment

� d(t) = accumulated values after t periods of time

� dr(t) = the real worth of the investment after t periods of time

� i = rate of interest expressed in decimal form, i.e. 1% = 0.01

� i(p) = p-yearly rate of interest

� j(p) = effective interest

� r = rate of depreciation expressed in a decimal form, i.e. 1% = 0.01

� sn = accumulated value of an annuity certain

� an = present value of an annuity certain

� f = rate of inflation (annual) expressed in decimal form, i.e. 1% = 0.01

5.2 Simple Interest

5.2.1 Basic formula

The simple interest is calculated using the following formula:

d(1) = d(0)(1 + i) (5.2.7)

That is, we calculate d(1) for i and d(0) given.

Example If $200 is deposited into a bank account with a yearly interest rate of 5%,after 1 year the accumulated sum (in $) is:

d(1) = 200(1 + 0.05) = 210 dollars

5.2.2 Real worth

The real worth dr(1), of a fixed interest bearing investment over a given period where theinitial deposit was d(0) is given by:

dr(1) =d(0)

1 + f(1 + i) (5.2.8)

where f is the (‘constant’) rate of inflation over the period and i is the (fixed) rate ofinterest over the period.

41

Page 49: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Interest Calculations Chapter 5

5.2.3 Real return

The real return j, of an interest bearing investment over a given period is given by:

j =i− f

1 + f(5.2.9)

where i is the fixed interest over the period and f is the (‘fixed’) rate of inflation.

We also provide methods which calculate/estimate the average inflation and interest rateover a number of periods.

5.3 Compound Interest

5.3.1 Accumulated values

The accumulated value d(p) of an interest bearing investment d(0), after p periods of timewhere the fixed rate of interest is i, is given by:

d(p) = d(0) (1 + i)p (5.3.10)

We also provide a method which calculates the amount which an investor must deposit inorder to receive a given sum after a certain number of years.

Example If an investor wishes to receive $10, 000 from an fixed interest bearing in-vestment which pays 5% after 5 years then they most deposit today:

10000

(1 + 0.05)5= $7, 835.26

5.3.2 Real worth

The real worth of an fixed interest bearing investment after p periods of time, where theannual rate of inflation is f and the initial deposit is d(0). The fixed interest rate is i perinterval of time where each interval consists of n days. We provide formulae for the realworth according to the day count conventions in Europe, UK and Japan for the quotationof the annual rate of inflation:

� Europe

dr(p) =d(0)

(1 + f)np360

(1 + i)p (5.3.11)

� UK and Japan

dr(p) =d(0)

(1 + f)np365

(1 + i)p (5.3.12)

42

Page 50: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Interest Calculations Chapter 5

We also provide the general form when the annual inflation is quoted with respectto m days. Then the real worth is given by:

dr(p) =d(0)

(1 + f)npm

(1 + i)p (5.3.13)

We also consider in the general case the problem of determining the initial depositnecessary in order to get a pre-determined real worth from a fixed interest bearinginvestment. If the annual inflation is quoted with respect to m days and the final realworth of the investment after p periods is required to be M then the initial depositmust be:

M(1 + f)npm

(1 + i)p

5.3.3 Real return

The real return j of an interest bearing investment is over p time periods is calculatedwhere the annual rate of inflation f is assumed to be constant and the interest rate is i perperiod. We assume that each time period has n days, and the annual inflation is quotedin accordance with European, UK and Japanese conventions:

� Euro

j =(1 + i)p

(1 + f)np360

− 1 (5.3.14)

� UK and Japan

j =(1 + i)p

(1 + f)np365

− 1 (5.3.15)

We also provide thew general form where the annual inflation is quoted with respectto m days. Then the real return is given by:

j =(1 + i)p

(1 + f)npm

− 1 (5.3.16)

We also provide the general form when the annual inflation is quoted with respect to mdays. then the real return is given by:

j =1 + i

(1 + f)nm

− 1 (5.3.17)

5.3.4 Depreciation

Physical assets which are owned by a corporation (e.g. cars) often decrease in value withtime. This process is referred to as depreciation. Estimates of the rate of depreciation areuseful since for accounting purposes this unrealized loss can be set against a companiesprofits.

43

Page 51: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Interest Calculations Chapter 5

The depreciation rate is expressed as the percentage decrease in the assets market valueover a period of time. We offer methods which calculate the percentage decrease in thebook value of a collection of assets over one or many time periods.

If P0 is an assets value (often referred to as book value) at time 0 and Pt is the assetsvalue (or expected value) after t periods of time then the depreciation rate per timeperiod is given by:

Pt = P0 (1− r)t (5.3.18)

Example: The cost of an asset is known to be 20,000 and its salvage value is estimatedat 8,000 after a useful life of 5 years.

Depreciation of asset = 1−(

8, 000

20, 000

) 15

We also provide a method which calculates the book value of an asset after a number oftime periods in which the depreciation rate may differ. If the book value P0, of an assetdeclines with a varying rate, ri being the rate of depreciation of the ith period we willobtain the book value Pt at the end of t years:

Pt = P0 (1− r1) (1− r2) · · · (1− rt) = P0

t∏i=1

(1− ri) (5.3.19)

5.3.5 Force of interest

If the nominal rate is continuously compounded from p to infinity, the resultant annualconvertible rate of interest is referred to as the force of interest and is denoted by thesymbol δ. We calculate δ using the following expression:

exp(1)δ = 1 + i

where exp(1) denotes the exponential function evaluated at 1 (i.e. 2.718 . . .).

Therefore,δ = ln(1 + i) (5.3.20)

If the force of interest δ is quoted then the following relation can be useful:

d(t) = d(0) exp(1)tδ (5.3.21)

5.4 Effective and Nominal Interests

5.4.1 Effective rate of interest

We convert the effective p-yearly rate into the q-yearly rate. If j(p) is the p-yearly rate,then the q-yearly rate of interest is j(q), where:

(j(p) + 1)p = (j(q) + 1)q

44

Page 52: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Interest Calculations Chapter 5

That is,j(q) = (j(p) + 1)

pq − 1 (5.4.22)

but this is only the interest over the qth period. Therefore, the interest compounded overthe qth periods to give the annual rate is:

j(q) = q (j(p) + 1)pq − q (5.4.23)

5.4.2 Real return

We calculate the real return jq of a q-yearly rate, knowing the p-yearly rate and the annualrate of inflation:

jq = q

(1 + i(p)

p

) pq

(1 + f)1q

− q (5.4.24)

5.4.3 Nominal rate of interest

If the effective rate of interest is expressed in terms of 1/p of a year, it is often convertedto an annual rate by simply multiplying by p. The rate of interest i per annum is p-yearly convertible. The rate of interest quoted in this way is known as the nominal rate ofinterest. If the effective annual rate is i, the nominal rate of interest convertible p-yearlyis i(p), where: (

1 +i(p)

p

)p

= 1 + i

5.5 Net Present value

To calculate the initial amount of money d(0) which has to be invested in order to accu-mulate the final sum d(t), where t is the number of periods and i is the interest over eachof these periods (assumed to be constant), we use:

d(0) =d(t)

(1 + i)t(5.5.25)

Remark The constant t need not to be an integer.

The initial amount of money d(0), which needs to be invested in order to accumulatea final worth dr(t), after t periods of time, if the annual rate of inflation is f and the periodof time has p days:

d(0) =(1 + f)

pt360 dr(t)

(1 + i)t(5.5.26)

where i in the interest rate paid over each period.

Remark Present values provides a method of comparing monies available at different

45

Page 53: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Interest Calculations Chapter 5

points in time. The calculation of the present value of future sums of money is referred toas discounting.

Example: You need to decide between two business opportunities. The first opportu-nity will pay $700 in 4 year’s time and the second opportunity will pay $850 in 6, year’stime. You have been advised to discount these future sums by using the interest rate of 8%.

By substitution we are able to calculate a present value for each of these future sums,which gives:

� First opportunity: d0 = 514.52

� Second opportunity: d0 = 535.64

Therefore, the second business opportunity is preferable to the first opportunity.

5.6 Annuities

An annuity is a series of periodic payments (or cash flows) of equal size. Annuities occurwithin a number of different investment scenarios including:

� Bond Coupon’s

� Social Security Payments

� Retirement Plan payments

Within this section we consider how the accumulated value and the present value of anannuity is evaluated.

5.6.1 Accumulated Values of an Annuity

The accumulated value

The accumulated value of a series sn of payments of one per interval, payable in arrearsfor n intervals (where i is the interest and n is the number of intervals) is:

sn =(1 + i)n − 1

i(5.6.27)

Series of payments

Series of payments of one per interval payable in advance for n intervals. Calculate theaccumulated value Sn of this series of payments:

Sn = (1 + i)sn (5.6.28)

46

Page 54: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Interest Calculations Chapter 5

5.6.2 Present Value of Annuities

The following types of annuity’s are particularly important in investments and it is thereforeuseful to know the general formulas for their present values.

Series of payments in arrears

Series cash of payments of one per intervals payable in arrears for n intervalsDenoted by the symbol an. The fixed rate of interest i is given. The present value an, isgiven by:

an = i−1 − (1 + i)−n (5.6.29)

where i is the interest rate paid on cash.

Remark In the case of large investment banks the interest rate paid on cash is known asthe risk free interest rate which we be approximately equal to the yield paid on near datedlocally denominated government bonds.

Series of payments in advance

Series of cash payments of one per interval payable in advance for n intervalsThe present value of this series is denoted by the symbol An, and is given by:

An = (1 + i)an (5.6.30)

where i in the interest rate paid on cash.

Infinite series of payments in arrears

Infinite series of cash payments made at the end of each interval The initial pay-ment is d1 and each subsequent payment is (1 + g) times the previous payment.

The present value is given by:

Present value =d1

i− g(5.6.31)

where i in the interest rate paid on cash.

Remarks

� The present value converges if and only if i is greater than g. Hence, our methodthrows an exception if g is less than or equal to i since clearly this situation cannotoccur.

� When g = 0 (i.e. there is zero growth) the present value of an infinite series ofpayments known as perpetuity.

47

Page 55: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Interest Calculations Chapter 5

Increasing annuity

An increasing annuity in which the first payment is one after one interval, thesecond payment is two after two intervals and so on... with a final payment of nafter n intervals. The present value of this series is denoted by (Ia)n, where:

(Ia)n =An − nvn

i(5.6.32)

where v = 11+i

.

5.6.3 Series of multiple payments per interval in arrears

Series of payments of one per interval payable p times per interval in arrearsfor n intervals. If the constants n, p, i are given then the present value is denoted bya

(p)n , is given by:

a(p)n =

i

i(p)an (5.6.33)

Series in multiple payments per interval in advance

Series of payments of one per intervals payable p times per intervals in advancefor one interval. Given the constants i, p and n, the present value is denoted by A

(p)n

and is given by:

A(p)n =

(i

i(p)+

i

p

)an (5.6.34)

5.7 Yield (internal rate)

If an investment X provides Xp money at the end of n years, then the equation of value is:

X(1 + i)n = Xp (5.7.35)

The rate of interest for which this equation of value is satisfied is the yield.

5.7.1 Finding the yield

Let a(k) be a function defined on the natural numbers N with values in {0, 1}, a(n) = 0if the payment has not been performed in the n-th period of time and a(n) = 1, if thepayment has been performed in the n-th period of time.

Assuming that the function a(k) for {k ∈ N : 1 ≤ k ≤ n}, and i the fixed interestrate are known we can calculate the yield j, using the following formula:

a(1)(1 + i) + a(2)(1 + i)2 + · · ·+ a(n)(1 + i)n = (1 + j)n (5.7.36)

Alternatively, if the initial investment d(0) and the amount repaid after n periods of timed(n) is known. We can calculate the yield j, by:

d(0)(1 + j)n = d(n) (5.7.37)

48

Page 56: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Interest Calculations Chapter 5

5.7.2 The relationship between real and nominal yield

If f is the annual rate of inflation and i is the effective annual nominal yield. Then thereal yield j is given by:

j =i− 1

1 + f(5.7.38)

5.8 Repo agreements

A repo agreement is an agreement between two parties where one party agrees to sell andthen buy back an asset at a later date from the counter party.

Remark The advantage of such an agreement is that it allows a party to temporar-ily borrow cash from a counter party who if the contract to structured correctly assumesvery little risk.

We denote:

� f = the inflation during the period of the repo agreement. For example, if the annualinflation runs at 6% during a six month repo agreement then the inflation during theperiod is 3%

� x = initial purchase/sale price when the repo contract in entered into

� Xf = final payment made at the end of the repo agreement

� X = final worth of the investment

Then the real return j, from a repo agreement is given by:

x(1 + j) = X =Xf

1 + f

Hence, the real return from the repo agreement is given by:

j =Xf

(1 + f)x− 1 (5.8.39)

49

Page 57: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Chapter 6

Programmer’s Guide for Microsoftr

Office

This chapter describes the steps to take in order to integrate WebCab Bonds with most Officedocuments, such as Excel worksheets, and Access documents. The integration is achieved boththrough VBA (Visual Basic for Application) code and features specific to the Office Applicationyou are using to write your documents. The information in this chapter applies equally toMicrosoft Office 2000, XP, and 2003 Applications and documents.

6.1 Developing with VBA from Office

This section describes how to write a VBA client for a business class documented in theAPI Reference for this product. The steps below are the same across all Microsoft OfficeApplications (Word, Excel, Access etc.) and involve using the Visual Basic Editor andwriting several lines of code:

1. Open the Visual Basic Editor

2. Add a Code Module

3. Declare a Subroutine

4. Add a Reference to This Product

5. Declare a Class Instance Variable

6. Create a Class Instance

7. Call a Class Method

8. Display the Method Result

9. Run the Subroutine

50

Page 58: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.1: Starting the Visual Basic Editor in Excel

6.1.1 Open the Visual Basic Editor

In order to add VBA code to your Office document, you will first need to open the VisualBasic Editor, by going to the Tools | Macro | Visual Basic Editor menu, as shown in figure6.1.

6.1.2 Add a Code Module

In the upper-left corner of the Visual Basic Editor window, you can find all Office objectsassociated with your document. Right click any of the objects and select Insert | Module,as shown in Fig. 6.2 in order to add a new VBA module to your project. A code windowwill appear, where you will be writing the code that will enable you to use this product’sfunctionality.

6.1.3 Declare a Subroutine

The first step in writing the code, which makes use of the functionality provided by thisproduct is to declare a subroutine, which can then be run directly from your Office Appli-cation. To declare a subroutine, use the Sub and End Sub keywords and the name you wishto assign to this subroutine. For example, in order to declare a subroutine named run, youwould write the code displayed in Fig. 6.3.

51

Page 59: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.2: Adding a module to a VBAProject

Fig. 6.3: Declaring a subroutine named run in VBA

6.1.4 Add a Reference to This Product

Adding a reference to this product is required only once for every Office document that usesfunctionality provided by this product. This step will enable VBA code auto-completionfor all business clases and methods that belong to this product, saving you time typingand browsing the API Reference. Also, it will speed up all calls to this product’s methods,increasing the overall performance of your project.

52

Page 60: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.4: Opening the “References” window in the Visual Basic Editor for Office

Fig. 6.5: Selecting a reference to a WebCab product, here ‘Functions’

To add a reference to this product, go to the Tools | References... menu as shown inFig. 6.4 in order to open the “References” dialog window. Scroll down and select the entrynamed WebCab Bonds Demo from the list of available references in the dialog window andthen click OK. Figure 6.5 shows how to add a reference to WebCab Functions Demo.

53

Page 61: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.6: Creating a new instance of a class named “Interpolation”

6.1.5 Declare a Class Instance Variable

The API Reference for this product describes all business classes, their methods and prop-erties, and offers advice on how to use each of them. You can browse the API Referencefrom the Start Menu at Programs | WebCab Components | Bonds for .NET | COM | APIReference. In order to call methods of a business class listed in the API Reference, youneed to declare a variable to hold a reference to its instance.

Write a Dim statement to declare a variable of the same type as the business class that youwish to make calls to. For example, if you wish to call methods belonging to a businessclass named “Interpolation” and declare a variable of this type named instance, you wouldwrite the following:

Dim instance As Interpolation

6.1.6 Create a Class Instance

In order to create an instance of a business class listed in the API Reference, you will haveto write code that connects to its corresponding COM server1.

Use the Set keyword in order to assign the class instance to the variable you have de-clared in the previous step. The Set keyword is required in class instance assignments,as omitting this keyword would result in a run-time error. The reference assigned to thisinstance is created by writing the New keyword, followed by the name of the same businessclass you used to declare the variable.

1“COM server” is a generic term used to describe a COM interface, which provides functionality to VBand VBA applications.

54

Page 62: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

For example, assume you wish to create an instance of a business class named Interpola-tion, which is located in the WebCab Functions for .NET product. Figure 6.6 shows howto create an instance of this class and how to assign it to the instance variable declaredin the step above.

6.1.7 Call a Class Method

In order to call a method belonging to a business class for which you have created aninstance, you can use the name of the method as listed in the API Reference and appendit to the name of the variable that holds the class instance, separating it with a period.For example, in order to call a method named MyMethod, you could write the followingline of code:

result = instance.MyMethod (parameter-values)

where parameter-values are the ordered values of the parameters separated by a comma.The actual type of these parameters and that of the results variable depends on the signa-ture (i.e. the return type and parameter types) of the MyMethod method.

Remark For a more detailed Visual Basic example of how to invoke a method, seesection 6.1.10.

6.1.8 Display the Method Result

To see what the result of the method call was, you can display it inside a window by callingthe MsgBox function, as shown below:

MsgBox "The result of the method call was " & result

This line of code will display a small dialog window containing the result of the methodcall.

6.1.9 Run the Subroutine

After having finished writing the subroutine code as described in the steps below, you canrun the subroutine. There are several ways to run a subroutine, two of which are describedbelow:

1. Type F5 in the Visual Basic EditorYou can run your subroutine by placing the editing cursor within its body (i.e.between the Sub and End Sub keywords) and pressing the F5 key. This will instantlyexecute the subroutine, bringing up the result window.

55

Page 63: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.7: Opening the “Macro” window from the menu in Excel.

2. Run the Soubroutine as a MacroYou can run the subroutine even after having closed the Visual Basic Editor, directlyfrom the Office Application you are using. Go to the Tools | Macro | Macros... menu,as shown in Fig. 6.7 to open the “Macro” dialog window. Select the macro, whichhas the same name as your subroutine and click Run (see Fig. 6.8).

56

Page 64: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.8: Running a subroutine macro named run from Office.

57

Page 65: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

' Declaring a subroutine named `run'Sub run()

Dim instance As Interpolation' Creating an new `Interpolation' instanceSet instance = New Interpolation

' Declaring the first parameter (a double array)Dim x(0 To 4) As Doublex(0) = 1x(1) = 2x(2) = 3x(3) = 4x(4) = 5

' Declaring the second parameter (a double array)Dim y(0 To 4) As Doubley(0) = 3y(1) = 2.4y(2) = 1.7y(3) = 1.4y(4) = 0.7

' Declaring the variable to hold the method resultDim result As Double

' Calling the `CubicSplinePointwise' method. All other' parameter values are being written here. The result' is stored in the `result' variable.result = instance.CubicSplinePointwise(x, y, -0.6, -0.7, 1.2)

' Printing the result inside a dialog windowMsgBox "The result of the method call was " & result

End Sub

Table 6.1: Generic Office VBA Example

6.1.10 A Generic VBA Example for Office

In this section we provide the complete VBA source code for a subroutine named run,which makes a call to a method in a business class and prints the result of the method callinside a window. The same steps mentioned above are being followed in this example.

The code in table 6.1 calls a method named CubicSplinePointwise, belonging to the Interpo-lation business class in the WebCab Functions product. This method takes five parameters,of which the first two are one-dimensional arrays and the last three are double values. The

58

Page 66: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

method returns a double value.

6.2 Integrating with Microsoft Excel

This section is dedicated exclusively to Microsoft Excel users, who wish to tightly andseamlessly integrate the functionality provided by this product directly into Excel. At theend of this section, you will have learned how to create your own user-defined functions,which you can call directly from your worksheets as formulas or from the Insert | Function...menu. The following steps describe completely how to achieve integration of this product’sfunctionality within Excel:

1. Open the Visual Basic Editor

2. Add a Code Module

3. Declare a Function

4. Add a Reference to This Product

5. Declare a Class Instance Variable

6. Create a Class Instance

7. Call a Class Method

8. Store the Method Result as a Function Return Value

9. Insert the Function in your Worksheet

6.2.1 Open the Visual Basic Editor

First you will need to open the Visual Basic Editor, by going to the Tools | Macro | VisualBasic Editor menu, as shown in figure 6.1. The Visual Basic Editor will allow you to writethe necessary VBA code that uses the functionality provide by this product.

6.2.2 Add a Code Module

In the upper-left corner of the Visual Basic Editor window, you can find all Microsoft Excelobjects associated with your workbook. Right click any of the objects and select Insert |Module, as shown in Fig. 6.2 in order to add a new VBA module to the existing VisualBasic project. A code window will appear, where you will be writing the code that willenable you to use this product’s functionality.

59

Page 67: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.9: Declaring a function named “MyFunction” in VBA

6.2.3 Declare a Function

In the source code window, declare a function using the Function and End Function key-words. You can pick any name you wish for this function, as you will be able to call itdirectly from a worksheet, like a regular Excel formula. You can change the name of thefunction at any later time, by simply editing the function declaration. Figure 6.9 showshow to declare a function named MyFunction.

6.2.4 Add a Reference to This Product

As described in section 6.1.4, in order to add a reference to this product, you will need togo to the Tools | References... menu as shown in Fig. 6.4. This will open the “References”dialog window. Scroll down and select the entry named WebCab Bonds Demo from thelist of available references in the dialog window and then click OK. Figure 6.5 shows howto add a reference to WebCab Functions Demo.

6.2.5 Declare a Class Instance Variable

The API Reference for this product details all business classes, their methods and proper-ties, and gives advice on how to use each of them. You can browse the API Reference fromthe Start Menu at Programs | WebCab Components | Bonds for .NET | COM | API Reference.In order to call methods of a business class listed in the API Reference, you need to createa variable to hold a reference to its instance.

Write a Dim statement to declare a variable of the same type as the business class that youwish to make calls to. For example, if you wish to call methods belonging to a businessclass named “Interpolation” and declare a variable of this type named instance, you wouldwrite the following:

60

Page 68: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

Dim instance As Interpolation

6.2.6 Create a Class Instance

Use the Set keyword in order to assign the class instance to the variable you have declaredin the previous step. The Set keyword is required in class instance assignments, as omittingthis keyword would result in a run-time error. The reference assigned to this instance iscreated by writing the New keyword, followed by the name of the same business class youused to declare the variable.

For example, the Interpolation business class inside the WebCab.COM.Math.Interpolationnamespace has the following full name: WebCab.COM.Math.Interpolation.Interpolation.In order to create an instance of this class and assign it to the variable we have declaredin the previous step, we would write the following VBA code:

Set instance = New Interpolation

6.2.7 Call a Class Method

In order to call a method belonging to a business class for which you have created aninstance, you can use the name of the method as listed in the API Reference and appendit to the name of the variable that holds the class instance, separating it with a period.For example, in order to call a method named MyMethod, you would write the followingline of code:

instance.MyMethod (parameter-values)

where parameter-values are the ordered values of the parameters separated by a comma.The actual type of these parameters and that of the results variable depends on the signa-ture (i.e. the return type and parameter types) of the MyMethod method.

Remark For a more detailed Visual Basic example of how to invoke a method, seethe next section, 6.2.8.

6.2.8 Store the Method Result as a Function Return Value

The result of the method call must be stored as the method’s return value, by assigningthe method’s result to the the the name of the function itself, as shown below:

MyFunction = instance.MyMethod (parameter-values)

61

Page 69: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

' Declaring a function named `MyFunction'Function MyFunction()

Dim instance As Interpolation' Creating an instance of the `Interpolation' business classSet instance = New Interpolation

' Declaring the first parameter (a double array)Dim x(0 To 4) As Doublex(0) = 1x(1) = 2x(2) = 3x(3) = 4x(4) = 5

' Declaring the second parameter (a double array)Dim y(0 To 4) As Doubley(0) = 3y(1) = 2.4y(2) = 1.7y(3) = 1.4y(4) = 0.7

' Calling the `CubicSplinePointwise' method. All other' parameter values are being written here. The result' is stored as a return value for this function.MyFunction = instance.CubicSplinePointwise(x, y, -0.6, -0.7, 1.2)

End Function

Table 6.2: The VBA code for a user-defined function in Excel

The complete source code of a function named MyFunction is shown in table 6.2. Theexample calls the same method as the generic VBA example in section 6.1.10.

6.2.9 Insert the Function in your Worksheet

Switch back to the worksheet window and open the “Insert Function” window from theInsert | Function... menu (see Fig. 6.10). From the dialog window, click the drop-down listthat lists all the categories, and select the category named “User Defined”, as shown infigure 6.11.

The name of your function will appear in the list of user-defined functions. Select itand click the OK button (Fig. 6.12). A window named “Function Arguments” will appear,asking for values for the arguments. In case your function takes no arguments, as in ourexample above, simply click OK, as shown in figure 6.13.

62

Page 70: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.10: How to open the “Insert Function” window in Excel

Fig. 6.11: Selecting the “User Defined” category

The current cell value will contain the value of a formula, which calls the “MyFunction”function with no parameters. The result of the formula, listed in the fx formula bar, willbe printed inside the cell, as shown in figure 6.14. You can change the formula directlyfrom the formula bar, or by opening again the “Insert Function” window.

You can also add a reference to the formula directly from the worksheet, by typing thevalue of the formula directly into the cell, without opening the “Insert Function” window,

63

Page 71: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.12: Selecting the “MyFunction” user-defined function

Fig. 6.13: Inserting the “MyFunction” user-defined function into the worksheet

Fig. 6.14: The value returned by the “MyFunction” formula in an Excel worksheet

64

Page 72: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Microsoft Office Chapter 6

the same way you would call a standard Excel formula.

65

Page 73: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Chapter 7

Programmer’s Guide for VisualStudio 6

This chapter is dedicated to Visual Studio 6 developers, programming with either or both ofthe Visual Basic 6 and Visual C++ 6 languages. Using WebCab Bonds from these languagescomes down to connecting to a COM server and making calls to it. The first section is forVisual Basic 6 developers, while the second section is for Visual C++ 6 developers.

7.1 Developing with Visual Basic 6

This section describes the steps required to use this product from VB6. These steps arealways the same, irrespective of the type of project you are developing. In an example atthe end of this section, we also provide a generic Visual Basic example of how to connectto our components from a “Standard EXE” Project.

Assuming you have already started a new project or opened an existing project, hereare the steps required to connect and use a WebCab Bonds COM server:

1. Add a Reference to This Product

2. Declare a Class Instance Variable

3. Create a Class Instance

4. Call a Class Method

7.1.1 Add a Reference to This Product

Adding a reference to this product is required only once for every VB Project that usesfunctionality provided by this product. This step will enable VB code auto-completion forall business clases and methods that belong to this product, saving you time typing andbrowsing the API Reference. Also, it will speed up all calls to this product’s methods,increasing the overall performance of your project.

66

Page 74: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.1: Opening the “References” window in Visual Basic 6

To add a reference to this product, go to the Project | References... menu as shown inFig. 7.1 in order to open the “References” dialog window. Scroll down and select the entrynamed WebCab Bonds Demo from the list of available references in the dialog window andthen click OK. Figure 7.2 shows how to add a reference to WebCab Functions Demo.

7.1.2 Declare a Class Instance Variable

The API Reference for this product details all business classes, their methods and proper-ties, and gives advice on how to use each of them. You can browse the API Reference fromthe Start Menu at Programs | WebCab Components | Bonds for .NET | COM | API Reference.In order to call methods of a business class listed in the API Reference, you need to createa variable to hold a reference to its instance.

Write a Dim statement to declare a variable of the same type as the business class that youwish to make calls to. For example, if you wish to call methods belonging to a businessclass named “Interpolation” and declare a variable of this type named instance, you wouldwrite the following:

Dim instance As Interpolation

To avoid name clashing with other classes that may be named the same as the businessclass you are instantiating, you can prefix the name of the business class with the nameVB6 assigns to the COM reference to this product. Assuming the name of this reference

67

Page 75: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.2: Selecting a reference to a WebCab product, here WebCab Functions

is WebCab_COM_FunctionsDemo, the complete business class name would be referenced asfollows:

Dim instance As WebCab_COM_FunctionsDemo.Interpolation

7.1.3 Create a Class Instance

In order to create an instance of a business class listed in the API Reference, you will haveto write code that connects to its corresponding COM server. Use the Set keyword in orderto assign the class instance to the variable you have declared in the previous step. The Set

keyword is required in class instance assignments, as omitting this keyword would resultin a run-time error. The reference assigned to this instance is created by writing the New

keyword, followed by the name of the same business class you used to declare the variable.

For example, assume you wish to create an instance of a business class named Inter-polation, which is located in the WebCab Functions for .NET product. The following lineof code will create an instance of this class and assign it to the instance variable declaredin the step above:

Set instance = New Interpolation

68

Page 76: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

To avoid name clashing with other classes that may be named the same as the busi-ness class you are instantiating, you would use the complete name of the business class, asshown below:

Set instance = New WebCab_COM_FunctionsDemo.Interpolation

7.1.4 Call a Class Method

In order to call a method belonging to a business class for which you have created aninstance, you can use the name of the method as listed in the API Reference and appendit to the name of the variable that holds the class instance, the same way you would calla method or property in Visual Basic. For example, in order to call a method namedMyMethod, you could write the following line of code:

result = instance.MyMethod (parameter-values)

where parameter-values are the ordered values of the parameters separated by a comma.The actual type of these parameters and that of the results variable depends on the signa-ture (i.e. the return type and parameter types) of the MyMethod method.

Remark For a more detailed Visual Basic example of how to invoke a method see thefollowing section, ??.

7.1.5 Provide Functions for the Pricing Module

Within the Pricing Modules you may be requried to provide a user defined function inorder to describe certain price, volatility or interest rate models to be used within theapplication of the General Pricing module.

The following example demonstrate how to use your own defined functions for the meth-ods from within Pricing module. If you plan to use the SetHoLeeRateModel method fromwithin InterestDerivative class you will need to define your own drift function. By declar-ing a Class Module that implements InterestDerivative COM Interface and sending aninstance of this class to SetHoLeeRateModel method you will be able to submit your owndrift function.

The steps in creating a Class Module and writing the code which describes a functionare:

1. Add a Class ModuleRight-click the Project Explorer, and select Add | Class Module, as shown in figure .In the next window (Fig. 7.4), select Class Module and click OK.

69

Page 77: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.3: Adding a new Class Module to a Visual Basic 6 Project

Fig. 7.4: Selecting the type of Class Module to add to a Visual Basic 6 Project

70

Page 78: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

2. Implements the COM InterfaceUse the Implements VB6 keyword in order to have your class implement the FunctionCOM Interface. Here is how you implement this interface:

Implements WebCab_COM_Finance_Bonds_Pricing_Function

3. Write the FunctionIn order to provide a Declare a function named WebCab_COM_Finance_Bonds_Pricing_Function_GetValueAt

in order to express the value of your function at any point. Functions namedWebCab_COM_Finance_Bonds_Pricing_Function_Integrate for the integral of your func-tion and WebCab_COM_Finance_Bonds_Pricing_Function_IntegrateFrom are only de-clared here, but is not necessary to implement them. The full signatures of thesefunctions are shown in the source code example below:

Public Function WebCab_COM_Finance_Bonds_Pricing_Function_GetValueAt_

(ByVal x As Double) As DoubleFunction_GetValueAt = x * 0.01

End Function

Public Function WebCab_COM_Finance_Bonds_Pricing_Function_Integrate _(ByVal timeSteps As Long) As Surface

End Function

Public Function WebCab_COM_Finance_Bonds_Pricing_Function_IntegrateFrom_

(ByVal t0 As Double, ByVal timeSteps As Long) _As WebCab_COM_Finance_Bonds_Pricing_Function

End Function

Once you are done writing the Class Module that describes your one-dimensional function,you can create an instance of this class and send it as a parameter to the SetHoLeeRate-Model method, that belongs to the InterestDerivative COM server like in the source codebelow.

71

Page 79: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Private Sub Form_Load()' Declaring an instance of class InterestDerivativesDim instance As WebCab_COM_BondsDemo.InterestDerivatives' Initializing the instance of the class InterestDerivativesSet instance = New WebCabCOM_BondsDemo.InterestDerivatives

' Declaring an instance of the COM FunctionDim drift As WebCab_COM_Finance_Bonds_Pricing_Function' Initialize the drift variable with a instance of the Class1' (which contains our own implementation of the drift function)Set drift = New Class1

' Declaring the variable to hold the method resultDim priceCall As Double

' Here we set the contract which we are to priceCall instance.SetCapSpotContract(100, 2004.5, 0.05, 0.25, 2006)

' Here we set the price model usedCall instance.SetLognormalPriceModel(100)

' Here we set the volatility model usedCall instance.SetHullWhiteVolatilityModel(0.5, 0.08, 0.01, 0.03)

' Here we set the interest rate model used and we pass our own defined' drift function as the first parameterCall instance.SetHoLeeRateModel(drift, 0.01, 0.0125)

' Here we set number of simulations used within the Monte Carlo' simulationCall instance.RunSimulation(24, 1000, 2004.5)

' Here we read off the price once the Monte Carlo simulation has been' performedpriceCall = instance.GetPrice

' Printing the result in a Message BoxMsgBox "The calculated asset price is: " & priceCall

End Sub

7.2 Illustrating Visual Basic Examples

Within this section we provide a number of source code examples which demonstrate howto use our Bonds product inside a Visual Basic 6 application. These examples will illustrate

72

Page 80: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

how to use a variety of methods from different classes within the Bonds product which takea variety of parameter and return types.

Examples Provided

In particular we provide source code examples for the following methods:

� RealReturn(double, double) which returns a double

� WeightOfBonds(double[]) which returns a double array

Aim of Examples

The aim of these examples is to provide practical hand-on instruction as to exactly whatyou are required to input in order to use our Bonds product inside a Visual Basic project.Each example will invoke a method from a business class and return the result within amessage box. These examples will cover of the full range of parameter and return typewhich you may encounter within the application of this components. Therefore, by re-using these ‘template’ code examples you will be able to use any methods from within thiscomponent.

For a detailed description of the nature of each one of the methods within the Bondproduct please consult our API documentation at: WebCab Bonds API documentation

Structure of each Example

Each of these source code examples have the same structure and perform the followingsteps:

� Start Visual Basic Project - Within our examples we use a Form project in whichwe illustrate the method call.

� Declaring an instance of the class - In order to use the methods from a givenclass you must first create an instance of that class.

� Initializing the instance of the class

� Declaring the Parameters - Create the types which will be used within the methodcall.

� Declaring the variable to hold the returned method result

� Invoke the Method

� Print the result within a message box

Remark: We assume that the Bonds component has been registered and is availablewithin the Visual Basic project. For further details on how this is performed please seethe previous section.

73

Page 81: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Obtaining the Source code

We provide an implementation of RealReturn example with associated project files withinthe directory:

home/Libraries/Client/Interest/VBExamples/RealReturn

where home refers to the directory where the product is installed which will generallybe: C:/Program Files/WebCab Components/Bonds for .NET

This folder can also be access via the START menu by selecting: START > Programs >

WebCab Components > Bonds for .NET > .NET > Tools > Interest > VBExamples Custom Example

Within this folder you will find the following files:

1. RealReturn.frm - The Visual Basic source code file.

2. RealReturn.vbp - The Visual Basic project file.

3. RealReturn.vbw - The Visual Basic Project Workplace

In order to run this example you will need to:

1. Open VB Project file - Double click on the .vbp file which will open the projectwithin Visual Basic 6. We assume that you have Visual Basic 6 installed and thatVisual Basic project files (i.e. .vbs file) are associated with this IDE.

2. Add a WebCab Bonds Reference - Select from the VB6 menu Project > Reference

which will bring up the ’References’ dialog box. With the text area list please selectthe item ’WebCab Bonds Demo’ and then click ’OK’.

3. Run the example - After the Component has been registered you are able to runthe examples by pressing F5.

7.2.1 Calling the Real Return method which takes and returnsdoubles

This example shows how to use the RealReturn method from the Interest business classwhich takes two doubles as parameters and returns a double.

To reuse this Visual Basic example contained within the table 7.1 just copy and pasteto code within any of your subroutines or functions. In our example, we placed the codeinside the Form_Load subroutine, which is been triggered at the time the Application Formis first executed.

74

Page 82: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Private Sub Form_Load()' Declaring an instance of class InterestDim instance As WebCab_COM_BondsDemo.Interest' Initializing the instance of the class InterestSet instance = New WebCabCOM_BondsDemo.Interest

' Declaring a variable of type double which will hold the value' of interestDim interest As Doubleinterest = 0.03' Declare a variable of type double which will hold the value of' inflationDim inflation As Doubleinflation = 0.02' Declaring the variable to hold the method resultDim result As Double

' Calling the `RealReturn' method which calculates the real return of' an interest bearing investment over a given period when the average' rate of inflation and the average rate of interest over that period' are known.result = instance.RealReturn(interest, inflation)

' Printing the result in a Message BoxMsgBox "The real return of a interest bearing a investment over" & _" a given period when the interest is 3 percent and the " & _" inflation is 2 percent is : " & result

End Sub

Table 7.1: A specific Visual Basic client example

7.2.2 Calling the WeightOfBonds method which takes and re-turns double arrays

This example shows how to use the WeightOfBonds from within the DurationConvexitybusiness class which takes one double array and returns a double array.The source code for this example can be found at the following location:

home/Libraries/Client/BasicBonds/VBExamples/RealReturn

where home refers to the directory where the product is installed which will generallybe: C:/Program Files/WebCab Components/Bonds for .NET

This folder can also be access via the START menu by selecting: START > Programs >

75

Page 83: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Private Sub CalculateWeight_Click()' Within this example we test the method WeightOfBonds from' within DurationConvexity class' Declaring an instance of the class DurationConvexityDim instance As WebCab_COM_BondsDemo.DurationConvexity' Initializing the instance of the class DurationConvexitySet instance = New WebCabCOM_BondsDemo.DurationConvexity

' We calculates the weights of a bonds portfolio with 10 assets' with values 1, 2, 3, ..., 9, 10.

' Declaring an double array which will hold the values of the assets' IMPORTANT NOTE: The double array index must start with 0Dim valueOfBond(0 To 9) As DoublevalueOfBond(0) = 1valueOfBond(1) = 2valueOfBond(2) = 3valueOfBond(3) = 4valueOfBond(4) = 5valueOfBond(5) = 6valueOfBond(6) = 7valueOfBond(7) = 8valueOfBond(8) = 9valueOfBond(9) = 10

' Calling the WeightOfBonds method and storing the' result within result variableresult = instance.WeightOfBonds(valueOfBond)

' Printing the result within the FormFor Index = 0 To 9 Step 1Print "The weight of the asset " Index + 1 " is: " result(Index)Next Index

End Sub

Table 7.2: A Visual Basic client example with double arrays

WebCab Components > Bonds for .NET > .NET > Tools > BasicBonds > VBExamples Custom

Example

In this example, contained in table 7.2, we placed the code inside CalculateWeight_Click

subroutine, which is been triggered when the button Calculate is clicked.

76

Page 84: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

7.3 Developing with Visual C++ 6

Using this product from Visual C++ 6 involves two major steps: importing the TypeLibrary for this product and passing parameters to the COM methods according to COMstandards. All the other steps are rather straightforward and involve basic C++ codewriting:

The steps are as follows:

1. Open a New or Existing Project

2. Add All COM Specific ‘include’ Declarations

3. Import the Type Library for this Product

4. Call “CoInitialize”

5. Connect to a COM Server

6. Declare the Parameter Types and Values

7. Declare the Return Type

8. Call the Method

9. Call “CoUninitialize”

7.3.1 Open a New or Existing Project

You can start a new Visual C++ Project by going to the File | New... menu (see Fig. 7.5),which will bring up the “New” dialog window. From this window, choose the “Projects”tab and select the Win32 Console Application. Type in the name of your project in theProject name text box (for example, Project1) and click OK, as shown in Fig. 7.6.

In the next window, select “A simple application” (see Fig. 7.7), click the Finish but-ton, and click OK in the next window as well. From the left hand side of the screen, switchto “FileView” and select the .cpp file with the same name as your project – as seen in Fig.7.8. Note that the source code snippets in this section apply both to a new project and toone of your existing projects.

77

Page 85: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.5: Starting a new project

78

Page 86: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.6: Starting a Console Application named “Project1”

79

Page 87: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.7: Creating a simple Console Application

80

Page 88: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.8: Location of the main C++ source code file, Project1.cpp

7.3.2 Add All COM Specific ‘include’ Declarations

COM specific calls will require that the header file objbase.h is included within your project.This header offers functionality to enable C++ to interoperate with COM servers. To in-clude this header file within your project you will need to add at the top of your mainsource code file the following line:

#include "objbase.h"

7.3.3 Call “CoInitialize”

In order to allow Visual C++ clients to connect to a COM server, you need to make a callto a function named CoInitialize, which belongs to the objbase.h header file, mentionedabove. The call to the function must be made as shown below:

CoInitialize(NULL);

81

Page 89: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

7.3.4 Import the Type Library for this Product

The name of all COM interfaces and their methods are described by a Type Library filewith a .tlb extension. These methods are automatically exposed to your Visual C++ 6client by the IDE, if you import this .tlb file into your project.

In order to import the Type Library for this product, add an #import declaration (rightafter the #include declarations in your main source code file) followed by the complete pathto the COM .tlb file, which is located in the COM Libraries subdirectory of the instalationpath for this product. The default installation path for users with Administrator privilegesis C:\Program Files\WebCab Components\Bonds for .NET, while the default installationpath for a user without Administrator privileges is C:\Documents and Settings\User-Name\Local Settings\Application Data\WebCab Components\Bonds for .NET.

If you add no_namespace at the end of the #import statement, the COM interfaces willbe placed within the default namespace, so you can access them directly without prefixingthem with the namespace name.

For example, if you installed with Administrator privileges, you can import the TypeLibrary for this product by writing the following statement:

#import "C:\Program Files\WebCab Components\Bonds for .NET\\COM Libraries\WebCab.COM.BondsDemo.tlb" no_namespace

If you omit the no_namespace parameter, the COM methods will be exposed as part ofa namespace called WebCab_COM_BondsDemo.

7.3.5 Connect to a COM Server

For every COM server described in the COM API Reference, the previous step defines atype with the same name prefixed by “COM_” and followed by “Ptr”. Declare a variable ofthis type and invoke its method named CreateInstance with the GUID of the COM serveritself as a parameter.

For example, in order to connect to the Interpolation COM server, part of the WebCabFunctions for .NET product, you would write the following C++ code:

COM_InterpolationPtr instance = NULLinstance.CreateInstance(__uuidof(Interpolation));

The variable named “instance” will hold the connection to the “Interpolation” COM serverin all subsequent calls.

82

Page 90: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

7.3.6 Declare the Parameter Types and Values

Passing non-array parameters to the COM methods is as straightforward as passing pa-rameters to a C++ method. You can declare a parameter to hold the value, pass the valuedirectly, or pass the result of another method call.

When it comes to passing one-dimensional or two-dimensional arrays as parameters toCOM methods, you will need to perform some additional COM specific steps. First of all,all COM arrays are typed as SAFEARRAY. The SAFEARRAY type holds a pointer to a standardC++ array, but has some extra fields that describe the type of the array, its number ofdimensions, and most importantly its lower and upper bounds. Handling arrays of thistype can be done fairly easy using standard SAFEARRAY manipulation functions, such asSafeArrayCreate, SafeArrayRedim, and SafeArrayDestroy.

You will need to pass either one-dimensional or two-dimensional safe arrays to any ofthe COM methods within this product. Here is how you can accomplish this from VisualC++ 6:

� Declaring a One-Dimensional Safe ArrayUse the SafeArrayCreateVector function to create a one-dimensional safe array,by passing the element type, the lower bound and the number of elements the arrayhas. The element type is one of the types declared by the VARENUM enumeration type.Of the most common types, you will be using the VT_R8 constant (corresponding tothe double type in the API Reference), VT_I4 (corresponding to the integer type),VT_DATE (the DateTime type), and VT_BOOL for boolean types.

After making the call to this function, you will need to copy the values referenced bya C++ one-dimensional array to the memory location referenced by the pvData fieldof the safe array structure. This C++ array must hold the values that you wish tosend across to the COM method as a parameter value.

For example, in order to create a one-dimensional array of 4 double elements, hereis how you could define the corresponding safe array and the underlying C++ one-dimensional array:

int noElements = 4;double pvData_myOneDimensionalArray[] = {1, 2, 3, 4};SAFEARRAY *psa_myOneDimensionalArray = SafeArrayCreateVector(

VT_R8, 0, noElements);memcpy(psa_myOneDimensionalArray->pvData,

pvData_myOneDimensionalArray, noElements * sizeof(double));

� Declaring a Two-Dimensional Safe ArrayIn order to declare a two-dimensional array, you will first declare the correspond-

83

Page 91: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

ing C++ two-dimensional array. However, the C++ array needs to be transposed,such that the number of rows becomes the number of columns and vice-versa. Thisis due to the transposed memory layout of safe arrays, opposed to that of C++ arrays.

For example, if to declare an n by m safe array, you will need to declare an mby n C++ array, and lay the elements in this reversed order.

Also, you will need to make sure that the number of elements of all sub-arrays isthe same, because the two-dimensional safe array is a rectangular array, which as-sumes fixed number of elements on each dimension.

The safe array structure can be initialized using the SafeArrayCreate function,which takes the following parameters: the element type, the number of dimensions(two in our case), and the lower bound and number of elements on each dimension.The lower bound and number of elements is declared using a SAFEARRAYBOUND struc-ture, one for every dimension.

Assuming a two-dimensional array of 2 by 4 double elements, its corresponding safearray and C++ two-dimensional array must be 4 by 2 and its elements must be laidout as follows:

int noRows = 2;int noColumns = 4;double pvData_myTwoDimensionalArray[4][2] = {

{ 1, 5 },{ 2, 6 },{ 3, 7 },{ 4, 8 },

};

SAFEARRAYBOUND myTwoDimensionalArrayBounds[2];myTwoDimensionalArrayBounds[0].lLbound = 0;myTwoDimensionalArrayBounds[0].cElements = noRows;myTwoDimensionalArrayBounds[1].lLbound = 0;myTwoDimensionalArrayBounds[1].cElements = noColumns;

SAFEARRAY *psa_myTwoDimensionalArray = SafeArrayCreate(VT_R8, 2, myTwoDimensionalArrayBounds);

memcpy(psa_myTwoDimensionalArray->pvData,pvData_myTwoDimensionalArray, noRows * noColumns *

sizeof(double));

The actual values in the safe array are { 1, 2, 3, 4 } on the first row, and { 5, 6,

7, 8 } on the second row.

84

Page 92: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

Before sending a safe array to a COM method, you will also need to perform one last step– wrap it within a VARIANT type. The VARIANT structure is a generic type that can wraparound any other COM type. Define a variable of type VARIANT, and use its fields to specifythe type of the safe array and the reference to the safe array structure. To describe thetype of the safe array, use the VT_ARRAY constant and the constant corresponding to theelement type of the array.

For example, a variant corresponding to the two dimensional safe array declared abovewill look as follows:

VARIANT myTwoDimensionalArray;myTwoDimensionalArray.vt = VT_ARRAY | VT_R8;myTwoDimensionalArray.parray = psa_myTwoDimensionalArray;

A complete list of VARENUM constants corresponding to all COM types that might be re-quired by this product can be found at this MSDN link.

7.3.7 Declare the Return Type

COM methods that return arrays require special attention. Instead of declaring a C++array pointer, you will need to declare a pointer to a SAFEARRAY structure, and assign toit the result of the method call. Here is how you would declare a variable to hold a safearray returned by a COM method:

SAFEARRAY *arrayResult;

COM methods that return non-array types can be used like regular C++ methods, bydeclaring a variable of the corresponding type and assigning to it the result of the methodcall.

7.3.8 Call the Method

You can call a COM method by using the variable that holds the connection to the COMserver and the name of the method, as listed in the COM API Reference. For example,assuming you wish to call a method named ComMethod, which takes two double values forparameters and returns a third double value, here is how you could perform this call fromC++:

double result = instance->ComMethod (10, 20);

Any other COM method calls can be made the same way, by using a different method

85

Page 93: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

SAFEARRAY *twoDimArray;// A fictive call is made to the COM methodtwoDimArray = instance->ComMethod (paramValue1, paramValue2 etc.);

// We read off the lower and upper bounds on each dimensionlong l1, u1, l2, u2;SafeArrayGetLBound(twoDimArray, 1, &l1);SafeArrayGetUBound(twoDimArray, 1, &u1);SafeArrayGetLBound(twoDimArray, 2, &l2);SafeArrayGetUBound(twoDimArray, 2, &u2);

// We read through all elements and print them to the screenlong indices[2]; // the indices for every dimensionfor (indices[0] = l1; indices[0] <= u1; indices[0]++) {

for (indices[1] = l2; indices[1] <= u2; indices[1]++) {double element;SafeArrayGetElement(twoDimArray, indices, &element);printf ("twoDimArray[%d,%d] = %lf", indices[0], indices[1],

element);}

}

Table 7.3: Handling a two-dimensional safe array in C++

name, a different set of parameter values, and maybe a different return type.

Special care must be taken when processing the result of COM methods, which returna one or two-dimensional array. Since, as described above in section 7.3.7, the type of thevariable to hold the result is a pointer to a SAFEARRAY structure, you will need to use safearray specific methods, in order to inspect all element values, and reuse them in C++.

Table 7.3 gives an example of how to handle a two-dimensional array, covering most ofthe operations you are likely to perform in your C++ applications with safe arrays re-turned by COM methods.

7.3.9 Call “CoUninitialize”

In order to free generic COM related resources held by a C++ client, you must make acall to the CoUninitialize function. The call to this function can be made right before theend of your application or when your client no longer requires to use COM resources. Theline of code which releases all COM resources is:

CoUninitialize();

86

Page 94: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

7.3.10 A Generic Visual C++ Example

In this section we provide a generic Visual C++ example of a simple Console Application,which connects to one of our business classes, invokes one of its methods and prints the re-sult in a window. This source code example works with a new Win32 Console Application,which can be created as described in section 7.3.1. Since this example’s structure in notspecific to the method being invoked, you may adapt this example to whatever businessclass, product, and method you wish to call.

This C++ application calls a method named RelativeToAbsolute, belonging to the As-setParameters business class in the WebCab Portfolio for .NET product. This methodtakes one two-dimensional double array parameter and returns another two-dimensionaldouble array.

87

Page 95: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

// Project1.cpp, a Simple Win32 Console Application//

#include "stdafx.h"#include "objbase.h"#include "stdio.h"

// Adding a reference to the Portfolio COM Type Library#import "C:\Program Files\WebCab Components\Portfolio for .NET\\COM Libraries\WebCab.COM.PortfolioDemo.tlb" no_namespace

int main(int argc, char* argv[]){

CoInitialize(NULL); // Enable C++ to COM interoperability

/** Declare a variable to hold the connection to the* `AssetParameters' COM server and establish* the connection using its GUID.*/

COM_AssetParametersPtr instance = NULL;instance.CreateInstance(__uuidof(AssetParameters));

int noRows = 2;int noColumns = 4;// Reverse the dimensions for the C++ array, by declaring first// the number of columns and then the number of rows.double pvData_absoluteValues[4][2] = {

{ 100, 140 },{ 120, 135 },{ 125, 135 },{ 115, 140 },

};SAFEARRAYBOUND bounds[2];bounds[0].lLbound = 0;bounds[0].cElements = noRows;bounds[1].lLbound = 0;bounds[1].cElements = noColumns;SAFEARRAY *psa_absoluteValues = SafeArrayCreate(VT_R8, 2, bounds);memcpy(psa_absoluteValues->pvData,

pvData_absoluteValues, noRows * noColumns * sizeof(double);

Table 7.4: Generic VC++ example (continued on the next page)

88

Page 96: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Visual Studio 6 Chapter 7

VARIANT absoluteValues;absoluteValues.vt = VT_ARRAY | VT_R8;absoluteValues.parray = psa_absoluteValues;

// Call the `AbsoluteToRelative' COM methodSAFEARRAY *relativeValues;relativeValues = instance->AbsoluteToRelative(absoluteValues);

// Print the result inside a MessageBoxchar text[200] = "";long indices[2];long l1, u1, l2, u2;SafeArrayGetLBound(relativeValues, 1, &l1);SafeArrayGetUBound(relativeValues, 1, &u1);SafeArrayGetLBound(relativeValues, 2, &l2);SafeArrayGetUBound(relativeValues, 2, &u2);for (indices[0] = l1; indices[0] <= u1; indices[0]++) {

sprintf (text, "%s{ ", text);for (indices[1] = l2; indices[1] <= u2; indices[1]++) {

double element;SafeArrayGetElement(relativeValues, indices, &element);sprintf (text, "%s%lf ", text, element);

}sprintf (text, "%s}\n", text);

}

MessageBox(NULL, text, "The Relative Values", MB_OK);

CoUninitialize(); // Free all COM specific resourcesreturn 0;

}

Table 7.5: Generic VC++ example (continued)

89

Page 97: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Chapter 8

Programmer’s Guide for BorlandC++ Builder

This chapter contains information concerning the use of this Component product from Borland’sC++ Builder product lines; include Borland C++ 2005, Borland C++BuilderX and BorlandC++Builder; on the Windows development platform. The principles and code examples pro-vided here can be applied verbatim in order to use this component with the C++ languageon the Windows development platform. Though the use of the different IDE products lineswill differ slightly, the same Windows client code can be used verbatim within any of the C++Builder product lines.

8.1 Developing with Borland C++ Builder

In order to connect and make calls to our COM servers from Borland C++ Builder, youwill need to write late-binding code.

The steps are as follows:

1. Open a New or Existing Project

2. Add all COM Specific ‘Include’ Declarations

3. Call “CoInitialize”

4. Create a Class Instance

5. Obtain a Method ID

6. Declare the Parameter Values and Types

7. Declare the Return Type

8. Call the Method

9. Call “CoUninitialize”

90

Page 98: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Borland C++ Builder Chapter 8

Fig. 8.1: Starting a new project

8.1.1 Open a New or Existing Project

You can start a new Borland C++ Builder Project by going to the File | New... menu (seeFig. 8.1), which will bring up the “Object Gallery” dialog window. From this window,choose the “Project” left-hand item, select the New Console project and click OK, as shownin Fig. 8.2.

Type in the name of your project in the next dialog window and click Next (see fig. 8.3). Inthe next window (figure 8.4) simply click Next, and in the last window, select the checkboxnext to the untitled entry and click the Finish button, as shown in figure 8.5.

91

Page 99: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Borland C++ Builder Chapter 8

Fig. 8.2: Starting a Console Application

Fig. 8.3: Choosing a name for a new Borland C++ Console Application

92

Page 100: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Borland C++ Builder Chapter 8

Fig. 8.4: Selecting platforms and tools sets for a new Borland C++ Console Application

8.1.2 Add all COM Specific ‘Include’ Declarations

COM specific calls will require that the header file objbase.h is included within your project.This header offers functionality to enable C++ to interoperate with COM servers. To in-clude this header file within your project you will need to add at the top of your mainsource code file the following line:

#include "objbase.h"

8.1.3 Call “CoInitialize”

In order to allow Borland C++ Builder clients to connect to a COM server, you need tomake a call to a function named CoInitialize, which belongs to the objbase.h header file,mentioned above. The call to the function must be made as shown below:

CoInitialize(NULL);

93

Page 101: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Borland C++ Builder Chapter 8

Fig. 8.5: Specifying the project files for a new Borland C++ Console Application

8.1.4 Create a Class Instance

In order to create an instance of a WebCab Bonds business class, you will need to providethe full name (i.e. the ProgId) of the business class, as declared within the API Reference.The full name of a business class contains the namespace, followed by a period and thename of the class itself.

The C++ code below returns an instance of the Interpolation business class, located insideWebCab Functions for .NET. Its namespace is WebCab.COM.Math.Interpolation, meaningits full name is WebCab.COM.Math.Interpolation.Interpolation. You can easily adapt thecode below to create an instance of another business class, by replacing the ProgId belowwith the full name of the class you wish to use.

94

Page 102: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Borland C++ Builder Chapter 8

CLSID clsid;CLSIDFromProgID(OLESTR( // Get the CLSID of the ProgId

"WebCab.COM.Math.Interpolation.Interpolation"),&clsid);

LPDISPATCH instance = NULL; // the COM `instance'LPUNKNOWN punk = NULL;

CoCreateInstance (clsid, NULL, CLSCTX_INPROC_SERVER,IID_IUnknown, (void**) &punk);

punk->QueryInterface(IID_IDispatch, (void**) &instance);punk->Release();

The variable named “instance” will hold the connection to the “Interpolation” COM server.

8.1.5 Obtain a Method ID

In order to call a method using the instance created above, you will need to obtain a ref-erence to its ID. Use the code below to obtain the ID of the method you wish to call, byreplacing the generic method name “MyMethod” with the name of the method you wishto call. The variable “methodID” will hold the reference to the method.

DISPID methodID; // The ID of the method

/** Replace `MyMethod ' with the name of the method you wish to call*/

wchar_t *methodName = L"MyMethod";instance->GetIDsOfNames(IID_NULL, &methodName, 1, LOCALE_USER_DEFAULT,

&methodID);

8.1.6 Declare the Parameter Values and Types

For every parameter, you will need to declare a variable of type VARIANT, whose type willbe set to the type of the parameter, and its value will correspond to the value you wishthe parameter to take. The code listed in table 8.1 shows how to declare the parametervalues for a method that takes two double parameters.

For information about how to set other types of parameters, such as integers, booleanvalues, and arrays; we refer the reader to this ‘IDispatch Data Types and Structures’article on Microsoft’s MSDN site.

95

Page 103: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Borland C++ Builder Chapter 8

int noParameters = 2; // the number of parameters// 1st parameterVARIANTARG parameter1;parameter1.vt = VT_R8; // 8-bit real typeparameter1.dblVal = 100.0; // 100.0// 2nd parameterVARIANTARG parameter2;parameter2.vt = VT_R8; // 8-bit real typeparameter2.dblVal = 95.0; // 95.0

DISPPARAMS parameters; // the list of parametersmemset(&parameters, 0, sizeof(DISPPARAMS));parameters.cArgs = noParameters;parameters.rgvarg = new VARIANTARG[noParameters];memset(parameters.rgvarg, 0, sizeof(VARIANT) * noParameters);

// Add the parameters in reverse orderparameters.rgvarg[1] = parameter1;parameters.rgvarg[0] = parameter2;

Table 8.1: Declaring parameter types and values for a COM method

8.1.7 Declare the Return Type

A VARIANT variable needs to be declared for the return value of the method as well. Thetype of the VARIANT will be automatically set by the method invocation, so you will onlyneed to initialize its type to VT_EMPTY by calling the VariantInit function.

VARIANTARG result; // Variable to hold the resultVariantInit(&result);

8.1.8 Call the Method

Calling the method comes down to using all the variables declared in the previous steps (theinstance, the method ID, the parameters, and the return value) in one call, as shown below:

// Call the underlying methodinstance->Invoke(methodID, IID_NULL, LOCALE_SYSTEM_DEFAULT,

DISPATCH_METHOD, &parameters, &result, 0, NULL);

The return value of the method is stored in the result variable, in the field correspondingto the method’s return type. For example, if the method returns a double, you will writethe following code in order to store the result in a double variable named “resultAsDouble”:

96

Page 104: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Borland C++ Builder Chapter 8

// Get the result as doubledouble resultAsDouble = result.dblVal;

8.1.9 Call “CoUninitialize”

In order to free generic COM related resources held by a C++ client, you must make acall to the CoUninitialize function. The call to this function can be made right before theend of your application or when your client no longer requires to use COM resources. Theline of code which releases all COM resources is:

CoUninitialize();

8.1.10 A Generic Borland C++ Builder Example

In this section (tables 8.2 and 8.3) we provide a generic Borland C++ Builder example ofa simple Console Application, which connects to one of our business classes, invokes oneof its methods and prints the result in a window. The source code below works with anew Win32 Console Application, which can be created as described in section 8.1.1. Sincethis example’s structure in not specific to the method being invoked, you may adapt thisexample to whatever business class, product, and method you wish to call.

This C++ application calls a method named Kairi, belonging to the MovingAverage busi-ness class in the WebCab Technical Analysis for .NET product. This method takes twodouble parameters and returns a double value.

97

Page 105: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Borland C++ Builder Chapter 8

// Project1.cpp, a Simple Win32 Console Application//

#include "objbase.h"#include "stdio.h"

int main(int argc, char* argv[]){

CoInitialize(NULL); // Enable C++ to COM interoperability

CLSID clsid;CLSIDFromProgID(OLESTR( // Get the CLSID of the ProgId

"WebCab.COM.Finance.Trading.Indicators.MovingAverage"),&clsid);

LPDISPATCH instance = NULL; // the COM `instance'LPUNKNOWN punk = NULL;

CoCreateInstance (clsid, NULL, CLSCTX_INPROC_SERVER,IID_IUnknown, (void**) &punk);

punk->QueryInterface(IID_IDispatch, (void**) &instance);punk->Release();

DISPID methodID; // The ID of the method

// The method name is `Kairi'wchar_t *methodName = L"Kairi";instance->GetIDsOfNames(IID_NULL, &methodName, 1, LOCALE_USER_DEFAULT,

&methodID);

int noParameters = 2; // the number of parameters// 1st parameterVARIANTARG parameter1;parameter1.vt = VT_R8; // 8-bit real typeparameter1.dblVal = 100.0; // 100.0// 2nd parameterVARIANTARG parameter2;parameter2.vt = VT_R8; // 8-bit real typeparameter2.dblVal = 95.0; // 95.0

Table 8.2: Generic VC++ example – Part 1

98

Page 106: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for Borland C++ Builder Chapter 8

DISPPARAMS parameters; // the list of parametersmemset(&parameters, 0, sizeof(DISPPARAMS));parameters.cArgs = noParameters;parameters.rgvarg = new VARIANTARG[noParameters];memset(parameters.rgvarg, 0, sizeof(VARIANT) * noParameters);

// Add the parameters in reverse orderparameters.rgvarg[1] = parameter1;parameters.rgvarg[0] = parameter2;

VARIANTARG result; // Variable to hold the resultVariantInit(&result);

// Call the `Kairi' methodinstance->Invoke(methodID, IID_NULL, LOCALE_SYSTEM_DEFAULT,

DISPATCH_METHOD, &parameters, &result, 0, NULL);delete [] parameters.rgvarg;

// Get the result as doubledouble percentage = result.dblVal;// Print the result inside a MessageBoxchar text[200];sprintf(text, "The percentage is %lf", percentage);MessageBox(NULL, text, "Method result", MB_OK);

CoUninitialize(); // Free all COM specific resourcesreturn 0;

}

Table 8.3: Generic VC++ example – Part 2

99

Page 107: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Chapter 9

Programmer’s Guide for .NET

This chapter describes development techniques for various business solutions that make useof the functionality provided by our .NET Service. We analyze both standard and enterprisesolutions, including stand-alone applications, ASP.NET pages, and XML Web services.

9.1 Developing with .NET Class Libraries

The .NET Edition of this product offers core-level functionality to the .NET developerallowing the implementation of fully personalized components and applications for specificbusiness problems on a variety of deployment environments. Irrespective of the complexityof the project a programmer may be working on, this .NET Service can be integrated inan equally straightforward manner by providing the needed functionality in a compact andprecise way.

The Bonds for .NET v2.0 component comes as a collection of DLL files. Each DLL isa packed collection of classes that provide the functionality offered by this .NET Service asdocumented inside the API reference directory of this package. Depending on the type of.NET solution you are developing, you will be using these DLL files in a specific way. Onceyou have chosen a particular implementation of a deployment framework, the structure ofyour source code will need to adapt accordingly. In the following discussion we describeseveral basic .NET implementation examples that can be used to make use of our product’sfunctionality.

9.1.1 Stand-alone C# .NET Applications

A stand-alone C# application is a C# class which acts as a client for the deployed .NETcomponents (i.e. DLLs). The source code listed below defines a standard stand-aloneapplication skeleton which communicates with a class within a .NET Component. By cre-ating an instance, calling a method, sending in a set of parameters and then retrieving thereturned result of the method call. As soon as the method call has gone through success-fully the method continues by displaying its result on the screen.

100

Page 108: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for .NET Chapter 9

/*

* The class we are is located inside the WebCab.Libraries.NetService

* namespace.*/

using System;

using WebCab.Libraries.NetService;

public class StandAloneExample {

public static void Main () {

/*

* Creates an instance of the NetClass class*/

NetClass instance = new NetClass ();

/*

* Defines the method parameter.*/

double parameter = 25;

/*

* Invokes a method with the specified parameter* and puts the result in the result variable.*/

double result = instance.ComputeResult (parameter);

/*

* Prints out the retrieved result.*/

Console.WriteLine ("Method ’ComputeResult’ in class NetClass

returned " + result + ".");

}

}

If the method ComputeResult of the NetClass class returned 100, this stand-alone appli-cation would print the following:

Method ’ComputeResult’ in class NetClass returned 100.

101

Page 109: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for .NET Chapter 9

9.2 Developing with XML Web Services

This component has been XML Web service enabled and the relevant deployment files canbe deployed which means that you may deploy the Application as a web service and makethe methods contained therein available as XML Web service methods.

9.2.1 Deploying the XML Web Services

Using Windows XP with .NET Framework and IIS installed

In order to deploy this .NET Service as an XML Web service you will need to go throughthe following steps:

� Copy DLL Files - copy the DLL files provide into the bin directory of the IIS serversdirectory. On the standard install this is located at:

C:\Inetpub\wwwroot\bin

� Copy asmx Files - now copy the asmx files included into the folder:

C:\Inetpub\wwwroot\

Now the web service can be accessed through the URL:

http://localhost/WebServices/filename.asmx

Remarks

1. If you prefer to change the URL in which the XML Web service can be accessedthen just create and then copy the asmx files into another subfolder of the ‘wwwroot’directory, in which case the corresponding URL of the web service will correspondingchange.

2. In order to copy the installation files to your IIS location you will need to haveappropriate read and write access to the folder under question.

9.2.2 Writing XML Web Service Clients

The building of an XML Web service client will require the following steps:

� Create a proxy class for the XML Web service.

102

Page 110: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for .NET Chapter 9

� Reference the proxy class in the client code.

� Create an instance of the proxy class in the client code.

� Call the method on the proxy class corresponding to the XML Web service methodyou want to communicate with.

For most clients, these steps differ only on how the proxy class is referenced and how theXML Web services are deployed.

9.2.3 Writing Console XML Web Service Clients

An XML Web service client may take a number of forms including a console application,ASP.NET page, HTML page, Windows Form, Java Applet/Frame and any other XMLWeb service enabled client technology.

Here in order to illustrate the core step involved in making a client we describe the stepsrequired to build a console application. Creating other types of clients will involve similarsteps. We assume that you have the .NET Framework installed (on the client and server)and that the IIS server has (been installed and) started on the server.

To create a console XML Web service client application you must:

� Deploy the DLL provided into a bin which you need to create somewhere in a subdi-rectory of the IIS web server you plan to use. The default location for this web serveron your local machine is ‘C:\Inetpub\wwwroot’. The DDL is the required XML Webservice .NET assembly file.

� Deploy the web service descriptor ‘Classname.asmx’ provided, into a IIS web-serversubdirectory.1 Note that we will assume below that the URL of the deployed Class-name.asmx file is:

http://yourserver/Webservices/Classname.asmx

� Create a XML Web service proxy by using the WDLS command line tool. Enter aDOS prompt in the directory where you intend to (develop and) run your consoleapplication from and type at the command line:

Wsdl.exe http://yourserver/Webservices/Classname.asmx

1The purpose of the asmx file is to tell the server that the XML Web service exists so that it may startsearching for the relevant classes within the DLL files in the bin directory. Hence, the asmx file is verysimple and consists of the one line:

<%@ WebService language="C# " class="Classname" %>

and is saved as a TXT file with an extension .asmx.

103

Page 111: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for .NET Chapter 9

That is ‘Wsdl’ followed by the URL of the asmx file for the XML Web service. Thisutility will generate a C# file which will be written to the present directory (whichshould be the clients directory)2. The WSDL file is an interface (in OOP terminology)or proxy for the DLL C# implementation of the XML Web service.

� Write a console application in the standard way and instantiate the WebService meth-ods (as if the DLL is hosting locally) using the WSDL proxy. See the below template:

using System;

public class ClassnameClient {/// <remarks>

/// The Main method ensures that the console will run.

/// </remarks>

static void Main() {/*

* We instantiate the "object" represented by

* the proxy class.

*/

Classname classnameObject = new Classname();

/*

* We invoke the ‘Compose’ method of the

* Classname XML Web service

*/

Console.WriteLine("XML Web service method Compose

applied to 7.0 and 3.9 is " +

classnameObject.Compose(7, 3.9));

}}

2WSDL is a standard by which all XML Web services are described. See http://www.w3.org/TR/wsdl

104

Page 112: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for .NET Chapter 9

9.2.4 Importing Web services into Visual Studio .NET projects

Fig: Adding a Web reference.

Fig: Adding a Web reference.

105

Page 113: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for .NET Chapter 9

9.3 Connecting to a Database with our .NET Libraries

9.3.1 Overview

Most of the financial and mathematical functionality provided by this .NET Service is in-tended for use within a multi-tier environment where the back-end role is taken by an SQLDatabase server. By packaging this functionality within .NET components such as XMLWeb services and .NET Class Libraries we separate the business logic from the databaselogic, allowing you to customize the way you access the database and the way the retrieveddata is sent to the business methods.

In order to assist you in developing DBMS based .NET solutions, we provide the ADOMediator as a standardized way of using our .NET components with an SQL Databaseserver. The ADO Mediator is also a .NET component, which sits on the same level as theother financial and mathematical .NET components and is a seamlessly integrated compo-nent of this .NET Service. While reducing the amount of DBMS code you have to type, itallows you to concentrate on the SQL queries and procedure calls to the Database serverand map the stored data directly to the business methods of this .NET Service.

The ADO Mediator’s functionality has been enabled for use with the following modulescontained within the WebCab Bonds for .NET v2.0:

� The “Basic Bonds” Module

� The “Interest” Module

� The “Interest Derivatives” Module

9.3.2 The ADO Mediator

There is one ADOMediator class for every module in this .NET Service. You will use thecorresponding ADOMediator class for performing Database operations with classes of a cer-tain module. The ADO Mediator class is located inside the ‘ADO’ subnamespace of itscorresponding module. For example if a module contains the:

WebCab.Libraries.Finance.Trading

namespace, its ADOMediator class will be found under:

WebCab.Libraries.Finance.Trading.ADO.ADOMediator.

Configuring the ADO Mediator

There are three steps to perform in order to start using an ADO Mediator class:

1. Specify the ADO.NET DriverThe constructor accepts an input connection and an output connection. There is no

106

Page 114: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for .NET Chapter 9

restriction that you should provide both an input and an output connection. Youmay choose to read data and display it inside your Application, compute data andwrite it into the database, or read and write to and from the database, and specifyonly the input or output database connection.

Connecting to your database requires an ADO.NET Driver. This driver is a .NETclass which is part of a DLL file provided by your Database vendor. You specifythe driver you wish to use by sending in to the ADOMediator constructor its run-timetype. That is, if your driver class name is System.Data.SqlClient.SqlConnection3,its run-time type under C# is specified by typing inside your source code:

typeof (System.Data.SqlClient.SqlConnection)

2. Provide the input/output ConnectionString propertyThe ConnectionString property is a piece of text which describes the Database servermachine address, the credentials, and additional information required in order toobtain access to certain parts of your Database server. This piece of text is alwaysdocumented by the provider of the ADO.NET Driver and should be used as suchwhen submitting it to an ADOMediator constructor. An example for the previousADO.NET SQL Server driver would be:

"Initial Catalog=Northwind;Data Source=localhost;Integrated Security=true;"

You may easily notice that the string above describes the machine name and theinitial catalog to connect to. The Integrated Security=true bit enables you toconnect to the SQL Server 2000 by using the current Windows login username andpassword.

3. Assign a business .NET componentThe previous two steps are part of creating an instance of an ADOMediator class andtaking care of the Database connections. This third step involves specifying the busi-ness class belonging to this module which deals with the financial and mathematicalfunctionality. Choose a class of the corresponding module and assign an instance ofthis class to the UnderlyingInstance property of the previously created ADOMediator

instance.

For example, if the name of the class you choose is TradingClass, you could writethe following C# code4:

TradingClass aTradingClassInstance = new TradingClass ();adoInstance.UnderlyingInstance = aTradingClassInstance;

3The built-in ADO.NET driver class name for connecting to the MS SQL Server4We assume adoInstance is the name of the previously created ADOMediator instance.

107

Page 115: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for .NET Chapter 9

Using the ADO Mediator

Once these three steps have been performed, you may use the created ADOMediator instanceto perform Database related calculations using the assigned .NET business class. Thereare several methods which you may use with your ADO Mediator instance. Some methodsallow you to read from the database and perform calculations for every retrieved row, andthen store the result in a .NET variable. Other methods allow you to specify the inputvalues and write the result in the database. There are also methods which allow you toread the input parameters from the database and write the method results back into thedatabase in one go.

The basic methods of the ADO mediator are:

� Select Method - Allows you to retrieve the results of a method of your choice be-longing to the underlying business class instance, applied to every row of an SQLSELECT query.

� Update Method - Directly updates values inside your database, as returned by amethod belonging to the underlying business class instance.

� SelectAndUpdate Method - Allows you to combine the two methods mentioned aboveby selecting the data, computing the results and writing it back to the database,according to your own criteria.

A complete API reference for these methods is found inside the Documentation folder ofthis pack. The Windows Installer (MSI) for this .NET Service has also created a short cutto this documentation from the Start Menu.

How the ADO Mediator Works

The way the ADO Mediator processes requests from the client and transfers them to the.NET components and the Database is shown in the diagram below.

108

Page 116: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for .NET Chapter 9

Fig: This diagram describes how the ADO Mediator passes onto the Database andthe .NET components its client requests.

C# Source Code Example

The following C# source code makes use of the ADO Mediator’s functionality in order toread and update the database according to a known algorithm. We use the standard SQLServer ADO.NET Driver to connect to a fictitious table named TRADES, and invoke theTradingMethod method of the TradingClass business class.

109

Page 117: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for .NET Chapter 9

using System;using System.Data.SqlClient;using WebCab.Libraries.Finance.Trading;using WebCab.Libraries.Finance.Trading.ADO;...try {.../** We specify the same driver and connection string for both the input and output* connections to the SQL Server 2000 Database server.*/

ADOMediator adoInstance = new ADOMediator (typeof (SqlConnection), // Input

"Initial Catalog=Northwind;Data Source=localhost;Integrated Security=true;",typeof (SqlConnection), // Output

"Initial Catalog=Northwind;Data Source=localhost;Integrated Security=true;");

/** We assign an instance of the TradingClass business class to the newly created* instance of this ADO Mediator.*/

adoInstance.UnderlyingInstance = new TradingClass ();

/** We invoke the SelectAndUpdate method which will populate the table according to* the result of the method and the position of the input values in the database.*/

adoInstance.SelectAndUpdate ("TradingMethod","SELECT C ID, SHARES, VALUE FROM TRADES", // Select"UPDATE CUSTOMER SET MONEY=@MONEY WHERE C ID=@C ID", // Update"@MONEY", // Maps the ‘TradingMethod’ method result to @MONEY{new Object[] {"@C ID", "C ID"}}, // Maps C ID to @C IDfalse); // True when updating with a stored procedure

}catch (ADOMediatorException e) {Console.WriteLine (e);

}

Using ADO Mediator with SQL Server 2000

The ADO Mediator instance above requires the same information as in the case of writingyour own ADO.NET source code. The difference lies in the fact that you do not have tomanually control the driver specific operations such as opening and closing a connection,and only concentrate on your SQL queries and the functionality of our business classes.You start by following the three steps mentioned above5 and continue by making calls toany ADOMediator methods.

5Specifying the input and/or output ADO.NET drivers and their connection strings and assigning aninstance of the fictitious TradingClass business class.

110

Page 118: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Programmer’s Guide for .NET Chapter 9

As you may notice, the SelectAndUpdate method above follows a logical pattern of de-scribing how the data should be read from the database, computed, and written back,with special care to the use of named parameters. You do not require previous experiencein dealing with named parameters, as they are basically a way to substitute real values withnames inside SQL queries. You may have spotted the @MONEY and @C ID named parametersin our UPDATE statement above. These named parameters will be replaced with real values,taken either from the TradingMethod’s result, or directly from a column returned by theSELECT query.

In our case, we replace @MONEY with the result of applying the TradingMethod method6

to the values of the SHARES and VALUE columns returned by the SELECT query. The sec-ond named parameter (@C ID) is replaced directly by the value of the C ID column of theSELECT query. For more information about named parameters you may wish to consult yourADO.NET driver’s manual. Most special cases are related to the use of named parametersand have been covered by the current version of the ADO Mediator.

6Which in our example belongs to the fictitious TradingClass business class.

111

Page 119: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Chapter 10

Examples

Within this chapter we illustrate how the Portfolio Component can be applied to solve reallife problems. We provide with this Component examples of two types:

1. QA Examples

2. Custom Examples

10.1 Question and Answer (QA) Client Examples

10.1.1 Overview

Within this folder we offer client examples written using a number of .NET compliantlanguages for the .NET Business Components provided within this package. In particular,for each business method contained within each business Component we provide an exampleimplemented within C# , VB.NET and C++.NET; which illustrates how functionalitycontained within this component can be applied to solve real world problems. In addition,to these examples we also include custom applications which solve some of the genericproblems which this Component is designed to address.

10.1.2 Structure of QA Examples Directory

By drilling down the QA Client directory structurr you will find the following six directorylevels:

1. Client Level2. Language Level3. Business Module Level4. Business Class Level5. Example Level6. Custom Example Level

which have the structure as shown in the following diagrams.

112

Page 120: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

Top Three levels of the QA Directory Structure

(Client Level) (Language Level) (Business Module Level)

QAClients +

|

+ C# ------------------------+

| |

+ VB.NET --+... + ‘Business Module 1’ ----------

| |

+ C++.NET --+... + ‘Business Module 2’ --+...

| |

+ QALibrary.dll + ...

|

+ QALibraryModule.netmodule

|

+ Readme.txt

Bottom Three levels of the QA Directory Structure

(Business Class Level) (Example Level) (Custom Example Level)

--+

|

+ ‘Business Class 1’ --------+

| |

+ ‘Business Class 2’ --+... + ‘BusinessClass’.exe.conf

| |

+ ... + ‘BusinessClass’.cs

|

+ compile.bat

|

+ run.bat

|

+ run_gui.bat

|

+ ‘CustomClient’ -------+ ‘CustomClient’.cs

| |

+ ... + compile.bat

|

+ run.bat

113

Page 121: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

10.1.3 Quick Start Guide

Browse down to the particular client within the business module for the given .NET com-patible language which you are interested in. Run the compile.bat, script in order tocompile the example and then run the run.bat, script in order to run the example.

10.1.4 Explanation of the QA Directory Structure and its files

1. Client Level

The directory containing the Questions and Answer Examples is named ‘QAClients’.This directory can be located by using the Readme.html file, which is presented atthe end of the installation process, by selecting:

Run Examples > Run .NET Class Library Examples

The Readme.html file can also be opened from the shortcut:

Start > Programs > WebCab Components > ‘Name of Components Package’ > Readme.html

2. Language Level

Within the ‘QAClients’ folder is the Language level of the QA directory structure.Within this folder you will find 3 sub-directories: C# , VB.NET and C++.NET;which contain examples written in each of the .NET languages C# , VB.NET andC++.NET respectively. Within this folder you will also find the following three files:

� QALibrary and QALibraryModule.netmodule - contain utility function-ality necessary for running the clients. If you wish to run these examples fromwithin Visual Studio .NET (for example) then you will need to register this DLLwithin your VS.NET project.

� Readme.txt - this Readme file.

As mentioned above within the overview we provide an implementation of each ‘Ques-tion and Answer’ example as three eqivalent implementations, namely: a C# client,a VB.NET client and a C++.NET client. Selecting one of the three folders C# ,VB.NET or C++.NET; in order to view the client implementated within the corre-sponding language.

3. Business Module Level

After selecting one of the sub-folders C# , VB.NET, C++.NET at the ‘LanguageLevel’ (see (2) above) you will enter a folder which contains a sub-folder for each ofthe modules contained within this component package. The modules are convenientcollections of business classes containing the business functionality offered by thiscomponent. Each module has a sub-folder which contains the ‘Question and Answer’examples of each method of the classes which it contains.

114

Page 122: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

4. Business Class Level

At the business class level under the module level we are presented with one sub-folderfor each of the classes within the business module. Each of these folders contains thefiles of the examples for each of the methods contained with the respective class.

5. Example Level

At the Example level you will be presented with the files which allow you to compileand then run the examples of the application of the Business methods of the respec-tive class. The files within this directory which constitute the Client example are asfollows:

� Source Code File(s) - Depending on the .NET compatible language selectedat the ‘Language Level’ this folder will contain a source code file(s) with theextension .cs, .vb or .cpp corresponding respectively to the C# , VB.NET orC++.NET client.

� Configuration File - Apart from the main source code file the folder willalso contain a configuration file with the extension .conf, this file contains theinformation concerning the location of the DLLs which the example will require.You may add more references as needed but you should not remove the referencesalready contained within this file.

� Compile Batch File - Assuming that you have access to the relevant C# ,VB.NET or C++.NET compiler the compile batch file (compile.bat) once runwill compile the client example from the folders source code file. Below weinclude some remarks on how to obtaining suitable .NET compilers in order tobe able to compile and then run these C# , VB.NET and C++.NET examples.

� Run Batch File - The run batch file (run.bat) will run the examples executablefile (exe) which is generated from the compilation of the source code file. If theexample over runs your console screenful then press space in order to page down.

6. Custom Example Level

At the Custom Example level you will find a source code file containing the im-plementation of the Application which addresses a typical question for which theComponent is designed. The source code has a linear structure with full inline com-mentary. By just running the compile and then run scripts contained within thisdirectory you will be able to solve to given problems view the results obtained. Thefiles contained within each Custom Client Example directory are as follows:

� Source Code File(s) - Depending on the .NET compatible language selectedat the ‘Language Level’ this folder will contain a source code file(s) with theextension .cs, .vb or .cpp corresponding respectively to the C# , VB.NET orC++.NET client.

115

Page 123: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

� Compile Batch File - Assuming that you have access to the relevant C# ,VB.NET or C++.NET compiler the compile batch file (compile.bat) once runwill compile the client example from the folders source code file. Below weinclude some remarks on how to obtaining suitable .NET compilers in order tobe able to compile and then run these C, VB.NET and C++.NET examples.

� Run Batch File - The run batch file (run.bat) will run the examples executablefile (exe) which is generated from the compilation of the source code file. If theexample over runs your console screenful then press space in order to page down.

10.1.5 Remarks on .NET compilers

1. Required compilers and how to test for them

In order to compile the C# , VB.NET or C++.NET examples you will require foreach of these .NET languages a suitable compiler. The easiest way in which to testwhether you have access to the three main .NET language compilers at your com-mand prompt is to type the follow commands at the command line:

csc - Invokes the C# compilervbc - Invokes the VB.NET compilercl - Invokes the C++.NET compiler

2. How to obtain the required compilers

Compilers for the C# and VB.NET .NET compatible languages are provided withinthe .NET SDK v1.0 (or higher). At the time of writing within the standard Microsoft.NET SDK the C++ compiler is enabled only as a C compiler.

In order to obtain the C# and VB.NET command line compilers you simply needto download and install the .NET SDK available from the Micrsoft site. In orderto obtain a fully functional C++.NET compiler you can either download and installMicrosoft’s feeely available and fully functional Visual C++ Toolkit 2003, availablefrom: http://msdn.microsoft.com/visualc/vctoolkit2003/; or use the C++ compilerwhich is provided with Microsoft’s Visual Studio .NET IDE.

10.2 Custom Examples

The following sections describe all custom-made examples.

10.3 Fundamental Theory of Bonds

We provide examples for each of the methods provided by this module.

116

Page 124: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

10.3.1 Zero Rates

Within this subsection we describe the examples provided within the:

CalculatingZeroRatesClient.java

client which is contained within the Client\CalculatingZeroRates folder of this package.Within this client we provide one example for each of the methods within the CalculatingZeroRatesclass.

Zero Rate implied from Zero Bond rates

Problem: What is the zero rate of a zero bond with 2.13 years to maturity which has amarket price of $96.24 and a face value of $100?

Solution: The gross interest yield is 0.0173 . . ., which can be evaluated using:

zeroRateFromZeroBond(2.13, 100, 96.24)

method of the CalculatingZeroRates class.

Boot strap method

Problem: The market price of a coupon paying bond with 1.9 years to maturity is $94.The coupon paying bond pays an annual coupon of $1 which is due in 0.9 years. Further,the zero rate of 1 year and 0 years maturity is known to be 4% and 4.2% respectively.What is the zero rate of duration 1.9 years?

Solution: The zero rate of maturity 1.9 years is 0.0327 . . ., which can be evaluated usingthe:

calculatingZeroRatesObject.zeroRateBootstrap(1.9, {1, 1}, { 0.9, 1.9 }, {4, 4.2}, 94,100)

method of the CalculatingZeroRates class.

10.3.2 Forward Rates

Within this subsection we describe the examples provided within the:

ForwardRatesClient.java

client which is contained within the Client\ForwardRates folder of this package. Withinthis client we provide one example for each of the methods within the ForwardRates class.

117

Page 125: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

Evaluate the Forward rate

Problem: What is the forward rate corresponding to the period between 3 and 4 years.Where the 3 year zero rate is 10.8% and the 4 year zero rate is 11% ?

Solution: The forward rate is 0.115999 . . ., and is given by the method:

forwardRate(0.108, 0.11, 3, 4)

method of the ForwardRates class. Note, that by ‘reversing’ the rates, that is evalu-ating:

forwardRate(0.11, 0.108, 3, 4)

the forward rate is now given by 0.10199 . . ., and hence the order in which the interestrates are given effects the final result.

Forward Rate Agreement

Problem: What is the value of a forward rate agreement (FRA) of the following contract?The 1-year zero-coupon rate is 10% and the two-year zero coupon rate is 10.5%, furtherthe 2-year zero coupon continuously compounded rate is 10.5%. Suppose we had enteredinto a FRA where we will receive a rate of 12% with annual compounding on a principlesum of $1 million between the end of year one and the end of year two.

Solution: This contract can be evaluated by first evaluating the forward rate using themethod:

forwardRate(0.10, 0.105, 1, 2)

which give a value of 11% with continuous compounding or 11.6278% with annual com-pounding. Now the forward rate agreement can be evaluated using the method:

forwardRateAgreement( 1000000, 0.12, 1, 2, 0.116278, 0.105)

which give a value of 3016.99.

10.3.3 Treasury Price

Within this subsection we describe the examples provided within the:

TreasuryPriceClient.java

118

Page 126: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

client which is contained within the Client\TreasuryPrice folder of this package. Withinthis client we provide one example for each of the methods within the TreasuryPrice

class.

Price of Bond

Problem: What is the theoretical price on a bond with principle sum of $100, 2 yearsuntil maturity which pays in coupon a one year of $5, and two years of $7; where the 1and 2 year zero rates are 5.2% and 5.7% respectively?

Solution: The price of the bond is evaluated by using the method:

priceOfBond(principleSum, timeToMaturity, zeroRateAtMaturity, payments, time-OfPayments, zeroRatesOnPaymentDates)

within the TreasuryPrice class, which gives a price of 100.218 . . ..

T-Bond Price

Problem: What is the price of a US T-bond which has a principle sum of $100 and has2.43 years until expiry? The bond pays coupons of $4, and is due to make payments in0.4, 0.9, 1.4, 1.9 and 2.4 years after which the bond is due to expire. Further note that therisk free interest rate is known to be 5%

Solution: The price of the T-Bond is 113.31, and is given by:

tbondPrice(100, 0.05, 2.43, couponPayments1, timeOfPayments1)

where:

� couponPayments1[] = {4, 4, 4, 4, 4}

� timeOfPayments1[] = {0.4, 0.9, 1.4, 1.9, 2.4}

Price of Treasury Zero bond

Problem: What is the price of a zero coupon UK gilt with a principle value of 100 poundsand a time to maturity of 3.4 years where the risk free interest rate for pounds is 6% ?

Solution: The price of zero bond is 81.54 . . ., which can be evaluated using the method:

zeroTBondPrice(100, 0.06, 3.4)

from the TreasuryPrice class.

119

Page 127: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

Yield to Maturity

Problem: What is the yield to maturity of a corporate bond with a principle value of $100and a market price of $120 and 4.2 years to maturity? The corporate bond pays annualcoupons of $10 in 0.7, 1.7, 2.7 and 3.7 years from now until expiry.

Solution: The yield to maturity is 0.114 . . . (or 11.4%), which we evaluate using themethod:

yieldToMaturity(100, 120, 4.2, couponPayments3, timeOfPayments3)

from the treasuryPrice class, where:

� couponPayments3 = {10, 10, 10, 10}

� timeOfPayments3 = {7, 1.7, 2.7, 3.7}

Yield to Maturity of a zero bond

Problem: What is the yield to maturity of a (corporate or treasury) bond which has amarket price of $90, $100, $110, a principle sum of $100, $110, $120 (respectively) and atime to maturity of either 1 or 2 years? Note, that all of these bonds pay a coupon of 5after the first year and where appropriate also after the second year.

Solution: Using the method:

zeroYieldToMaturity(principleSum, marketPrice, timeToMaturity)

from the TreasuryPrice class we obtain the following results:

� Market Price $90, Principle Sum $100, Time to maturity 1 year, Yield to maturity0.1053605156578262

� Market Price $100, Principle Sum $110, Time to maturity 1 year, Yield to maturity0.09531017980432488

� Market Price $110, Principle Sum $120, Time to maturity 1 year, Yield to maturity0.08701137698962982

� Market Price $90, Principle Sum $100, Time to maturity 2 year, Yield to maturity0.052680257828913175

� Market Price $100, Principle Sum $110, Time to maturity 2 year, Yield to maturity0.04765508990216244

� Market Price $110, Principle Sum $120, Time to maturity 2 year, Yield to maturity0.04350568849481491

120

Page 128: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

Remark In order to express the above results in the form α%, multiply each of the resultsby 100.

Yield to Maturity from Price

Problem: What is the yield from three different bonds with 4.25 years to maturity aprinciple sum of $100, which all pay semiannual coupon payments of $5 (with the firstpayment due immediately) and have a market price of $71, $86, $92?

Solution: Using the method:

yieldToMaturityFromPrice(price, payments, timeOfPayments)

within the TreasuryPrice class we obtain the following results:

� The yield of the bond with a market price of $71 is 0.212 . . ., or 21.2%

� The yield of the bond with a market price of $86 is 0.152 . . ., or 15.2%

� The yield of the bond with a market price of $92 is 0.132 . . ., or 13.2%

Remark Note that the payment of the principle sum at the maturity of the bond is thefinal payment, not the last coupon payment.

Par Yield

Problem: What is the par yield of a US T-Bond where:

� principle sum = 100

� maturity = 10 years

� 10 Year Zero Rate = 5.7%

� The bond pays annual coupons

� time to coupon payments in years = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

� zero curve on payment dates= 5.62, 5.62, 5.62, 5.63, 5.63, 5.64, 5.65, 5.67, 5.69, 5.7

Solution: The Par yield is 11.03%, and is evaluated using the method:

parYield (principleSum, maturity, annualOrSemiAnnual, maturityZeroRate, time-ToCouponPayments, zeroCurveOnPaymentDates)

from the TreasuryPrice class.

121

Page 129: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

10.3.4 Duration

Within this subsection we describe the examples provided within the:

DurationConvexityClient.java

client which is contained within the Client\DurationConvexity folder of this package.Within this client we provide one example for each of the methods within the DurationConvexityclass.

Price of Bond

Problem: What is the theoretical price of a bond which has a continuously compoundedyield of 6%, has a principle sum of $100 and pays semiannual coupons of 1 and has twoyears until maturity?

Solution: The price of the bond is 92.51 . . ., which we evaluated using the method:

priceOfBond(yield, payments, timeOfPayments, principleSum, timeToMaturity)

from the DurationConvexity class.

Duration of Bond

Problem: What is the duration of a bond with continuously compounded yield of 6%,has a principle sum of $100 and pays a semi-annual coupon of 1 and has two years untilmaturity?

Solution: The duration of the bond is 0.03024 . . ., which we evaluated using the method:

duration(yield, payments, timeOfPayments, principleSum, timeToMaturity)

from the DurationConvexity class.

Price change under Parallel Yield Curve Shift

Problem: What is the percentage change in the price of a bond which has a duration of0.73, when the yield curve experiences a parallel shift of 5 basis points (i.e. 0.0005%)?

Solution: The percentage price change in the price of the bond is −0.0365%, whichwe evaluated using the method:

percentagePriceChange (double deltaYield, double duration)

122

Page 130: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

from the DurationConvexity class.

Weight within Bond Portfolio

Problem: What is the weights of each bond within a bond portfolio with 10 assets withvalues 1, 2, 3, ..., 9, 10.

Solution: The weights can be evaluated using the method:

valueOfBonds

within the DurationConvexity class, which yields the values:

The weight of the 0 bond is 0.01818181818181818

The weight of the 1 bond is 0.03636363636363636

The weight of the 2 bond is 0.05454545454545454

The weight of the 3 bond is 0.07272727272727272

The weight of the 4 bond is 0.09090909090909091

The weight of the 5 bond is 0.10909090909090909

The weight of the 6 bond is 0.12727272727272726

The weight of the 7 bond is 0.14545454545454545

The weight of the 8 bond is 0.16363636363636364

The weight of the 9 bond is 0.18181818181818182

Duration of a Portfolio

Problem: What is the duration of the portfolio with assets of weight (0.25, 0.50, 0.25)and corresponding durations (0.73, 1.52, 3.34)?

Solution: The duration of the portfolio is 1.77749 . . ., which can be evaluated using themethod:

durationOfPortfolio (double[] duration, double[] weightOfBond)

from the DurationConvexity class. Which agrees with the solution in Example 6.

Duration of a Portfolio’s Value

Problem: What is the duration of the portfolio of US T-Bonds which consists of threeholdings with a market value a $250,000, $500,000 and $250,000; with corresponding du-rations of 0.73, 0.152 and 3.34?

Solution: The duration of the portfolio is 1.77749 . . ., which can be evaluated using themethod:

123

Page 131: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

durationOfPortfolio (double[] duration, double[] weightOfBond)

from the DurationConvexity class. Which agrees with the solution in Example 5.

Percentage Price change of Portfolio

Problem: What are the percentage price changes of a portfolio which contains the fol-lowing assets:

Asset 1 duration = 2.05 valueOfBond = 50030

Asset 2 duration = 3.65 valueOfBond = 25802

Asset 3 duration = 1.65 valueOfBond = 15620

and experiences a parallel shifts in the yield curve of 0.005, 0.01, 0.02 (i.e. 0.5%, 1% and2%)?

Solution: The percentage price change can be evaluated using the method:

percentagePriceChange (double deltaYield, double[] duration, double[] valueOfBond)

within the DurationConvexity class, which yield the price changes of:

� When the yield curve experiences a shift of 0.005 then the change in price of theportfolio is 0.012165496653982415, or equivalently 1.2165496653982415%

� When the yield curve experiences a shift of 0.01 then the change in price of theportfolio is 0.02433099330796483, or equivalently 2.433099330796483%

� When the yield curve experiences a shift of 0.02 then the change in price of theportfolio is 0.04866198661592966, or equivalently 4.866198661592966%

Percentage Price change of a Bond portfolio

Problem: What is the percentage price change of the bond portfolio with a duration of2.25 and a yield of 4%, which experiences a parallel shift in the yield curve of 0.01 (i.e. 1%)?

Solution: The percentage price change is evaluated using the method:

percentagePriceChange (duration, annualYield, deltaYield)

within the DurationConvexity class, giving a percentage change of −0.0216 . . ., or equiv-alently −2.16 . . .%.

124

Page 132: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

Percentage Price change of a bond portfolio (semi-annual)

Problem: Using the same situation as in the previous example, except that here the yieldof 4% is expressed semiannually (i.e. equivalent annual yield is less than 4%) and we wishto know the percentage price change?

Solution:The percentage price change is evaluated using the method:

percentagePriceChange (duration, yield, periodsCompoundedOver, deltaYield)

within the DurationConvexity class, giving a percentage change of −0.0220 . . ., or equiv-alently −2.20 . . .%.

Duration in a General Setting

Problem: What is the duration of an futures contract on a zero coupon bond which hasa market price of $10 and is known to experience a $0.50 price change for a 1% change inthe zero coupon yield curve?

Solution: The duration is evaluated using the method:

durationGeneral (price, deltaZero, changeInPrice)

within the DurationConvexity class, giving a value of the duration of −0.5.

Price change in the General Setting

Problem: The percentage change the price of the above futures contract under a changein the zero curve of 2% is?

Solution: The price change is evaluated using the method:

percentagePriceChangeGeneral (duration, deltaZero)

within the DurationConvexity class, giving a percentage price change of 0.1, or equiva-lently 10%.

Convexity of a Bond Portfolio

Problem: What is the convexity of a bond portfolio which consists of one bond whichpays an annual coupon of 1, with the next payment due in exactly 6 months and wherethe bond has exactly 5 years to maturity and yields 6%?

Solution: The convexity of the bond is evaluated using:

125

Page 133: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

convexity (yield, payments, timeOfPayments)

from the DurationConvexity class, giving a result of 8.1419 . . ..

Convexity when the Price is known

Problem: What is the convexity of a bond portfolio which consists of one bond whichpays an annual coupon of 1 and has a market price of $90? The next payment is due inexactly 6 months and the bond has 5 years to maturity.

Solution: The convexity of the bond when its market price is known is evaluated us-ing:

convexityFromPrice (price, coupons, timeOfCoupons)

from the DurationConvexity class, giving a result of 0.36547 . . ..

Chance in Price taken Convexity into account

Problem: What is the percentage change in the price of a portfolio of UK Gilts with aduration 4.1 years and a convexity of 0.43, when the yield of the portfolio changes by 25basis points?

Solution: The price change taking the convexity into account is given by:

bondPriceChange (duration, convexity, yieldChange)

from the DurationConvexity class, giving a result of −0.01024 . . ., or equivalently −1.02%.

Applying the Duration Hedge Ratio

Problem: An investor wishes to hedge his exposure from a bond portfolio to interestrate risks by the use of interest rate futures over the next 3 months. The investor holds aportfolio of T-bonds with an estimated forward duration of 5.3 years and a forward valueof $1,315,040, at the end of the intended hedge in 3 months.

The current price of the T-bond future is 94 and each futures contract represents anunderlying quantity of $100,000 face value of bonds. Therefore, the futures contract priceis $94,000. The expected cheapest-to-deliver bond at the expiry of the futures contract hasa duration of 8.20 years. In order to hedge the T-bond portfolio the investor needs to sellT-bond futures. What is the optimal number of T-bond futures which the investor willneed to sell in order to provide the best hedge during the next 3 months?

126

Page 134: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

Solution: The optimal number of T-Bond future the investor will need to sell in or-der be hedge the T-bond portfolio is 9. Since this is the closest number of contracts to theDuration hedge ratio which is 9.042 . . ., which is evaluated using the method:

durationHedgeRatio(94000, 8.20, 1315040, 5.3)

from the DurationConvexity class.

10.3.5 Database Example with JDBC Mediator

The Database Example is located inside the Client/BasicBonds/DatabaseExample direc-tory. The following steps are required before running the Database example.

1. Installing our Tables (MySQL Only)In order to create the database structure from which you are able to load the outputresults, you will need to run the ‘create.sql’ scripts in the ‘Data’ subdirectory. Openthe MySQL prompt from the ‘Data’ subdirectory and:

� Select (or create and then select) a database you can spare for a table namedCOUPONS. For example, if you have decided using the ‘test’ database, youwould optinally type the SQL command to create it (unless it already exists):

CREATE DATABASE test;

and then, you would type the following to select it:

USE DATABASE

� Run the ‘create.sql’ SQL script located in the ‘Data’ subdirectory of the currentdirectory by typing at the same MySQL prompt the following:

source create.sql

If this fails, make sure you have started the MySQL prompt from the ‘Data’subdirectory (this is where the database files for this example are stored).

2. Configuring the Database ConnectionEdit the Java source code file by filling out JDBC information about your database,such as:

(a) Driver Name (e.g. com.jdbc.mysql.Driver)

(b) JDBC Url (e.g. jdbc:mysql://localhost/test)

(c) Username and Password

If you are unsure whether you have a JDBC Driver for your Database, skip this stepand try running the example with the predefined values. If that fails, you will needto probably download the latest driver.

127

Page 135: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

3. Running the example

Run the ‘compile’ script (compile.sh for Linux, compile.bat for Windows) to compilethe Java source code, and then the ‘run’ script to see the results.

Uninstalling the Source Data

To delete all the tables used in this example, open the MySQL prompt from the ‘Data’subdirectory, select the database where you created the tables, and run the following:

source delete.sql

10.4 Yield of Fixed-Interest Bonds on Interest Pay-

ment Dates

Within this section we illustrate the use of the methods provided by the FixedInterestBondsclass. The source code for these examples can be found within the:

FixedInterestBondsClient

console client which is contained within the Client folder of this installation package.

10.4.1 Gross Interest Yield

Problem: Let’s assume that the quoted price of 10% bond is £102 (per £100 nominal).We need to calculate the interest yield for an investor who pays no tax.

Solution: The gross interest yield is 0.098, which can be calculated using the:

grossInteretYield(0.10, 102)

method within the FixedInterestBonds class.

10.4.2 Gross Redemption Yield

Problem: A treasury bond has a term to redemption of exactly 14 years. If the couponrate is 13% and the current market price is 123.9 what is the gross redemption yield?

Solution: The gross redemption yield is 0.098, and can be evaluated using the:

grossRedemptionYield(123.0,13,14)

method within the FixedInterestBonds class.

128

Page 136: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

10.4.3 Holding Period Return

Problem: An investor who pays no tax purchases a treasury bond with coupon rate 12.5%at a price of $114.25. Accrued interest on the settlement date was zero. After holding thebond exactly 3 years, the investor sold at $126.75. Ignoring expenses, what is the holdingperiod return per halt-year?

Solution: The holding period return is 0.069, and can be evaluated using the:

holdingPeriodReturn (114.25, 12.5, 126.75, 3)

method within the FixedInterestBonds class.

10.5 Interest Investments

10.5.1 Compound Interest

Problem: If Charles deposits $100 in a savings account at a federally insured bank nowat 12% interest, how much will accumulate in the account in 7 years if the interest accumu-lates annually? How much will Charles accumulate if interest is compounded semiannually?

Solution: Charles will accumulate $221.06 with annual compounding and $226.09 withsemiannual compounding.

Source Code: The source code for this example can be found inClient/Interest/CompoundInterest folder.

10.5.2 Effective Rate of Interest

Problem: You have an amount of money and you want to put them into a bank so it willearn interest. You have two offers:

� make an annual deposit with 4% yearly interest rate

� make a semiannual deposit with 2.5% semiannual interest rate

Knowing that you want to keep the money at the bank for a year, which is the best offer?

Solution: One way to solve this problem is to convert the annual rate of 4% into semi-annual rates. To perform this task using the method convertYearlyRate from theEffectiveAndNominalInterests class.

Source Code: The source code for this example can be found inClient/Interest/EffectiveAndNominalInterests folder.

129

Page 137: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

10.5.3 The accumulated value

Problem: Calculate the value of a series of payments of one per interval, payable in ar-rears for 5 intervals when the interest is 6%?

Solution: To calculate this we will use the method accumulatedSeriesOfPaymentsmethod from the AccumulatedValuesOfAnnuityCertain class.

Source Code: The Java source code for this example can be found inClient/Interest/AccumulatedValue folder.

10.5.4 Present Values

Problem: You need to decide between two business opportunities. The first opportunitywill pay $700 in 4 year’s time and the second opportunity will pay $850 in 6 year’s time.What represents the best business opportunity when the interest rate is expected to aver-age at 8% annually over the next four and six years?

Solution: We calculate the discount of these future sums and hence calculate the ini-tial amount of money that has to be invested in order to receive the respective future sum.To do this we will use the presentValue method from the PresentValues class. Theresults will give:

� $514.52 for the first opportunity

� $535.64 for the second opportunity

On the basis of the present value calculation we would choose the second opportunity sinceit represents an opportunity with a higher present value.

Source Code: The source code for this example can be found inClient/Interest/PresentValue folder.

10.5.5 Yield

Problem: What is the yield of an investment over six years if the investment makes aninterest payment in the first, second, third and sixth years at a rate of 5%?

Solution: To solve this problem one should use the method yield from the ValueRe-turnYield class. Set the array argument to [true true true false false true], thenumber of periods to 6 and the interest to 0.05.

Source Code: The source code for this example can be found inClient/Interest/Yield folder.

130

Page 138: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Examples Chapter 10

10.5.6 Repo agreements

Problem: What is the real return from an investment of $100.000, which increases invalue to $150.000, after one year where the rate of inflation was 1%?

Solution: To solve this problem one should use the method realReturn from the Re-alReturns class.

Source Code: The source code for this example can be found in Client/Interest/Repofolder.

131

Page 139: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Chapter 11

Guide to WebCab Components

11.1 The Company

WebCab is a privately owned British company that has built business solutions since itsinception in 1999. We continue to refine and develop our Mathematical and FinancialFramework which we have implemented on the Office, J2SE, J2EE, Delphi, COM and.NET platforms.

11.2 Presentation of Products

Our aim is to provide good quality, useful information to help you decide which componentbest suits your development needs. WebCab is committed to honesty and realism whenpresenting our products. In order to achieve this a detailed, clear and factual style forpresentation is adopted within our documentation and marketing material.

11.3 Supported Clients, IDEs, Containers and DBMSs

By supporting all major development, server and client side technologies we preserve thedevelopers flexibility in making tool and architecture decisions. In particular, each productcontains detailed examples and advice concerning the integration and use of our moduleswithin existing development tool and infrastructure platforms. In short, our documenta-tion provides the information that the developer needs to get their applications up andrunning as quickly and as easily as possible.

We detail exactly how the developer can use the .NET Component, COM Componentand XML Web service contained within this product with the following technologies:

� Client containers - Internet Explorer, Mozilla, Microsoft Office

� IDEs - Microsoft’s Visual Studio .NET (incl. Visual C.NET, Visual Basic .NET,Visual C++.NET), Microsoft’s Visual Studio 6 (incl. Visual C++, Visual Basic),

132

Page 140: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Guide to WebCab Components Chapter 11

Borland’s C++ Builder (incl. C++ 2005, C++BuildX), .NET Framework SDK,Office’s Visual Basic Editor

� Client Side Technologies - Application Clients, ASP.NET, C#, VB.NET, C++.NET

� XML Web services - Implemented in C#, VB.NET

� DBMS - Oracle, IBM DB2, SQL Server, Sybase, MySQL

� Platforms - Windows 2003/XP/2000/NT/9x

For these technologies we include all installation scripts and template examples which willhelp the developer quickly and easily assemble their multi-tier enterprise application.

11.4 Transparent Functionality

All technical and business intelligence incorporated within our products is described withinthe associated documentation. This allows the developer to see the nature of the method-ology implemented within our proprietary algorithms.

11.5 Company Culture and Activity

WebCab Components is focused solely on the production of high quality software moduleswithin our Financial and Mathematical Framework. The WebCab team contains a widerange of expertise and experience from the academic, investment banking and softwaredevelopment worlds.

Within the company there exists significant internal competitive pressures with constantpeer review and evaluation, resulting in higher quality products, which adhere to highprofessional standards and offer extended functionality.

11.6 Product Life cycle

We continuously add value to our products by evolving them according to new .NETFramework specifications, customer feedback and market demands. We give particularemphasis to incorporating our clients suggested modifications and additions into our prod-uct development cycle.

11.7 Support, Warranty and Upgrades

WebCab warrants that each component will perform substantially in accordance with theaccompanying written material. We provide with all our products without charge sixty(60) days product support services including fixing bugs, compatibility issues and other

133

Page 141: WebCab Bonds for .NET v2 · Preface This documentation accompanies the WebCab Bonds .NET Service. WebCab Bonds con-tains methods which enable the implementation of models for the

Guide to WebCab Components Chapter 11

technical support issues.

All maintenance updates (including service packs) will be distributed free of additionallicense cost.

Dr Ben Fairfax

Founder and CEO

WebCab Components - From Developer, To Developer

.NET and all .NET-based marks are trademarks or registered trademarks of Microsoft Corporation,

Inc. in the U.S. and other countries.

134