Archive for the ‘Finance’ Category

R/Reuters Real-Time Data Extension

Thursday, December 11th, 2008

Last week, I posted an R extension DLL that downloads historical data from Reuters using the SFC API. This time around, I am posting an extension DLL that can subscribe to real-time updates using the RFA API. This extension allows you to specify a list of items and data fields, and subscribe for a specified amount of time to updates on those items.

Here is an example:

# Load the DLL
dyn.load("RfaClient")

# Low-level subscription function wrapper
rsub < - function(time, items, func, sessionName, config, debug) {
.Call("subscribe", as.integer(time), items, func , sessionName, config, debug)
}

# Define items and fields to subscribe to
items <- list()
fields <- c("BID","ASK","TIMCOR")
items[[1]] <- c("IDN_SELECTFEED", "GBP=", fields)
items[[2]] <- c("IDN_SELECTFEED", "JPY=", fields)

# Callback function (invoked when data items update)
callback <- function(df) {
print(paste("Received an update for",df$ITEM, ", update time=", df$TIMCOR))
}

# Subscribe for 5 seconds using the supplied config parameters
rsub(5000, items, callback, "clientSession", "rfa.cfg", FALSE)

A short introductory guide is supplied:

Introduction (PDF)

Introduction (PDF)

The functionality is pretty basic right now, and there may be issues with the code (e.g. memory leaks, performance issues). Any feedback is gratefully received.

The package, including source, can be downloaded here:

rfaclient.zip

It was built with R 2.8.0 and RFA C++ 6.0.2, using Visual C++ 2005.

R/Reuters Time Series Data Extension

Saturday, December 6th, 2008

This is an upload of the historical data retrieval component of the R/Reuters interface that I presented at the R user conference in August 2008 (see the presentation here).

The extension is a C++ DLL that uses the Reuters SFC API to retrieve limited time series data from the TS1 time series service. It is compiled under Visual Studio 2005 and Windows XP, but could be cross-compiled to Linux without too much difficulty.

The DLL comes with a .R file that contains commands to load the DLL, and set up some necessary initialization. If you are familiar with Reuters infrastructure and APIs, the following points are important:

  • This extension has been built with support for SSL infrastructure only;
  • You will need to provide appropriate parameters to the init() function (see the documentation for details).

The extension, plus the associated source and documentation can be downloaded here:

reuters_ts1.zip

The package makes retrieving time series data for analysis easy: I have provided a single entrypoint for retrieving data, called fetch(). This will return a data frame with a Date column and one or more data columns, depending on the data being requested.

Some examples follow:

First, an example that fetches historical daily price data for Microsoft stock and creates a price/volume chart (the historical data returned contains OHLC price data and volume data):

msft.vol < - fetch("MSFT.O",sd="1/1/2008",ed="10/31/2008")
layout(matrix(c(1,1,1,1,2,2), 3, 2, T))
plot(msft.vol$Date, msft.vol$CLS, main="MSFT Close Price", type="l", ylab="", xlab="Date")
plot(msft.vol$Date, msft.vol$VOL, main="Volume", type='h', ylab="", xlab="")

MSFT Chart

MSFT Chart

The next example retrieves historical price data for the highest and lowest-rated ABX subprime indices – sometimes called the barometers of the subprime crisis:

abx.aaa < - fetch("ABXAA38FGB=MP", sd="1/1/2007", ed="12/1/2008", t="d")
abx.bbb <- fetch("ABXBM38FGB=MP", sd="1/1/2007", ed="12/1/2008", t="d")
op <- par(mfcol=c(2,1),las=2)
plot(...)

ABX AAA and BBB- Indices

ABX AAA and BBB- Indices

Finally, an example that shows the yield spreads between AAA and BBB-rated benchmark corporate bonds, and a 10-year US treasury bond:

library(zoo)
aaa10y < - fetch("AAAUSD10Y=", n=600, t="d")
bbb10y <- fetch("BBBUSD10Y=", n=600, t="d")
ust10y <- fetch("US10YT=RR", n=600, t="d")

aaa10y.series <- zoo(aaa10y, order.by=aaa10y$Date)
bbb10y.series <- zoo(bbb10y, order.by=bbb10y$Date)
ust10y.series < - zoo(ust10y, order.by=ust10y$Date)

full.series <- merge(aaa10y.series, bbb10y.series, ust10y.series, all=FALSE)
...

Yield Spreads

Yield Spreads

There are many more examples, plus documentation of the required R functions and their usage, in the manual:

Introductory Manual

Introductory Manual

UPDATE: The above package was built in Visual C++ 2005 using debug mode. I have attached another package below that was built in release mode. This package also includes the msvcrt redistributable DLLs, in case you get linker issues when R is loading the extension (as it was built using the MSVCRT 8.0 runtime).

reuters_ts_release1.zip

NB: This extension also depends on the Reuters SFC DLLs – specifically it loads ssl45w3280.dll and sipc3280.dll. These are available in the Reuters SSL C++ SDK version 4.5.5 (the latest version at the time of writing). I cannot legally redistribute these DLLs, so I would suggest that you download them from the Reuters development support site. Once downloaded, these DLLs should be in your system PATH (or in the same directory as the extension), so they can be loaded on demand.

DISCLAIMER: This software is not developed by Thomson Reuters and Thomson Reuters are in no way responsible for support or malfunction of this software.

Presentation at UseR! 2008

Tuesday, August 12th, 2008

Today is the second day of UseR! 2008 in Germany, and I will be giving a short talk on a market data interface I developed for R a while back. The confererence is apparently the largest R user conference yet, with over 400 participants, from all areas of industry and academia.

Here are the slides:

r_market_data

For some reason, I couldn’t get the Beamer package to number my contents correctly, so it looks a little strange.

Black-Scholes in R

Monday, April 28th, 2008

Here is a simple implementation of the Black-Scholes pricing formula in R. This will return a two-element vector containing the calculated call and put price, respectively.

# Black-Scholes Option Value
# Call value is returned in values[1], put in values[2]
blackscholes <- function(S, X, rf, T, sigma) {
    values <- c(2)

    d1 <- (log(S/X)+(rf+sigma^2/2)*T)/sigma*sqrt(T)
    d2 <- d1 - sigma * sqrt(T)

    values[1] <- S*pnorm(d1) - X*exp(-rf*T)*pnorm(d2)
    values[2] <- X*exp(-rf*T) * pnorm(-d2) - S*pnorm(-d1)

    values
}

Example use:

> blackscholes(100,110,.05,1,.2)
[1] 6.040088 10.675325

Black-Scholes in Excel, Part II

Friday, December 22nd, 2006

Following on from the post a few weeks ago on a simple Black-Scholes Excel macro, here is a follow up, with a slightly updated version that also calculates the major greeks (vega, gamma and delta). The formulae are from Hull’s book, or see here for examples of the closed-form greeks.

Usage of the spreadsheet is identical to the previous example, so refer to that post. The only difference is the output, which now looks like this (click to enlarge):

black-scholes-greeks.png

The spreadsheet is available for download here, and the code is below for reference.

Function BlackScholes(SpotPrice As Double, ExercisePrice As Double,
        TimeToMaturity As Double, RiskFreeRate As Double, sigma As Double,
        Optional DividendYield As Double) As Double()

    Dim d1 As Double
    Dim d2 As Double
    Dim Nd1 As Double
    Dim Nd2 As Double
    Dim N_dash_d1 As Double
    Dim ResultArray() As Double
    Dim gamma As Double
    Dim vega As Double
    Dim theta As Double

    ReDim ResultArray(10) As Double

    If (IsMissing(DividendYield)) Then
        d1 = WorksheetFunction.Ln(SpotPrice / ExercisePrice)
        + ((RiskFreeRate + (0.5 * (sigma ^ 2))) * TimeToMaturity)
    Else
        d1 = WorksheetFunction.Ln(SpotPrice / ExercisePrice)
        + ((RiskFreeRate - DividendYield + (0.5 * (sigma ^ 2))) * TimeToMaturity)
    End If

    d1 = d1 / (sigma * (TimeToMaturity ^ (1 / 2)))
    d2 = d1 - (sigma * (TimeToMaturity ^ (1 / 2)))
    Nd1 = WorksheetFunction.NormSDist(d1)
    Nd2 = WorksheetFunction.NormSDist(d2)

    'Call Value
    If (IsMissing(DividendYield)) Then
        ResultArray(0) = (SpotPrice * Nd1) - (ExercisePrice * Exp(-RiskFreeRate * TimeToMaturity) * Nd2)
    Else
        ResultArray(0) = Exp(-DividendYield * TimeToMaturity)
        * (SpotPrice * Nd1) - (ExercisePrice * Exp(-RiskFreeRate * TimeToMaturity) * Nd2)
    End If

    'Call Delta
    ResultArray(1) = Nd1 * Exp(-DividendYield * TimeToMaturity)

    'Call Gamma
    N_dash_d1 = (1 / ((2 * WorksheetFunction.Pi) ^ (1 / 2)) * (Exp((-d1 ^ 2) / 2)))
    gamma = (N_dash_d1 * Exp(-DividendYield * TimeToMaturity)) / (SpotPrice * sigma * (TimeToMaturity ^ (1 / 2)))
    ResultArray(2) = gamma

    'Call Vega
    vega = SpotPrice * (TimeToMaturity ^ (1 / 2)) * N_dash_d1 * Exp(-DividendYield * TimeToMaturity)
    ResultArray(3) = vega

    'Call Theta
    theta = -(SpotPrice * N_dash_d1 * sigma * Exp(-DividendYield * TimeToMaturity)) / (2 * (TimeToMaturity ^ (1 / 2)))
    theta = theta + (DividendYield * SpotPrice * Nd1 * Exp(-DividendYield * TimeToMaturity))
    theta = theta - (RiskFreeRate * ExercisePrice * Exp(-RiskFreeRate * TimeToMaturity) * Nd2)
    ResultArray(4) = theta

    'Put Value
    If (IsMissing(DividendYield)) Then
        ResultArray(5) = Exp(-RiskFreeRate * TimeToMaturity) * ExercisePrice
        * (1 - Nd2) - SpotPrice * (1 - Nd1)
    Else
        ResultArray(5) = Exp(-RiskFreeRate * TimeToMaturity) * ExercisePrice
        * WorksheetFunction.NormSDist(-d2) - Exp(-DividendYield * TimeToMaturity)
        * SpotPrice * WorksheetFunction.NormSDist(-d1)
    End If

    'Put delta
    ResultArray(6) = (Nd1 - 1) * Exp(-DividendYield * TimeToMaturity)

    'Put Gamma
    ResultArray(7) = gamma

    'Put Vega
    ResultArray(8) = vega

    'Put Theta
    theta = -(SpotPrice * N_dash_d1 * sigma * Exp(-DividendYield * TimeToMaturity)) / (2 * (TimeToMaturity ^ (1 / 2)))
    theta = theta - (DividendYield * SpotPrice * WorksheetFunction.NormSDist(-d1) * Exp(-DividendYield * TimeToMaturity))
    theta = theta + (RiskFreeRate * ExercisePrice * Exp(-RiskFreeRate * TimeToMaturity) * WorksheetFunction.NormSDist(-d2))
    ResultArray(9) = theta

    BlackScholes = ResultArray
End Function

The CME Globex Electronic Futures Trading System

Saturday, December 16th, 2006

The story of the Reuters Globex futures trading system developed for the Chicago Mercantile Exchange is a classic ETS (Electronic Trading System) case study. Originally devised in 1987 and launched in 1992, the product was plagued with technical difficulties and defects, and the general reluctance of the traditionally pit-based futures trading community to accept its merits.

On its first day of business in June 1992, 2,063 futures contracts traded on CME Globex. Today, an average of more than one million contracts a day are traded on CME Globex, accounting for over 50% of total CME volume.

See http://www.cme.com/trading/get/abt/welglobex951.html

The orginal product was beset with issues, and there were still serious doubts as to whether an ETS could ever replace the open outcry system:

See http://sigchi.org/chi95/proceedings/papers/jll_bdy.htm

However, the success of Globex (although still not without its issues – see http://www.finextra.com/fullstory.asp?id=13768) is a strong validation of the potential efficiency gains that can be realised on an ETS platform.

Excel Black-Scholes Function

Thursday, November 23rd, 2006

[UPDATE: After reading this post, see here for an updated version of the spreadsheet].

The Black-Scholes option valuation formula for an option paying a continuous dividend yield is the following:

eq1.png

Where

eq2.png

and

eq3.png

Attached is a simple Excel function that calculates the Black-Scholes option value for a specific set of input parameters. Currently, it just calculates the call value – if you use it as an array function, it will return a 4-element array with call value, call delta, put value, put delta, respectively. You could extend it pretty easily to calculate the rest of the Greeks.

Here is the code for the function (To create an Excel function, press ALT-F11 in your workbook and select Insert>Module. Note that the dividend yield parameter is optional.

Function BlackScholes(SpotPrice As Double, ExercisePrice As Double,
        TimeToMaturity As Double, RiskFreeRate As Double, sigma As Double,
        Optional DividendYield As Double) As Double()

    Dim d1 As Double
    Dim d2 As Double
    Dim Nd1 As Double
    Dim Nd2 As Double
    Dim ResultArray() As Double

    ReDim ResultArray(4) As Double

    If (IsMissing(DividendYield)) Then
        d1 = WorksheetFunction.Ln(SpotPrice / ExercisePrice) +
                ((RiskFreeRate + (0.5 * (sigma ^ 2))) * TimeToMaturity)
    Else
        d1 = WorksheetFunction.Ln(SpotPrice / ExercisePrice) +
                ((RiskFreeRate - DividendYield + (0.5 * (sigma ^ 2))) * TimeToMaturity)
    End If

    d1 = d1 / (sigma * (TimeToMaturity ^ (1 / 2)))
    d2 = d1 - (sigma * (TimeToMaturity ^ (1 / 2)))
    Nd1 = WorksheetFunction.NormSDist(d1)
    Nd2 = WorksheetFunction.NormSDist(d2)

    'Call Value
    If (IsMissing(DividendYield)) Then
        ResultArray(0) = (SpotPrice * Nd1)
                - (ExercisePrice * Exp(-RiskFreeRate * TimeToMaturity) * Nd2)
    Else
        ResultArray(0) = Exp(-DividendYield * TimeToMaturity) * (SpotPrice * Nd1)
                - (ExercisePrice * Exp(-RiskFreeRate * TimeToMaturity) * Nd2)
    End If

    'Call Delta
    ResultArray(1) = Nd1

    'Put Value
    If (IsMissing(DividendYield)) Then
        ResultArray(2) = Exp(-RiskFreeRate * TimeToMaturity)
                * ExercisePrice * (1 - Nd2) - SpotPrice * (1 - Nd1)
    Else
        ResultArray(2) = Exp(-RiskFreeRate * TimeToMaturity) * ExercisePrice
                * WorksheetFunction.NormSDist(-d2) - Exp(-DividendYield * TimeToMaturity)
                        * SpotPrice * WorksheetFunction.NormSDist(-d1)
    End If

    'Put delta
    ResultArray(3) = -WorksheetFunction.NormSDist(-d1)

    BlackScholes = ResultArray
End Function

Save this, and set up the input parameters in Excel. Select a range of 4 cells, and then click the f(x) function selection button. Choose from the list of User Defined functions, and then select BlackScholes. Excel will prompt you for the input parameters:

ExcelDialog.png

When you are finished inputing the parameters, press CTRL+SHIFT+ENTER to execute the function. Excel will populate the four cells with the calculated option values:

ExcelDialog2.png

A sample workbook is attached:BlackScholes.xls