Category Archives: General

When the Dark Knight rises profound human behavior questions

Good evening everybody,

I decided to take a few minutes to write this post as I witnessed today two incredible things as I went to the Swiss premiere of “Batman: The Dark Knight Rises”.

First of all, the movie itself; it’s astonishing. I really liked it. I don’t usually go to the theater to watch movies these days as I think the quality is not worth the price anymore in most cases. However, as I’m a big fan of Batman, especially of the latest trilogy – and especially the last opus -, I just couldn’t resist. The last time I remember enjoying a movie in a cinema was for “Batman: The Dark Knight”, and I was really scared to be disappointed by this one. Obviously, I wasn’t; it was 160 minutes of mind-blowing sensational action combining surprise and emotion. I’m not gonna spoil any of it, trust me, just go and watch it.

As we all know, the release of the movie was overshadowed by the atrocious killings that occurred in the US at the premiere a few nights ago. I fully understand the emotion that can arise from such tragedy but today I witnessed a clear example of human irrationality and misinterpretation of available variables. Let me explain. As we entered the theater, there were a few security guards searching people for, I suppose, weapons and tear gas. Seriously, how ridiculous is that?

If we analyze mathematically the reasoning beyond such a pathetic display, we see the following steps. A guy, who is mentally unstable, in a country where you are allowed to buy weapons and who was just dumped by his girlfriend killed a dozen people and injured 50 in a movie theater at the premiere of a Batman movie. A year ago, Anders Behring Breivik, also remote to the society, killed even more people on an island. A few years back killings occurred at the Columbine High School. What are the common variables here? Well, from what I’ve witnessed today, some people think that the movie where the killings occurred was a determining variable.

It is really incredible how irrational people can be and it is another great example of how we can miss the big picture by focusing our attention on some noisy irrelevant variables. You can clearly see this happens in financial markets: even though the macro-economic outlook is bad, a single speech can trigger a market rally which will of course turn around straightaway as the underlying fundamental problem was not solved.

This is my food-for-thought of the day, but it might really be the ultimate problem of our modern society.  I don’t pretend to be able to enumerate what the reasons behinds the various killings are, but I would certainly not look at the specific movie that was shown in the movie theater when the tragedy happened. Maybe the guy had a blue shirt, maybe the guy ate a cheeseburger that day, should we avoid blue shirts? should we stop eating cheeseburgers?

A theory which I think is really plausible, is that these catastrophes occur purely randomly: you just can’t predict them, it’s just noise. Whichever source you might identify – video games, violent movies, political regimes, financial systems, social unrest, poverty – and even if you removed them all, it is possible that some individual are just inherently bad and will provoke chaos. I will add a few quotes from the Joker in “Batman: the Dark Knight” which illustrate the kind of personality I’m referring to:

[The Joker] I just did what I do best. I took your little plan and I turned it on itself. Look what I did to this city with a few drums of gas and a couple of bullets. Hmmm? You know… You know what I’ve noticed? Nobody panics when things go “according to plan.” Even if the plan is horrifying! If, tomorrow, I tell the press that, like, a gang banger will get shot, or a truckload of soldiers will be blown up, nobody panics, because it’s all “part of the plan”. But when I say that one little old mayor will die, well then everyone loses their minds!

[The Joker] Introduce a little anarchy. Upset the established order, and everything becomes chaos. I’m an agent of chaos. Oh, and you know the thing about chaos? It’s fair!

[The Joker] Do I really look like a guy with a plan? You know what I am? I’m a dog chasing cars. I wouldn’t know what to do with one if I caught it! You know, I just… *do* things.

I guess everybody can choose his theory: either catastrophes are completely random or you can try to predict it. It’s like in financial markets: either markets are efficient (and you should just optimize you risk adjusted return) or they are not (and it makes really sense to do some active management).

In anyway, the bottom line is: focus on meaningful variables, and forget the noise.

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

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()
            use reader = new StreamReader(stream)
            let content = reader.ReadToEnd()
            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!