# CFA Level 1 Review: Quantitative Finance, Time Value of Money.

In this post, I will present a summary of the quantitative finance part of the CFA Level 1 exam.

The time value of money is a trivial concept in Finance, which can be summarized as “one dollar today is better than one dollar tomorrow“, because of the risk-free interest rate $r$. The following formulas allow to compute the present value $PV$ of a future cash flow $FV$ (in case of a single cash flow) or $CF_i$ (in case of several future cash flows).
$$PV=FV (1+r)^{-t}=\frac{FV}{(1+r)^t} \quad (1)$$

$$PV=\sum_{i=1}^N \frac{CF_i}{(1+r)^i} \quad (2)$$

That’s all trivial.

If there are infinite cash flows of constant value $c$, the product is called a perpetuity and its values is computed as follows:

$$PV_a=\frac{c}{r}$$

The only tricky part comes when you have multiple cash flows coming at the beginning $PV_b$ or at the end of the period $PV_e$. To compute the value of the investment, you just have to know that $PV_b = (1+r) PV_e$ as the two computation are basically shifted one period from one to the other.

When trying to compute the value of a project, the idea is to compute the NPV (net present  value) of the project which is the present value of the project cash flows which can be computed easily using (2). Any project with $NPV < 0$ should be rejected.

That was pretty easy anyway.

I’ll be back with more.

# A new challenge has entered the ring!

My first social life in the first 6 months of year 2012 has been compromised by a new challenge I decided to take on this year, the Chartered Financial Analyst (CFA) curriculum.

The CFA program is divided in 3 exams denoted Level I, II and III. The candidate gets the CFA designation upon completing the 3 levels which can be taken every year. I am hence taking the Level I in June.

The reason why I decided to take on this challenge is because I believe it contains interesting general finance topic and covers some of the basic concepts of quantitative finance. Let’s face it, it’s also good value to my CV if I can manage to pull it off.

I will try from time to time to put some summaries of what  I have encountered, in order to help me remember the formulas and to share with the community the key concepts.

I must add that I will use the resources provided by Kaplan Schweser which are from what I have seen so far a must-have in order to complete this curriculum successfully, especially if you do have a full position at the same time.

I’ll try to soon add my summary of the quantitative finance part.

# My wishes for 2012

Good evening everyone,

As we are converging towards the end of 2011, I would like to come back on the major events of this year and share with you my views on the upcoming one.

# Finance

Let’s first start by  a global overview of the financial world. As a matter of fact, 2011’s second semester was marked by the debt crisis and we saw again that the idiom “too big to fail” was an enormous fallacy not only for companies, but also for countries. It is very important to keep that in mind for diversifying portfolios correctly. We have seen a lot of volatility in exchange rates and it is hence important to consider all available currencies to have an optimal money market allocation.

## But what went wrong exactly?

I believe that states were relying on economical models based on facts such as life expectancy which are now completely outdated. Back in the days, people were expected to die on average around their 70’s, whereas people in developed countries are now expected to leave beyond 80. If the retirement plans were expected to last for 8 years on average, it would now be 18 years. People have to understand that the world has changed, and hence that retirement age has to go beyond their current levels. Politically, this is very difficult to put in place, as we have seen for example in France, but congratulations to the French government for keeping their heads up and standing firm. I believe that people are now taking shortcuts by only blaming the financial world for the current economical issues. In a sense, everybody is responsible: the financial institutions, the politicians and the people themselves. We have to stop delaying problems and increasing the debt, we are now paying for the mistakes our parents and grandparents made. Let’s try to look forward a bit more and to create new models which will avoid such catastrophes in the future.

## What’s to come in 2012?

I believe the equity markets will go back up during the 2012 year if the European states managed to find suitable solutions by taking drastic social decisions which are necessary to avoid a global recession. I believe the commodity markets are a good investment option as demand will stay firm if the global recession is avoided. Gold remains a question to me, as I personally believe it is overpriced at the moment. However, if investors want to fly to safety, we could see the gold market breaking all time highs again. Do you want to buy Euros at 1.20? I’m not really sure. If the European governments keep refusing to face reality and the crisis gets worse, the SNB’s floor might very well break and see Euros go back to parity with the Swiss franc, even beyond.

# Politics

I would like to come back to the Arab spring (or Arab awakening) which saw some of the worse dictators loose the power and people. Let’s try not to make the same mistake again. Let’s try not to put radical governments in place and have to do it all over again in 10 years. A lot of blood was spread to get to where we are now, we do not want this to have been done in vain.

Apart from that, I would like to wish you all and your beloved ones all the success in the world, health and prosperity for 2012. I will try to add more content on a regular basis to the blog in order to provide you with more insight on Quantitative Finance and Computer Science.

Thanks for following this blog and leaving your comments, and see you next year!

Jeremie

# Handling interaction between the Business Layer and the UI with the MVVM design pattern

Warning: DOMDocument::loadXML(): Space required after the Public Identifier in Entity, line: 1 in /home/clients/d6bcc13f01d956648e26ee7f6a76facd/blog/wp-content/plugins/wordpress-amazon-associate/APaPi/AmazonProduct/Result.php on line 149

Warning: DOMDocument::loadXML(): SystemLiteral " or ' expected in Entity, line: 1 in /home/clients/d6bcc13f01d956648e26ee7f6a76facd/blog/wp-content/plugins/wordpress-amazon-associate/APaPi/AmazonProduct/Result.php on line 149

Warning: DOMDocument::loadXML(): SYSTEM or PUBLIC, the URI is missing in Entity, line: 1 in /home/clients/d6bcc13f01d956648e26ee7f6a76facd/blog/wp-content/plugins/wordpress-amazon-associate/APaPi/AmazonProduct/Result.php on line 149

Warning: Invalid argument supplied for foreach() in /home/clients/d6bcc13f01d956648e26ee7f6a76facd/blog/wp-content/plugins/wordpress-amazon-associate/APaPi/AmazonProduct/Result.php on line 160

Hi everyone,

I’m taking the time to write this little post because I came across a great design pattern to handle interaction between the Business Layer (BL) and the user interface (UI).

This problem usually arises when creating multi-layers application which can be used by different kinds of users. As this blog is mainly dedicated to finance, I’ll take as an example an application which provides access to the financial time series of different assets.

When you implement this kind of programs, you might want to consume the business objects from, say, a backtesting platform to see how a strategy performs over some interval. However, you might also simply want to create a UI in WPF to see how the different assets performed using your favorite charting library.

The thing is, when you tackle user interaction, your objects need to be “interactive”. That is, you might want to rename you asset, or you might want to be willing to assign an asset to a different asset class, and you want the UI to update automatically.

Let’s take a simple example. You have a list of assets displaying the assets names. When you click on an asset in the list, the details show up in a form somewhere else on the window. If you were to modify the name of the asset, you would like the change to happen also in the list. To do so, you need to notify the list (the UI) that the (business) object has changed, otherwise, nothing will happen.

To notify changes of a property, you can implement the INotifiedPropertyChanged interface from the .Net framework.

However, there is a problem with implementing such interface within your Business Layer. Indeed, this means that your objects will handle the notifications, even when no UI is looking for it (in the backtesting platform for example). This could result in useless computations and reduce the efficiency of your computations.

This is why you would like to use the MVVM design pattern (for Model-View-ViewModel). The idea is to create enhanced versions of the objects which implement all the features required for user interaction. This object would be implemented in a different project which include the Business Layer. In our example, we would create a class called, for example, AssetViewModel which has a private property containing the business class Asset and providing access to all necessary properties with notifications upon changes.

This pattern can then be extended to represent the data available behind a complex window, as described in this article by Josh Smith. You then just set the View Model of the window as its DataContext, which allows you to bind the UI elements to it, and simply remove all the code behind.

Finally, another great advantage of MVVM is that you can test the UI workflow using simple Unit Test on your ViewModels.

See you next time!

# Asynchronous Financial Data processing using F#

Hi everyone,

I was looking at a book to find some algorithm to detect clusters within financial data. I managed to find a decent algorithm for that matter, but I then wanted to test it on some real data.

Hence, I had to get the data from somewhere and I chose to use Yahoo! Finance. The thing is, I wanted to do it in an automatized way in order to be able to re-use the module for further projects.

I remembered Luca Bolognese’s presentation of F# a few years back (certainly one of the best presentations I’ve ever seen) and I thought it was a good time to give it a try.

The idea is quite simple: you can import data from Yahoo! Finance by parsing the CSV files the website produces. These files are actually generated automatically, which means that you can access them by querying the right URL with the right parameters.

The following module shows how to generate the right query to get the CSV file from Yahoo! Finance:

module QueryModule
open System
let dateToList (d:DateTime) = [d.Month;d.Day;d.Year]

let parameters =['a';'b';'c';'d';'e';'f']

let parametersToString (d1:DateTime) (d2:DateTime)=
let datesList = (dateToList d1) @ (dateToList d2)
let rec innerFunc (dList: int list) pars =
match pars with
| [] -> ""
| x::[] -> x.ToString() + "=" + dList.Head.ToString()
| x::y -> x.ToString() + "=" + dList.Head.ToString() + "&" + (innerFunc dList.Tail y)

innerFunc datesList parameters

let getFileUrl (ticker:string) start stop =
"http://ichart.finance.yahoo.com/table.csv?s="+ticker+"&"+(parametersToString start stop)+"&ignore=.csv"


The idea is now to write a module to download this data. This would be pretty straightforward and I wouldn’t make you waste your time by reading further code right here.

What I’m trying to do here is to download these files asynchronously. Doing this using C# is possible but requires some heavy coding and the result will most likely contain some bugs. F# (and functional programming languages in general) allows you to do it much more easily.

Let’s see how to implement an asynchronous function in F# then:

module DownloadModule
open QueryModule
open Microsoft.FSharp.Control.WebExtensions
open System
open System.Net
open System.IO

let parseData (rawData:string) =
rawData.Split('\n')
|> Array.toList
|> List.tail
|> List.map (fun x -> x.Split(','))
|> List.filter (fun x -> x.Length = 7)
|> List.map (fun x -> (Convert.ToDateTime(x.[0]),float x.[6]))

let getCSV ticker dStart dEnd =
async   {
let query = getFileUrl ticker dStart dEnd
let req = WebRequest.Create(query)
use! resp = req.AsyncGetResponse()
use stream= resp.GetResponseStream()
let ts = parseData content
return ts
}


The whole trick in this code resides in the “async” block and the “use!” keyword. Basically, “use!” tells to F# not to wait for the result, that is, to proceed asynchronously if possible.

You now can run this function in parallel to download multiple ticker as follows:

let testPrices=
["MSFT";"YHOO"]
|>List.map (fun x -> getCSV x (DateTime.Parse("01.01.2000")) (DateTime.Parse("01.01.2010")))
|> Async.Parallel
|> Async.RunSynchronously;;


This works fine and it’s much faster than it would have been if the list was processed sequentially.

I pushed the example a little further by thinking: “What if I want to do some operation on the time series now?”.

Well, I could wait until the parallel execution is done and the run the following function to get the returns synchronously:

module AnalysisModule
open System

let getReturns (prices:(DateTime *float)list) =
[for i in 1..(prices.Length-1) -> i]
|> List.map (fun i ->(fst (List.nth prices i), (snd (List.nth prices i))/(snd (List.nth prices (i-1) )) - 1.0))


That wouldn’t be optimal; once the download of MSFT is done, I don’t need to wait until the download of YHOO is done as well before starting to process the returns…

So, how can I do this easily, without modifying any of the previous function I wrote.

let testReturns =
["MSFT";"YHOO"]
|> List.map (fun ticker -> async {
let! prices = getCSV ticker (DateTime.Parse("01.01.2000")) (DateTime.Parse("01.01.2010"))
return getReturns prices
})
|>Async.Parallel
|>Async.RunSynchronously;;


This way, everything is computed in parallel and I have a really great performance!

Hope you enjoyed this little demo!

See you next time!