You are on page 1of 460

Quantitative Finance Collector

abiao

Published: 2010
Categories(s): Non-Fiction, Business & economics, Finance
Tag(s): "quantitative finance" "financial engineering" "mathematical fin-
ance" quant "quantitative trading"

Please read update at http:://www.mathfinance.cn 1


Quantitative Finance Collector is simply a record of my financial engin-
eering learning journey as a master in quantitative finance, a PhD can-
didate in finance and a Quantitative researcher. It is mainly about Quant-
itative finance codes, methods in mathematical finance focusing on de-
rivative pricing, quantitative trading and quantitative risk management,
with most of the entries written at university.

Please read update at http:://www.mathfinance.cn 2


www.feedbooks.com
Food for the mind

Please read update at http:://www.mathfinance.cn 3


Quantitative Finance Collector

Updated: 8-10
Update this newspaper

Please read update at http:://www.mathfinance.cn 1


Quantitative Finance Collector
Handling Large CSV Files in R
A follow-up of my previous post Excellent Free CSV Splitter. I asked a
question at LinkedIn about how to handle large CSV files in R / Matlab.
Specifically,
Quotation
suppose I have a large CSV file with over 30 million number of rows,
both Matlab / R lacks memory when importing the data. Could you
share your way to handle this issue? what I am thinking is:
a) split the file into several pieces (free, straightforward but hard to
maintain);
b) use MS SQL/MySQL (have to learn it, MS SQL isn't free, not
straightforward).

A useful summary of suggested solution:


1, 1) import the large file via "scan" in R;
2) convert to a data.frame --> to keep data formats
3) use cast --> to group data in the most "square" format as possible, this
step involves the Reshape package, a very good one.

2, use the bigmemory package to load the data, so in my case, using


read.big.matrix() instead of read.table(). There are several other
interesting functions in this package, such as mwhich() replacing which()
for memory consideration, foreach() instead of for(), etc. How large can
this package handle? I don't know, the authors successfully load a CSV
with size as large as 11GB.

3, switch to a 64 bit version of R with enough memory and preferably on


linux. I can't test this solution at my office due to administration
constraint, although it is doable, as mentioned in R help document,
Quotation
64-bit versions of Windows run 32-bit executables under the WOW
(Windows on Windows) subsystem: they run in almost exactly the same
way as on a 32-bit version of Windows, except that the address limit for
the R process is 4GB (rather than 2GB or perhaps 3GB)....The

Please read update at http:://www.mathfinance.cn 2


disadvantages are that all the pointers are 8 rather than 4 bytes and so
small objects are larger and more data has to be moved around, and that
far less external software is available for 64-bit versions of the OS.

Search & trial.

Tags - r , csv

Please read update at http:://www.mathfinance.cn 3


Excellent Free CSV Splitter
Share an excellent free CSV splitter I found recently, as my csv file is too
large to be openned in Matlab & R, I have to split the csv into several
smaller files. As far as I have tried, Matlab & R warn "short of memory"
for reading csv file larger than 10,000,000 number of rows (it may be
varied across computers), while my tick-by-tick corporate bond data has
nearly 30,000,000 number of rows.

This CSV splitter allows you to split your large file into several smaller
files either by number of lines or by max pieces,

The amazing point of it is the smaller files keep the original header of the
big csv file, very cool. Download the free csv splitter here.
Tags - csv , tool

Please read update at http:://www.mathfinance.cn 4


Isin Cusip Conversion
Long time no blog. Just to let you know I am still alive, busy with my
own PhD research, collecting & cleaning data, programming, making my
hands dirty...

Data massaging is not fun, what makes us more upset is different data
providers have their own data format, name, code, etc., matching the
data from several sources is not so easy, for example, WRDS includes
CUSIP code while Datastream provides ISIN. I didn't understand why
they do business like that but now I get it, similar as those cell phone
manufacturers have distinct chargers and plug-in, not because it's hard
to standardize, but a way to impose customers to use always their own
products.

Anyway, you can convert ISIN code to CUSIP easily once you
understand the rule, ISIN is a 12-digit number while CUSIP is a 9-digit
one (at least the case for US corporate bond), so what you need to do is to
first strip off the first 2 characters representing country code and then
remove the last digit which is a check digit for catching error.

Suppose your ISIN code is in cell A1, ISIN CUSIP conversion can be
done easily in Excel as "=left(right(A1, 10), 9)", for instance, ISIN
US885797AB65 equals CUSIP 885797AB6.

As always, I have been looking for guest writers.


Tags - isin , cusip

Please read update at http:://www.mathfinance.cn 5


Investment banks and the World Cup
This is a news tip that might be of interest sent by Anthony Goldbloom,
thanks.

In the lead-up to the world cup, Kaggle invited statisticians and data
miners to take on the big investment banks in predicting the outcome of
the World Cup. Now that the final has been decided, we can take a look
at how Kagglers stacked up against the quants at JP Morgan, Goldman
Sachs, UBS and Danske Bank in forecasting the World Cup.

In total, 65 teams participated in the Take on the Quants challenge. JP


Morgan finished 28th, Goldman Sachs 33rd, UBS 55th and Danske Bank
64th. The betting markets fared better, finishing 16th.

The winner of the competition was Thomas Mahony, an Australian


economist. His approach relied on Elo ratings with an adjustment for
home country/continent advantage. His strategy correctly tipped Spain
to win, the Netherlands to finish second and Germany to finish in the top
four. The investment banks all had their top picks bow out early (UBS,
Goldman Sachs and Danske Bank picked Brazil and JP Morgan picked
England), hurting their overall performance.

The next big question is whether Kagglers can also outperform the
quants in forecasting financial markets (we won’t have to wait long to
find out, as Kaggle is currently hosting a competition to predict stock
price movements).

Tags - quant , world-cup

Please read update at http:://www.mathfinance.cn 6


Send SMS in Matlab
Ros is a colleague of mine in the same office, his main research is
empirical analysis of different option pricing models, and as a result, he
often use several computers on different desks to run his matlab codes,
which is time-consuming and not rare to last 2 or 3 days. So he has to
come back office frequently to check which computer has finished the
task. It sounds boring, why not write a small script to send SMS
message to you automatically when your matlab stops running?

Send Text Message to Cell Phone is such a great file I found recently,
bascially what it does is to send email via sendmail function of Matlab
from your gmail box to your cell phone carrier, and then your cell phone
carrier forwards the email to you as a text message.

Problem
However, it works for US based cell phones only, I have tried on my UK
T-mobile phone and it seems UK T-mobile doesn't support such a mail to
SMS service (correct me if I am wrong).

Solution
Fortunately, I came across SMS service website which allows people to
send up to 3 free email to SMS per day, it should be enough for our use
in Matlab. Add the following line in the switch case after line 55
case 'uk'; emailto = strcat(number,'@x-onsms.com');

that's it, the email will be delivered as an SMS to your mobile. Do let me
know if you are aware of a better alternative.

So what you need to do is to put the function send_text_message at the


end of your file, it will then send you a message automatically, for
example
send_text_message('079-123-456','UK', 'Desk 12 Calculation Done','Now
you can shut down the computer')

What else can it be used? stock price alert? profit threshold alarm? you
name it.

Possible error
Depends on your Matlab version and firewall setting, you may notice the

Please read update at http:://www.mathfinance.cn 7


following errors:
1, ??? Error using ==> sendmail
530 5.7.0 Must issue a STARTTLS command first
This could happen for MATLAB 7.1 (R14SP3) and before, you may have
to upgrade your version.

2, Could not connect to SMTP host: smtp.gmail.com, port: 25;


Connection timed out: connect
This is due to your firewall or anti-virus software setting. you are not
allowed to send email from port 25. What you shall do is too add an
exception and let your computer know this action is safe. For instance, I
have McAfee, to add an exception, open its control console -> double
click access protection -> anti-virus standard protection -> prevent mass
mailing worms from sending mails -> Edit

add Matlab.exe as a process to be excluded, save it, done.

Ros, you don't have to check computers one by one. Sounds useful?
download the file at http://www.mathworks.com/matlabcentral/
fileexchange/16649, don't forget to change the email address and
password at the beginning of the file.
Tags - matlab , sms

Please read update at http:://www.mathfinance.cn 8


Excellent R Code Format Package
I have been looking for this type of package for several days, and luckily
found it today. Unquestionable R is powerful, however, R programming
is unfriendly as far as I concern, mainly due to the lack of format
shortcut, which makes the R codes rather ugly. (It is an absolute
advantage of Matlab, for example, ctrl+R for comment, ctrl+T for
uncomment, ctrl+I for smart indent, etc.)

FormatR is the package for tidying R source code, although it is less


convenient to use than the straightforward shortcuts in Matlab, this
package is good enough for me, what is it for? as the title suggest:
Quotation
formatR: format R code automatically, farewell to ugly R code

Below is a comparison before and after using FormatR.


Before:

After:

Download the package at http://cran.r-project.org/web/packages/


formatR/index.html
Tags - r

Please read update at http:://www.mathfinance.cn 9


Simple Dummy R GUI Generator
Imagine you finish a dirty coding project and want to present to your
boss who is not in a good mood (may not be occasionally), how are you
going to start? Show him your hundreads of lines code, point to the lines,
explain what the arguments and outputs are? No, it is not a smart way
since you are supposed to introduce in a few short sentences. Generating
a GUI is probably the quickest / easiest way of understanding what this
code does. As the old saying goes: a picture is worth a thousand words,
so in a same logic, a GUI is worth n thousand words.

However, generating GUI is by no means easy as I know the pain when


creating the Matlab-GUI equity derivative calculator. It becomes even
worse in R language, to be honest, I hate the graph plotting in R, terribly
unflexible compared with in Matlab. Luckily I came across a good R GUI
package named "fgui", it does as its description: Rapidly create a GUI
interface for a function you created by automatically creating widgets for
arguments of the function.

Very nice indeed, after playing for half an hour, it is simple to use,
especially when what you need is just a basic GUI demonstrating to
others a rough idea. One line code is enough.

For a simple example, I create a European option pricer with Black


Scholes formula,
EuropeanOption <- function (s, k, r, t, vol, CallOption) {
d1 <- (log(s/k)+(r+0.5*vol^2)*t)/(vol*sqrt(t))
d2 <- d1-vol*sqrt(t)
if (CallOption){
return (s*pnorm(d1)-k*exp(-r*t)*pnorm(d2))
} else {
return (k*exp(-r*t)*pnorm(-d2)-s*pnorm(-d1))
}
}

then generating a GUI for this function is as simple as adding the


following code
res <- gui(EuropeanOption,
argOption=list(CallOption=c("TRUE","FALSE")))

Please read update at http:://www.mathfinance.cn 10


It returns a GUI looks like

where you are able to set inputs and get outputs. Nice. More advanced
GUI is possible by adding more lines.

Interested readers shall download the package "fgui" at http://cran.r-


project.org/web/packages/fgui/index.html
Tags - r , gui

Please read update at http:://www.mathfinance.cn 11


Short Term Stock Price Movement Prediction Competition
Many thanks to Anthony who emailed me the link to this competition.

So you are a quant-gambler? time to stand out!

Traders, analysts, investors and hedge funds are always looking for
techniques to better predict stock price movements. The 2010 INFORMS
Data Mining Contest takes aim at this goal, requiring participants to
build models that predict the movement of stock prices over the next 60
minutes.

Knowing whether a stock will increase or decrease allows traders to


make better investment decisions. Moreover, good predictive models
allow traders to better understand what drives stock prices, supporting
better risk management. The results of this contest could have a big
impact on the finance industry.

Quotation
Competitors will be provided with intraday trading data showing stock
price movements at five minute intervals, sectoral data, economic data,
experts' predictions and indices. We have provided a training database
to allow participants to build their predictive models. Participants will
submit their predictions for the test database (which doesn't include the
variable being predicted). The public leaderboard will be calculated
based on 10 per cent of the test dataset.

The submission deadline is October 10th 2010. Final results will be


announced on October 12th. The winners of this contest will be
honoured at a session of the INFORMS Annual Meeting in Austin-Texas
(November 7-10).

Check the detail of this competition at http://kaggle.com/informs2010


Tags - prediction , competition

Please read update at http:://www.mathfinance.cn 12


Debugging Your Thinking
Quotation
Writing program code is a good way of debugging your thinking - Bill
Venables

Believe it or not, on average programmers spend 70% of their working


time in debugging (I don't know where this number is from but I do
believe so). A good debug tool, command or even habit will definitely
improve your work efficiency, shorten working hour, and enjoy more
the world cup. When it comes to Matlab and R, I have to say the
debugging in Matlab is straightforward but is more comprehensive in R.
Here is an introductory video demonstrating how to debug and
understand Matlab codes:

Also a very good PDF document for debugging in R with detailed


examples at http://www.biostat.jhsph.edu/~rpeng/docs/R-debug-
tools.pdf. Enjoy.
Tags - debug

Please read update at http:://www.mathfinance.cn 13


Forex Market Strategy Guide: Scalping 101
There are multiple ways of profiting in forex, including swing trading or
trend following. However, scalping is the method with the shortest
trading periods. With this method, traders usually open a trade for 1-2
minutes, or 5 minutes at the very most. The idea is to benefit from short
fluctuations in the market.

This series of articles will serve as a guide for scalping, but for the
purpose of introduction, we can ask what makes this strategy popular
and effective. Many of these considerations will then serve as the topics
of further articles.

The first major reason for scalping is perceived safety. Scalping has a far
shorter time frame than the other forex methods, and many traders
argue that this limits their exposure to the market.

Of course, this limited exposure leads to a second major characteristic of


scalping—a large number of trades. Some scalpers may open and close
as many as several hundred trades within a single trading day.

This points to one of the major challenges for this style of trading. Since
the number of trades is extraordinarily high, scalpers must find forex
brokers with low transaction costs and fees. Before considering this style,
make sure that your broker’s commission structure allows for you to be
profitable.

A third characteristic is the fact that scalpers rely on some type of


leverage. The profit from each trade is generally quite small, and even
with a huge number of orders, the results would hardly be worthy of the
effort. Depending on the amount of leverage you use, this can eliminate
any real security. In spite of their arguments to the contrary, scalpers can
lose a day’s work in a few bad transactions.

A fourth characteristic of scalping is that it is generally a full-time


endeavor. This is a significant limitation, since the majority of forex
traders only do it in order to supplement their income. Scalping requires
constant and undivided attention. If you decide to use this strategy,
expect it to dominate your time and efforts for as long as you are trading.
It is generally best to set aside an extended period of time and eliminate

Please read update at http:://www.mathfinance.cn 14


any other distractions. This is unworkable for many traders, though
when a scalper finishes for the day, his exposure is finished as well.

Some scalpers try to eliminate this problem by automating the process.


In recent years, a vast number of robots and software automation kits
have become available for scalpers. Unfortunately, most of these are
unproven, and many make wild claims that stretch far beyond
plausibility. Still, there is a real benefit in automating certain parts of the
process. For instance, you might use software to execute redundant tasks
like stop-loss, take profit and other orders, while doing the analytical
tasks yourself. In this limited role, the automation can be a significant
help by allowing you to execute more trades with less drudgery.

Scalping is a workable strategy if you know what you are doing and are
willing to dedicate your full time energy to forex trading. Unfortunately,
too many beginners try scalping based on the assumption that they can
avoid risk. As any experienced investor knows, risk accompanies any
genuine financial opportunity. After several months of practice, and with
plenty of education, scalping is a great way to enter the forex markets.
This guide will tell you some of the main things you need to know when
getting started.

The first step in any guide on scalping is understanding how scalpers


actually make money. What does a scalping strategy look like in daily
practice?

We already mentioned that scalping involves entering and exiting the


market in short time spans. But what guides the choice to enter or exit?
Actually, this strategy works on the basis of careful analysis and timing.
What makes scalping different from other strategies is that it takes
advantage of volatility rather than trending, ranging, or fundamental
analysis. Recognizing that the market moves erratically in the short term,
scalpers try to identify small patterns and exploit them.

The strategy works when traders can find short-term disruptions in


liquidity, or other temporary abnormalities. For instance, a news shock
or some other factor might suddenly increase demand for the yen.
During that time, there will be a need for liquidity as too many people
demand the yen with insufficient supply. The spread between bid and
asking price will temporarily widen. A scalper might recognize that the

Please read update at http:://www.mathfinance.cn 15


liquidity has to return eventually and the price will eventually settle
back into normal levels. Based on this, he can go long or short, as
appropriate, and collect on the difference.

This means that scalpers actually benefit from volatility by trading on


the assumption that prices will stabilize again. It’s not hard to see that
after a major event, prices routinely zigzag for several minutes before
settling again. Since this is an emotional over-reaction, a scalper
maintains a realistic, stable viewpoint and profits from those who don’t.

It’s also easy to see that if trading wisely, scalpers act as “brakes” on the
micro-volatility of the market. They actually profit by dragging irrational
price-spikes back to meaningful levels. One other implication is that the
most important time for a scalper is just after a market shock. Scalpers
pay careful attention to announcements of economic data or news shocks
and the disruption that follows.

But these observations lead to the other major topic of this


article—leverage. The inherent limitation of trading on micro-volatility is
that it will never be very significant. Therefore, scalpers use surprising
amounts of leverage to make their trading more potent. Their leverage
might range from 5:1, all the way up to 50:1. These kinds of leverage
would be simply intolerable for other traders, but the important thing to
remember is the short duration that scalpers use. During this time, there
is little opportunity for wide swings in the market that would risk
massive losses. It is also crucial to always use a good stop-loss
mechanism and not adjust it for individual trades. If these measures are
maintained and a trade turns out badly, it will be closed in a matter of
minutes or even less when the stop-loss level is reached.

There are still a few cases when scalpers might still suffer significant
losses. Significant news shocks might cause very wide spreads in a short
time. Even the best brokers may not be able to complete stop-loss orders
quickly enough, and losses can multiply exponentially. Therefore,
traders should always be conscious of whether new economic data or
another type of event has the potential to cause significant disruptions.
In such cases, it is always wise to use caution and trade with lower
amounts of leverage.

Scalping is an interesting strategy because it takes advantage of

Please read update at http:://www.mathfinance.cn 16


phenomena that might otherwise seem random. It is a simple testimony
to the fact that on every level of the forex market, the same principle
applies—profit belongs to the traders that use their heads and who are
not carried away by short-term emotion. The scalpers that succeed are
the ones that have mastered that art.

The next logical question in our guide to scalping is how to do it. When
it comes right down to the pragmatics of this strategy, what do you need
to make it work, and where do you start?

One of the most important foundational issues is choosing the right


broker. In some cases, a brokerage may even have a stated policy against
scalping. Without the right platform and broker, you simply have no
chance of success. But what should you be looking for?

The first issue is the broker’s spreads. If a swing trader opens and closes
several positions every day, a spread of several pips is hardly an issue,
but scalpers might open and close more than a hundred daily. If you
work out the math, this is a significant loss. For instance, imagine that a
trader makes 50 trades with a nice profit of 130 pips. If the spread is
three pips, he would end up with a net loss of 20 pips. Since the cost of
the spread applies to every trade whether it is profitable or not, this loss
adds up very quickly. The conclusion is fairly obvious—if you want to
make any profit with scalping, you’ll need to find a broker with the
lowest spread possible. In addition to spreads, you should also check for
any commissions or hidden trading fees.

But this search is not always easy. Unfortunately, many brokers have a
bad relationship with scalpers. The problem is that the number of trades
scalpers make can sometimes overwhelm older systems. In addition,
every broker has to countertrade the orders he processes to avoid being
financially liable. Receiving large numbers of orders every day doesn’t
make this easy.

For those reasons, many brokers try to eliminate scalpers. Sometimes this
is a stated policy, but very often a broker will simply terminate a scalpers
account or slow down his processes so that scalping is impossible.
Therefore, you must also find a broker with the most up-to-date
technology and a toleration for large numbers of orders. Look for a fully-
automated broker with no-dealing desk (NDD).

Please read update at http:://www.mathfinance.cn 17


There are several other things that can make scalping impossible. If the
trades take too long to process (slippage), the price difference will
quickly make trading unprofitable. Therefore, you should always look
for efficient execution of your orders. Similarly, price quotes must
always be precise and updated dynamically. Even a small delay (latency)
makes trading based on micro-volatility impossible.

Finally, scalpers should look for platforms with a workable interface. For
the most part, this should include the same financial tools that trader’s
want with other strategies. Of course, you should look for an interface
with a full range of execution tools. But in particular, the interface needs
to be fast and easy to use. This is important because of the number of
rapid orders that must be made. Customization is also a big advantage,
as well as automation. You should also pay attention to the visual
appearance of the interface. Scalping requires intense focus, and many
traders report eye-strain after a long day of staring intensely at a screen.

In short, you should consider every angle before committing yourself to


a particular brokerage or a trading platform. Be upfront from the
beginning with your broker. If you try to use this strategy through a
system that can’t handle it, the brokerage will intentionally make trading
impossible. Of course, you should also be confident that your broker
isn’t fraudulent. Most of all, you should never try to use scalping
through a broker with wide spreads or other excess costs. The net result
will always be a loss. Done right, and done through the right avenues,
however, scalping can be quite successful.

Once you establish a broker, there are several other things you should
know about scalping.

First, you should wisely pick currency pairs that will work well with the
strategy. The best thing is to start out with the basic pairs, and move to
riskier pairs as you become more experienced.

The most stable and liquid currency pair is certainly EUR/USD. Other
majors have a similar stability, such as GBP/USD, USD/CHF and others
currencies from the major world economies. All of these currencies
change very slowly. Even major events will not produce significant
jumps in these pairs, because of the volume that is regularly traded.

Please read update at http:://www.mathfinance.cn 18


But isn’t the goal of scalping to profit from volatility? So it seems as
though more volatile currencies would be better. The advantage of the
more stable currencies, is that directional changes are much easier to
predict. Remember that even small fluctuations can be magnified
through leverage. This means that a trader can generate very large
returns from these pairs, if he is willing to accept the risk.

Another group can be called carry pairs. These currencies are liquid, but
much more volatile than the majors. A good example here is the
Japanese Yen. Interest rates are very high on the Yen, and many
investors also use the currency for risky assets. One of the results is that
market shocks will have extreme results that might result in very wide
spreads. Within a scalping strategy, this might result in extreme losses
that a stop-loss order cannot protect from. Furthermore, excessive
volatility can be quite unpredictable. Therefore, it is generally best for
beginners to stay away from pairs that involve the Yen (JPY) or other
carry pairs.

Finally, exotic pairs involve small or developing nations with a low


volume of trade. Examples might include the Norwegian Krone (NOK),
the Turkish Lira (TRY), the Brazilian Real (BRL), or any of the
developing currencies. These pairs are quite unpredictable, and often
run into significant liquidity problems. Trading with one of these is a
significant risk.

Any experience trader also realizes that the markets change during the
course of a day. So when is the best time to trade? From 7:00-8:00 (EST),
markets are quite choppy, because worldwide traders anticipate the
opening of the New York market. Late morning brings higher volatility,
but also great liquidity. Many announcements also direct the market
during this time. Early afternoon tends to be quite choppy, with higher
risks but potentially greater profits. Late afternoon sees the closing of
most large banks in developed countries, and the market becomes its
quietest.

Really, your preference for each of these times depends on your style. In
choppy conditions, scalpers should look for shorter trades without
concern for directionality. Of course, during the time that the markets
are open, there should be more attention to larger trends, and the

Please read update at http:://www.mathfinance.cn 19


possibility of more extended trades.

All of these factors are significantly influenced by your particular style


and your experience. Risk may be just the thing if you know how to
handle it, and experienced traders often had straight for more volatile
times and currency pairs. If you’re only beginning, the key is to stay with
major pairs and avoid times of wild fluctuations. Learn how to predict
the market with low leverage and minimal risk. Once you’ve seen and
handled various market conditions, you can consider taking bigger risks,
and pursuing larger profits.

This guide has sought to introduce scalping and discuss the pros and
cons of the strategy. After a brief introduction into the characteristics of
scalping, we discussed how scalpers profit and how they use leverage.
We also pointed out the major necessary things to make scalping
successful, including a good broker and an efficient platform. Finally, we
discussed the best currency pairs and times of day when scalping works
best.

But this guide runs the risk of being overly simplistic if we fail to talk
about the variations on scalping. Traders might use any one out of a
number of techniques to make their strategy successful. Trend scalpers
follow the direction of the market and try to profit from where it is
headed. Think of this as following the macro-direction of a currency, but
on a much smaller scale. Other scalpers prefer to take advantage of news
events and other shocks to the market. These traders stay away from the
period closest to the news event, but profit in the time just afterward.

The more important point to recognize is that scalping varies drastically


according to conditions. At times the distinction between scalping and
other strategies is quite unclear. For instance, if a scalper opens a
position and then observes a longer profitable trend, it only makes sense
to take full advantage of it. Depending on what is happening, a trader
might switch back and forth between all of the strategies, or form his
own hybrid.

However, this points to a very important issue that applies to all forex
trading. There is a deeply psychological aspect of dealing with risk and
loss that every trader should be conscious of. Here are a few qualities to
aim for.

Please read update at http:://www.mathfinance.cn 20


First, scalpers and all forex traders for that matter, must exercise
discipline in their trading. This is the only problem with moving
between various strategies—it becomes too easy to make emotional
decisions and take foolish risks. Let your strategy control your decisions.
In particular, don’t make the mistake of varying the size of your trades
too much—especially when you have a string of successes. One bad
trade can erase a lot of progress.

A second, related point is cool-headed thinking. When markets become


chaotic, it is easy to be controlled by the volatility and make foolish
mistakes. At those times, remember your strategy and follow it
assiduously.

Third, you must be patient for the long-term. Scalping works when lots
of small but profitable trades add up to a large sum. Be willing to wait
for that, even if it requires persistence and temporary loss.

Finally, it is imperative to know yourself. Know what style works well


for you. Observe what market conditions tend to reap the best profits for
your trading. At certain times, it may be best not to trade at all. When
you recognize that conditions mirror what has worked well for your
strategy in the past, you should jump into the market fully.

Beginning traders sometimes assume that scalping is the easiest way to


earn a quick profit. However, scalping is actually one of the most
challenging strategies. Some scalpers suffer losses at the beginning, but
with a lot of practice, discipline, education, and the right tools, this
method can be one of the most profitable forex strategies.

Tags - forex , trading , strategy

Please read update at http:://www.mathfinance.cn 21


Excellent Yahoo Finance Data Downloader
Although I have shared several ways to download data from Yahoo
Finance, for instance, Yahoo chinese historical stock data, download
option price data from Yahoo, I have to admit the one I recommend
today is the best and most comprehensive ever. It supports dozens of
tags to download, besides what we normally need for closing price,
volumn, daily high, and daily low, including (click the graph to see a
clearer picture):

Massive, isn't it? download the csv file and also a file for option data at
http://www.gummy-stuff.org/Yahoo-data.htm
Tags - data , yahoo

Please read update at http:://www.mathfinance.cn 22


R Sapply Problem
Any expert in R please educates me. I have got a problem about the
sapply (or lapply), it made me headache for over two hours.

As "for loop" is very slow in R, we should try best to avoid using it, and
to use vectorization instead. sapply is designed for this, for example,
instead of:
for (i in 1:10) {
z[i] <- mean(x[1:i])
}

we could use
z <- sapply(1:10, function(i, x) {mean(x[1:i])}, x)

It went well, but what if besides computing z, I need to update another


variable, for example, with loop, it is
temp <- 3
for (i in 1:10) {
x[i] <- x[i]-temp
z[i] <- mean(x[1:i])
temp <- x[i]-z[i]
}

in this case, temp is changing every step (it doesn't have to be a function
of z[i]). How to vectorize that and use sapply then? since sapply can't
return two variables z and temp.

I tried to define a matrix and store z in the first column and temp in the
second column and return the matrix, however, failed.

Many thanks.

PS, NO, still not correct, working on it...


ah, I worked it out, it can be done by passing z itself to sapply, that's
good.

Please read update at http:://www.mathfinance.cn 23


the following is a sapply example returning the same result for "for loop"
and "sapply".
sapply.example <- function(nsim = 10){
x <- rnorm(nsim)
y <- list()
z.for <- array(0, nsim)
temp <- 3
for (i in 1:nsim) {
x[i] <- x[i]-temp
z.for[i] <- mean(x[1:i])
temp <- x[i]-z.for[i]
}
y$z.for <- z.for

z.sapply <- array(0,2*nsim)


z.sapply[1] <- 3
z.sapply <- sapply(seq(1,2*nsim,by=2), function(i,x,z.sapply) {
temp <- z.sapply[i]
z.temp <- mean(x[1:((i+1)/2)])
temp <- x[((i+1)/2)]-z.temp
z.sapply[i] <- temp
z.sapply[i+1] <- z.temp
z.sapply[i:(i+1)]
}, x, z.sapply, simplify =TRUE)
y$z.sapply <- z.sapply[seq(2,2*nsim, by=2)]
y
}

Tags - r

Please read update at http:://www.mathfinance.cn 24


R for Matlab Users
My favorite software is Matlab, but partly because R is free, more and
more people & companies choose to use R as a major working language.
Nothing wrong with that, I am at the moment changing some of my
Kalman Filter Matlab codes to R.

One bothering issue is each software has its own coding rules, for
example, in Matlab we use a(1,1) but in R we use a[1,1]; in Matlab we
have ones(3,2) but in R we dont have such a command but matrix(1,3,2),
etc. (I am always wondering why they can't be designed in a similar
way). It does bring me trouble sometimes, luckily I came across a web
page similar as cheat-sheets, it lists those widely used commands in R
and corresponding commands in Matlab, very convenient indeed.

Search before trial & error: http://mathesaurus.sourceforge.net/octave-


r.html

PS:
Walking Randomly suggests another excellent PDF manual consisting of
47 pages, fantastic! http://www.math.umaine.edu/~hiebeler/comp/
matlabR.pdf
Tags - r , matlab

Please read update at http:://www.mathfinance.cn 25


South African World Cup
Today is the first day of South African world cup. Disappointing French
team, although JP Morgan's Quant group members use their model to
predict England will win this world cup Championship, I still go for
Netherlands. GO GO GO, Holland.

A funny graph showing the characteristic of each team, enjoy football


everyone.

Tags - football

Please read update at http:://www.mathfinance.cn 26


Exclusive Offer: Download $79-value Vertical Spreads
options trading ebook for free
A guest post from our Elliott.

Dear reader,

We have a very special offer for traders today. Our friends at Elliott
Wave International have just released their $79-value, 42-page ebook for
options traders for free download.

The new ebook, How to Use the Elliott Wave Principle to Improve Your
Options Trading Strategies -- Vertical Spreads, which sells in EWI's
online store for $79, is available for free, exclusively to you, for a limited
time.

The ebook is designed to help you exploit sharp price movement with
powerful vertical spread trading strategies, including: Bull Call
Spread, Bear Put Spread, Bear Call Ladder, Bull Put Ladder and more.
This valuable ebook belongs in any serious trader's library. You can
download it now for free here.
Tags - option , trading , elliott

Please read update at http:://www.mathfinance.cn 27


An Interest Rate R Package Plan
I recently have done some empirical studies on zero-coupon bond
modelling and pricing, and plan to create an interest rate R package in
order to make it re-usable, as I find there are only two R package on it,
one is http://cran.r-project.org/web/packages/termstrc/index.html,
the other one is http://cran.r-project.org/web/packages/YieldCurve/
index.html, both of them don't cover short interest rate model,
unfortunately.

Below is a short plan, help me add it by leaving a comment, thanks.

Tags - r , package , rate

Please read update at http:://www.mathfinance.cn 28


How to Create an R Package in Windows
There are many reasons to create an R package, such as codes protection,
convenient usage, etc. However, creating an R package in Unix is not
hard, it IS in Windows, as R is designed in a Unix environment which
includes a set of compilers, programming utilities, and text-formatting
routines while Windows lacks those. I used to build an R library in Unix
and thought it was relatively as the same convenient as in Windows, but
it turned out I had to spend several hours on it. Silly me.

Below are the selected steps to create an R package in Windows I


summarize:
1, you have to download Rtools at http://www.murdoch-
sutherland.com/Rtools/.

2, depending on your needs, you may download and install LaTex,


Microsoft HTML Help Workshop and the Inno Setup installer, available
at http://www.miktex.org, http://msdn.microsoft.com/en-us/library/
ms669985.aspx, and http://www.jrsoftware.org/, respectively. For
example, Microsoft HTML Help Workshop is for making HTML Help
documents, LaTex is for a nicer outlook, especially when your
documents have math equations.

3, double click Rtools.exe to install it and its accompanying tools:


minGW, perl. Rtools automatically recognizes the paths of those relevant
softwares and add them to the environment variables of your computer.

4, check and change your PATH “environment variables” of your


computer if incorrect. To set the path, right click on the “My Computer”
icon on your desktop, choose properties and click on the “advanced” tab,
click the environmental variables button, click on the path variable and
select the edit button. Check carefully whether all the paths are correct,
special attention needs to be given to the path of R software.

5, double check whether all tools are installed correctly by opening a


“command prompt” window and typing the following commands: R;
gcc –help; perl –help; Tex –help, respectively. You should see a list of
options, otherwise re-install or check the path if you see “… is not a

Please read update at http:://www.mathfinance.cn 29


recognized as an internal or external command …”

6, start R and run the command package.skeleton( ) with suitable


arguments, read the help http://stat.ethz.ch/R-manual/R-patched/
library/utils/html/package.skeleton.html for detail. For instance, I write
a sample code MonteCarloPi.R to estimate PI by Monte Carlo simulation,
we use package.skeleton(name = "MonteCarloPi", code_files =
“MonteCarloPi.R”), where MonteCarloPi.R includes function we want to
add to the package MonteCarloPi. This function creates the directory tree
for the package containing:
DESCRIPTION <<
man <<< for documentation
R <<< for R function definitions
src <<< for low-level source code (this is optional for other programming
files, such as your c++ codes)
data <<< for package datasets (this is optional)

7, remove the Read-and-delete-me file and modify other files in the


above directory with notepad or other tool, for instance, to add the
author information and Help explanation.

8, open a “command prompt” window, change the directory to where


your package is, type the command “R CMD build MonteCarloPi” to
build the package, this will generate a file called
MonteCarloPi_1.0.tar.gz. You must run the command in a “command
prompt” window instead of in R, otherwise you are expected to see
“Error: unexpected symbol in "R CMD"”.

9, test the package by typing “R CMD check MonteCarloPi_1.0.tar.gz”,


go back to step 8 if you see errors.

10, now you are able to install the package typing “R CMD INSTALL
MonteCarloPi_1.0.tar.gz”. Congratulations if you see “…done…” and
you will notice there is one more sub-folder “MonteCarloPi” in your R
library folder.

#MonteCarloPi.R -- PI estimation by Monte Carlo simulation

MonteCarloPi <- function(nsim){

Please read update at http:://www.mathfinance.cn 30


x <- 2*runif(nsim)-1
y <- 2*runif(nsim)-1
inx <- which((x^2+y^2)<=1)
return ((length(inx)/nsim)*4)
}

Quotation
Reference:
http://cran.r-project.org/doc/manuals/R-exts.html

Tags - r , package

Please read update at http:://www.mathfinance.cn 31


15 Incredibly Stupid Ways People Made Their Millions

A selection of stories outlining the stupid ways people made


their millions.

Inventions are important. They're the reason life has become so easy for
us, and technology so accommodating. The market for inventions is
enormous, and hundreds of new ones are patented every day. Since not
everyone is a genius, many of them fall into obscurity immediately as
inefficient or unimportant ideas. However, sometimes the silly ones we
might be quick to dismiss are unexpectedly more profitable than the
conventional method of doing whatever it is the newfangled thing does.
Here are 15 weird and ridiculous ideas that made people rich.

1. Pet Rock

The Pet Rock is undeniable proof that people will buy just about
anything. It's literally a rock with googly eyes glued to it, but the
inanimate companion grossed a couple million dollars in 1975. The fad
only lasted for that year before dying out, but the Pet Rock carriers,
equipped with breathing holes and a straw as if for a real animal, proved
irresistible for those wishing to give silly and ironic Christmas gifts.

2. SatLav

Really having to pee can be one of the most uncomfortable feelings ever.
You can’t concentrate on anything else, you fidget, you frantically search
for the bathroom. But what if you’re out in public and don’t know where
to find one? Poppin’ a squat it picking a dark corner isn’t always an
option, and many establishments have bathrooms restricted for
employee or customer use only. Conveniently, anyone with a cell phone
can now find the nearest public restroom just by texting a short number
for a small fee.

Please read update at http:://www.mathfinance.cn 32


3. Doggles

Do dogs really need goggles? No. Do they want them? Probably not.
Does anyone sell them? Of course -- and they've made more than a
million dollars off the idea. Giving dogs goggles is about as useful as
giving a goldfish a monocle and cane, but that didn’t stop the company
Doggles from doing their very best. At $80 a pair, Doggles is a multi
million dollar company.

If you think about it, looking at the photo above (and ignoring the fact
that this product shouldn’t exist in the first place), there’s no reason that
goggle s for dogs should look the same as those for humans. The bridge
of a dog’s nose isn’t directly between his eyes like a human, so this
design is a little strange. They pretty much look like Seth Green’s
character from Can’t Hardly Wait.

4. Million Dollar Homepage

How much is a solitary pixel floating around in cyberspace worth? Alex


Tew thought $1 per pixel was a reasonable price. Tew was just about to
begin studying business at the University of Nottingham, but the idea he
came up with to fund his education proved that he already possessed the
sensibility of a successful businessman. Tew bought a web domain, laid
out an area of 1,000,000 pixels, and sold them in 100-dollar blocks. Ads
ranged from online casinos, to Target and everything in between. This
was The Million Dollar Homepage.Tew came up with the idea in
August of 2005, and by New Year’s Eve, every pixel bar but one had
been sold. Not only did Tew make a whopping $ 1,037,100 gross from his
relatively simple idea, but he also managed to attract some big name
clients, like Tenacious D.

Please read update at http:://www.mathfinance.cn 33


5. Mungo & Maud’s Petite Amande Dog Fragrance

Even more absurd than dog goggles is the concept of a dog perfume. It's
true that wet, dirty dog smell is an awful one... But how about wet and
dirty mixed with floral extracts? It's like spraying air freshener in the
bathroom -- it doesn't cover up the poop smell, just sort of hangs on top
of it like an additional layer of sense assault. Here's an idea: give your
dog a bath. If the dog is clean, it won't smell so bad. Don’t just cover the
smell up like some French hooker from the 1700s. The fact that this
invention has earned over a million dollars is downright ridiculous.

Another case against Petite Armande is that dogs have an exponentially


stronger sense of smell than humans do. The animal most likely finds it
unpleasant to be sprayed with irritating odor concentrates. If the smell is
strong to us, it must be a billion times stronger for the dog. Suit
yourselves, perfumed-pup-lovers, just don’t complain when Timmy’s
stuck in a well an you bloodhound Biff can’t find him because his sense
of smell is masked by the wafted aroma of Lassie Chanel No. 5.

6. Lucky Wishbone Co.

Amazingly, this might be the silliest product yet – which is definitely


saying a lot, considering the cavalcade of weird stuff that’s preceded it.
Wishbones are traditionally considered lucky, and are taken from an
animal (which is typically being consumed) to break in half between two
people. Holding each end of the tiny bone, the two parties pull until it
snaps, and decide which player is the ‘lucky’ one according to who has
the larger portion. However, Lucky Wishbone Co. doesn’t sell real
wishbones. It sells fake little plastic ones, at around about a dollar each.
This abortion of an idea also makes its creators the a ton of money.

7. SantaMail

Please read update at http:://www.mathfinance.cn 34


Get a postal address in the North Pole, pretend you are Santa Claus and
charge parents 10 bucks for every letter you send to their kids. Well,
Byron Reese has sent over 200,000 letters since the start of that business
in 2001, meaning he's made a multi-millionaire dollar fortune.

One of the best ways to make money out of people has always been
taking advantage of their naïveté and dreams, and who's more naïve
than kids? Byron Reese, sprung for a postal address in the North Pole, a
place he'd never been, so he could pretend to be Santa. Even worse than
the mall Santa who lets kids sit on his lap and drinks malt liquor in the
parking lot, in some intangible way.
Reese writes back to the letters himself, but never reveals his true
identity. At first, this sounds quite sweet, but consider this: What if little
Susie (they are always called Susie) wants a little doll which Mommy
and Daddy can't afford? Is Santa going to say ‘no’? What if little Jessica
(she’s rich and has a last name like DuBois or something) wants a pony,
and Santa’s all like ‘I think that’s a bit much to ask, little Jessica. Ho ho
ho!’ but then Jessica’s parents buy her a really awesome pony with a
Bose sound system and five LCD monitors? Then Santa all of a sudden
seems nonexistent. Another million-dollar idea, this time one that
depersonalizes one of the most beautiful mysteries of childhood by
making it a capitalist business.

8. Excused Absence Network

Are you too lazy to show up to work or school on time, but don’t want to
waste your creativity on coming up with your own excuse? The Excused
Absence Network is a service which caters to all the lying employee’s
needs; from a missed math test all the way to skipping out on your own
wedding. The notes aren’t just those ‘little Johnny had a sore throat
today’ notes from mom – these are excuse notes that look as though they
come from a hospital or doctors office for just $25 per note.

9. Fetal Greetings

Please read update at http:://www.mathfinance.cn 35


What is the worst way of telling someone that you're pregnant? The guys
at Fetal Greeting have certainly come very close to nailing it -- their
website suggests that you should surprise friends, family, & even the
expectant father with these one-of-a-kind cards. It sounds almost like a
scenario for Maury Povich – ‘And the card says…Bob, you ARE the
father.’

As is the case with most everything else on this list, there seems to be a
positive correlation between the inanity of the product and it’s
commercial viability. Fetal Greeting saw sales being reported in the
million and climbing steadily.

10. www.MannequinMadness.com

Mannequin Madness is a website that sells second-hand mannequins at


third-hand mannequin prices. They boast that that have ‘the perfect
body for you to buy or rent’ and the second-hand mannequin business is
booming. The website stresses that the mannequins aren’t only good for
traditional uses, like showing off clothes and making you feel bad about
your body type. The website also suggests they be used for practical
jokes and Halloween displays (read: causing heart attacks).

11. Big Mouth Billy Bass

The Big Mouth Billy Bass was designed with the sole intention of driving
people insane. It's a product for old people, who are the only ones to find
its autonomous song incredibly novel. The singing fish is otherwise
given as an unwanted box where it sits in the box to gather dust or is put
out repeatedly at the same garage sale for two months. These two criteria
make up millions of people, and the Big Mouth Billy Bass has made
millions of dollars.
With its success has come the delightful discovery that hacks could leave
the Bass able to sing any song.

Please read update at http:://www.mathfinance.cn 36


12. www.ICanHasCheezburger.com

I Can Has Cheezburger? burst onto the web scene in early 2007 and
elevated the already rampant LOLcat meme to new level of
ubiquitousness. The site, now a conglomerate of several extended
memes, is primarily concerned with evoking humor from photos of cats
with added, sometimes nonsensical, subtitles. The site was acquired a
short eight months after is creation by a group of investors for a
whopping $2 million.
Two million dollars for a website whose principle visitors are stoners
and 13-year-old girls who have just learned how to use the internet. I
Can Has Cheezburger? Revenue is solely advertising-based.

13. One Red Paperclip

Kyle McDonald may not be a household name, but he’s definitely


internet-famous, and he definite has a household -- one that he traded
his way to from a solitary red paperclip (which, to be honest, looks
used). It only took Kyle exactly one year and fourteen trades to make his
way from a twisted piece of metal to a home for his family. Along the
way, he travelled to the far reaches of Canada, all across the US, met
Alice Cooper and Corbin Bernsen, and basically had one hell of a good
time.
Finally, Kyle settled with a home at 503 Main Street, Kipling,
Saskatchewan, Canada, and he still lives there to this day. His story
stands as an example of how you can start with absolutely nothing, and
then one day live in Canada.

14. Murder Clean Up

What is an ambitious real estate flipper to do with the abandoned house


whose floors have been ravaged by the waste and habitation of a feral cat
community? What about the family whose estranged hoarder aunt dies

Please read update at http:://www.mathfinance.cn 37


from eating herself into a corner surrounded by mountains of garbage
and human waste? Advanced Bio-Treatment specializes in murder,
suicide, drug lab, and (really nasty) waste clean-up. It sounds like a
morbid idea for money making, but ABT raked in about a million dollars
during 2009 alone. And if all else fails, at least grandpa has some
interesting bedtime stories for the kids.

15. Eternal Reef

Another death-related business is Eternal Reefs, a service which provides


underwater urns for individuals cremated after death. The cement globe
contains holes to encourage plant growth and allow fish to swim in and
out of your loved one’s ecologically friendly grave. Those purchasing the
Eternal Reef are allowed to press their hands into the soft concrete, or
attach a flag or sorts as a means of marking their reef. Eternal Reefs have
a profit of about half a million per year.

Tags - money

Please read update at http:://www.mathfinance.cn 38


Matlab File Style
Programming style, a set of rules or guidelines used when writing the
source code for a computer program, is important for a programmer, it
not only allows the reviewers to know the date and author of the file, but
also helps the programmer himself to track the file version and improve
work efficiency. Nevertheless, repetitive comments, especially for the
header part are boring. Uncomment is even more boring, read Matlab
comment stripping for a lazy way for that.

NEWFCN is a good function I always use when creating new files,


basically it creates a M-File having the entered filename and a specific
structure which helps for creating the main function structure. The actual
working MATLAB Version will be also captured. For example, running
newfcn('testnewfcn') generates a file named testnewfcn.m at a pre-
defined style, the new file looks like
function testnewfcn()
% TESTNEWFCN ...
%
% ...

%% AUTHOR : aBiao @ mathfinance.cn


%% $DATE : 28-May-2010 18:55:27 $
%% $Revision : 1.00 $
%% DEVELOPED : 7.1.0.246 (R14) Service Pack 3
%% FILENAME : testnewfcn.m

disp(' !!! You must enter code into this file < testnewfcn.m > !!!')
% ===== EOF ====== [testnewfcn.m] ======

Did I mention you can customize the exact style by modifying newfcn.m
to the appearance you like? just that simple!

Download at http://www.mathworks.com/matlabcentral/
fileexchange/6408
Tags - matlab

Please read update at http:://www.mathfinance.cn 39


Mathematica Home Edition
To be honest, I can't call myself a fan of Mathematica, as you can notice
by the number of posts under Mathematica category of this blog. No
specific or big reasons, but just because my first job required Matlab &
C++, my second job required R & S+ & Matlab, my master & PhD
universities don't have Mathematica installed, that's it. I personally came
across this software a few times either due to the codes I could find on
my interested topics having only Mathematica version, or the request by
my friends & colleagues for analysis.

That's why I only got to know the existence of Mathematica Home


Edition today despite the fact it has been in the market for over one year!
What is Mathematica Home Edition? as the webpage shows:
Quotation
Mathematica Home Edition gives home users Mathematica's powerful
technology, developed over 20 years and used by Nobel-winning
scientists and leading corporations. It provides access to curated data,
makes it easy to create and share interactive applications, and a whole
lot more.

It can be used for:


Calculate mortgage, credit card, car, and student loan payments
Evaluate currency exchange rates
Monitor stock market returns and predict trends
And much more...

In short words, Mathematica Home Edition contains the same functions


that can be found in Wolfram's Mathematica 7. it is the full version of
Mathematica but at reduced price for recreational or personal use.

How much does it cost? $295, if you think $295 is a lot, please keep in
mind the full non-student version is $2500!! Sounds a good business?
Start to Import, visualize and calculate using built-in financial data with
Mathematica Home Edition.

PS: this post is by abiao, not by bo.


Tags - mathematica

Please read update at http:://www.mathfinance.cn 40


FinMetrics
I came across a toolbox - FinMetrics this morning, it sounds good from
the introduction of help document, plus highly relevant to our topic
quantitative finance, so I am eager to share it here. However, I am unable
to get access to Matlab and check it in detail at the moment, please help
me test and leave a comment about your thoughts then.

Quotation
FinMetrics is MATLAB based, open source quantitative portfolio
management environment. Built on concepts of bottom-up approach to
application design, it allows users to define most basic, low level
building blocks, e.g. assets and transactions, to be further pieced together
in a higher level objects, e.g. positions or portfolios. Data analysis and
statistics function, implemented within the environment and native to
MATLAB, enable users to conduct scenario analysis, stress testing,
performance measurement and attribution, risk measurement and
attribution, design hedge strategies, etc. Open architecture of the
environment allows users to work with objects of any level, depending
on their requirements and expertise. The object structure and data types
are specifically designed to make integration with MATLAB and native
FinMetrics functions as easy as possible. FinMetrics user interface
application and MATLAB scripting may be utilized to facilitate or
automate complex and repetitive tasks, as well as extend functionality of
the environment.

Download it at http://www.mathworks.com/matlabcentral/
fileexchange/27778-finmetrics if interested.
Tags - matlab

Please read update at http:://www.mathfinance.cn 41


Flash Order
The stock market is a mess of people one-upping other people
constantly. Any chance to get an advantage is seized immediately and
one of those opportunities lies in the so called “Flash” Orders. In a brief
summary, a flash order is a brief glimpses (no more than milliseconds) of
someone else’s exchanges. Of course, only high-speed computers can see
these, but once they are seen, they can be used to get a leg up and buy or
sell ahead of others.

Some regard this as an unfair advantage as professional traders would


gain advance knowledge on trends before individual buyers. Others say
that it adds ‘liquidity’ to the stock market. This opinion comes, of course,
from the big businesses who are using the flash order service to their
advantage to gain a profit. The problem is in the shifts that this brings
about. For example, the big business might buy all of a certain stock, and
then sell it for a bit more than they bought it, but a penny less than what
the next guy is offering it for. This advantage causes motion in a violent
manner in ways that would not be present in normal conditions. While
this can for a time be a benefit, it means it can also fall just as quickly.

Another big gripe is that the High Frequency Trading can really mess
people over. Those with a leg up can make an investment risk-free, and
it is only risk-free for them because all of the risk falls on to the lower
tier. So far, it has upset enough people to be at risk for banning. The
stock market has become a beast to be weary of these days. If this unfair
advantage doesn’t go, what’s to ensure equality in the future?
Fortunately the flash order business will very likely be taken away as
more than a few well-placed officials have been given varitable heebie-
jeebies from this mess. Hopefully order will soon come out of this chaos.
Tags - trading

Please read update at http:://www.mathfinance.cn 42


How to Generate Report Automatically From Matlab
Often we have to generate reports to our boss, colleagues, and clients,
etc. Generally those reports include Matlab source codes, maths
equations, and possibly graphs. How do you generate your reports?
writing down your equations in Word, running your matlab codes,
copying and pasting the results?

It is all right to do like that, but the whole process becomes extremely
simple with the cell mode in Matlab, it generates report automatically for
us, any change you make regarding description, codes and results will
be updated by clicking a simple button: Publish to HTML.

The following steps outline the procedure,


First, opening an editor in Matlab by choosing File -> New -> M-file;
Second, selecting cell and enable cell mode in the editor;
Third, inserting cell divider under cell window, it allows you to type a
name for each section, similar with the title for chapters in Word;
Fourth, depending on your reports, inserting Text Markup, where you
are able to insert description text, bold text, etc. most importantly, it
supports TeX equations;
Finally, clicking "Publish to HTML", a nice-looking report is generated,
and if necessary, changing the codes and re-running to update the
report.

For a simple demonstration, I write the files as follows.


%% Cell mode publish demonstration
% abiao @ mathfinance.cn

%% Using Black Scholes formula as an example


% The value of a call and put options in terms of the Black–Scholes
parameters
% is:
%
% $$C(S,t) = SN(d_1) - Ke^{-r(T - t)}N(d_2) \,$$
%
% $$P(S,t) = Ke^{-r(T-t)} - S (SN(d_1) - Ke^{-r(T - t)}N(d_2)) = Ke^{-r(T-
t)} - S C(S,t)$$

Please read update at http:://www.mathfinance.cn 43


%
% $$d_1 = \frac{\ln(\frac{S}{K}) (r \frac{\sigma^2}{2})(T -
t)}{\sigma\sqrt{T - t}}$$
%
% $$d_2 = d_1 - \sigma\sqrt{T - t}$$

%% Sample code, for simplicity, I use the embedded command


[call, put] = blsprice(10,9,0.02,2,0.3);
fprintf('Call option value is %g. \n',call)
fprintf('Put option value is %g. \n',put)
call1 = [];
put1 = [];
for i = 1:10
call1(i) = blsprice(5 i,9,0.02,2,0.3);
end

%% Sample plot for demonstration only


plot(5 (1:10), call1)

The final report is shown at http://www.mathfinance.cn/attachment/


CellPublishDemo.html, looks fantastic.
Tags - matlab

Please read update at http:://www.mathfinance.cn 44


Matlab Comment Stripping
I have been doing an internship in London since last week and haven't
got enough time to write new posts, sorry for that. So I plan to write a
few posts to summarize the old Matlab functions I personally like a
lot. The one for today is Matlab comment stripping.

Needless to say, comment is crucial for programming, it helps ourselves


to debug our thoughts and other colleagues to understand the codes
efficiently, which is especially indispensable as each programmer has his
own coding style. However, under certain circumstances we may have
to remove those comments, for instance, for the sake of confidential, etc.
How do you do that then? delete the comments line by line? it is OK for
a small file, but generally we may end up with a file with dozens, if not
hundreds, lines of comments, what's worse is those comments intersect
and we have to be carefully to find them out.

Here is a clever way, MATLAB Comment Stripping Toolbox (it indeed


has only 3 short files if you are afraid by "Toolbox" ). Basically it is a
small collection of utilities for stripping MATLAB comments from
MATLAB code. The code may be given in strings, cell arrays of strings,
or read from a file or file identifier. There is full support for stripping
comments from multi-line strings, that is strings with embedded
newlines, which typically appear when an entire file is read in one go.
For example, I wrote a simple test.m file and prefer to remove the
comments and rename it as test-client.m:
% test the comment strip command using mlstripcommentsfile(infile,
outfile)
% by abiao @ mathfinance.cn
a = rnorm(10,1); % check if you can remove me
% one more line
b = rnorm(5,5);
c = rnorm(3,3)...
rnorm(3,3); %now i am here
% test finished

after running the command mlstripcommentsfile('test.m', 'test-client.m'),


I got the file test-client.m to send to others

Please read update at http:://www.mathfinance.cn 45


a = rnorm(10,1);

b = rnorm(5,5);
c = rnorm(3,3)...
rnorm(3,3);

Nice, isn't it? you can download the toolbox at


http://www.mathworks.com/matlabcentral/fileexchange/4645.
PS: the original codes use old Matlab version so you will get the warning
"Warning: The 'tokenize' option for regexprep is now the default
behavior." You may choose to modify the codes by deleting 'tokenize'.
Tags - matlab

Please read update at http:://www.mathfinance.cn 46


Financial Scams
A guest post of Bo.

People have a great amount of concern for money, and finding means to
get money quickly becomes almost a necessity. It is this need for quick
cash and no work that leads people to be drawn into great, sometimes
historical financial scams. One great example would be the use of
historical Bonds.

You see, back ‘in the day’, there were a number of gold bonds issued for
a variety of reasons. A way for the government to obtain money with the
promise to return it with interest. These bonds were payable in gold, and
after a certain maturity point could be cashed in. The problem is that
after a particular date they became useless. Nothing more than a piece of
history waiting to be preserved in a museum.

It is these relics or mock-ups of them that are sold to you by the


conartists. Normally with very official looking documentation and after
you’ve been hopped from bank to bank, you find out that it is in fact
worth nothing except maybe some sentimental collector’s value. If your
lucky, it may actually be an actual Bond, in which case you could get a
small amount of money from a museum that hosts them. This is truly a
great demonstration of one of the historical financial scams.

Another great example is the Viactuals Frauds. The pretense is that you
buy someone’s life insurance policy, making small investments. When
they die you get the full death benefit from said policy. You also walk
away happy knowing that your investments made a sick person’s life a
little better… right? Well just like any child in school there are people out
there who will fake sickness for the attention and the money. Your
money could easily be pocketed and you are left all the poorer. Then of
course there are scammers that will take your investments to buy their
own wants and luxuries rather than using it on the policy you wanted.

And the world goes ‘round. The best way to avoid these historical
financial scams is to stay away from any offer that looks too good to be
true unless you have the help of a real attorney or somebody who really
knows what they are talking about. Scam artists are usually
professionals at their trade, so will not likely be found.

Please read update at http:://www.mathfinance.cn 47


Tags - scam

Please read update at http:://www.mathfinance.cn 48


VarCalc Online Financial Calculator
A guest post of Kang Wang.

The VarCalc Pty Ltd Australia is a specialist in financial modelling &


their numerical methods, actuarial mathematics, web tool development
and Adobe Flash media design. On the web site
http://www.varcalc.com.au, it provides a series of innovative and
comprehensive financial calculators for both Australian and
international investors. These online tools cover many aspects of finance
and investment like home loan & mortgage, savings, personal finance,
bond and financial derivatives. The VarCalc will launch new calculators
regularly.

Tags - calculator

Please read update at http:://www.mathfinance.cn 49


Log Normal Distribution
A guest post by Sidharth Mallik.

The lognormal distribution is used extensively as an approxmiation to


the price of a financial asset after time t given a known price at t=0.
However there is very little known about the lognormal distribution and
the resources are even more limited. I tried finding books about the
lognormal distribution and came up with the following 2 (only 2) :

1. Aitchison J and Brown JAC, 1957. The lognormal distribution,


Cambridge University Press, Cambridge UK.
2. Crow EL and Shimizu K Eds, 1988. Lognormal Distributions: Theory
and Application, Dekker, New York.

among all the books on statistics and millions of resources on normal


distribution the exponential counterpart only has two genuine reference
books.

However my job is to give you some light in the matter. Lets start with
the basic properties of the lognormal distribution :

parameters: sigma^2 > 0 — squared scale (real),


mu an element of R — location
support: x =(0, +Inf)

pdf: \frac{1}{x\sqrt{2\pi\sigma^2}}\, e^{-\frac{\left(\ln


x-\mu\right)^2}{2\sigma^2}}
cdf: \frac12 + \frac12\,\mathrm{erf}\Big[\frac{\ln
x-\mu}{\sqrt{2\sigma^2}}\Big]
mean: e^{\mu+\sigma^2/2}
median: e^{\mu}\,
mode: e^{\mu-\sigma^2}
variance: (e^{\sigma^2}\!\!-1) e^{2\mu+\sigma^2}
skewness: (e^{\sigma^2}\!\!+2) \sqrt{e^{\sigma^2}\!\!-1}
kurtosis: e^{4\sigma^2}\!\! + 2e^{3\sigma^2}\!\! +
3e^{2\sigma^2}\!\! - 3
entropy: \frac12 + \frac12 \ln(2\pi\sigma^2) + \mu
mgf: (defined only on the negative half-axis, see text)
cf: representation

Please read update at http:://www.mathfinance.cn 50


\sum_{n=0}^{\infty}\frac{(it)^n}{n!}e^{n\mu+n^2\sigma^2/2} is
asymptotically divergent but sufficient for numerical purposes
Fisher information: \begin{pmatrix}1/\sigma^2&0\\0&1/
(2\sigma^4)\end{pmatrix}

As you may guess the same information is available at wikipedia at


http://en.wikipedia.org/wiki/Log-normal_distribution.

now for the estimation properties. well conviniently you would want to
estimate the mean and the variance of the corresponding logarithmic
distribution which happens to be normal and then may be use the above
formulas to find the lognormal's parameters. but there is error associated
with this.

An example of the error is :

say you decide on a parameter m as the mean of the corresponding


normal distribution and sigma^2 as the variance. the you may say that
the corresponding mean of the lognormal distribution is simply

mean of lognormal distribution = exp(m+sigma^2/2)

However using some math i will show you that this is not an unbiased
estimator. Let E[.] denote the expectation of the quantity within the
brackets and let M denote the mean of the lognormal distribution.Then if
the above estimator was unbiased, we should have

E[M] = E[exp(m+sigma^2/2)]

But,
E[exp(m+sigma^2/2)] => exp(E[m+sigma^2/2])

according to the Jensen inequality. for those of you who don't know
what this is refer to the http://en.wikipedia.org/wiki/
Jensen_inequality.

Hence there are problems with this form of the estimation. So i would
redirect you to this page check out some other ways how this can be
done

Please read update at http:://www.mathfinance.cn 51


http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1285465

Now having resolved the univariate case we turn our attention to the
bivariate case.

The parameters in this case are the two means, the two standard
deviations and the correlation coefficients. Now the natural question is
how to calculate the correlation coefficient.

The expression for the covariance is

cov(x1,x2) =
exp((sigma1*sigma2)-1)*exp(m1+m2+(sigma1^2+sigma2^2)/2)

The expression for the correlation coefficient is

rho = [exp(sigma1*sigma2)-1]/sqrt(exp(sigma1^2-1)*exp(sigma2^2-1))

For more such references and also to get a table for actual values check
the following out

http://www.stuart.iit.edu/shared/shared_stuartfaculty/
whitepapers/thomopoulos_some.pdf

I will want to finish off with some intuition as to where can you apply
the lognormal distribution. Now first identify if the variable under study
is throughout positive or not like a stock price. Next identify the fact that
the variable contains kind of multiplicative factors in the sense that say
there are levels to the quantity in multiplicative terms. What I mean to
say is that the variable has let us say a level r on normal days.Then when
you expect the variable to go up it goes upto 1.5 times r then even higher
means that it goes to say 5 times r. Similarly for the lower side. If your
variable is indicative of this then it suggests a lognormal distribution.

Tags - distribution

Please read update at http:://www.mathfinance.cn 52


Black Litterman Model (II)
This is the second part of Black Litterman Model, check the first part at
Black Litterman Model (I).

I skip the technical section, which can be found in the original paper
Beyond Black-Litterman in Practice: A Five-Step Recipe to Input Views
on Non-Normal Markets, and the Matlab codes can be downloaded at
http://www.mathworks.com/matlabcentral/fileexchange/9061, in the
Extra->COP folder. Suppose we would like to invest in the US treasury
market at a weekly investment horizon, and we are interested into the
following six key interest rates: 6 month, 2 year, 5 year, 10 year, 20 year
and 30 year. For illustration, we use Monte Carlo simulation to generate
100,000 scenarios based on a t Copula with skew t marginal distribution,
the sample mean, standard deviation, skewness and kurtosis of the six
key rates are shown in table 1.

(table 1)
We can easily see from the table 1 that all of the key rates, in particular
the short period rates, are non-normally distributed as the kurtosis is
significantly larger than 3, which corresponds to normal distribution.

Case 1: Based on the simulated data, we consider a practitioner who has


a 10 bp steepening view on the 2-20 spread and a 5 bp bullish view on
the 2-5-10 butterfly, Further, we assume that those views are uniform
distributed, and the confidence level is 25% in both views. The results
are:

Compared with table 1, we notice the means of 2y and 10y are decreased
significantly, and the means of 5y and 20y are increased, which are
consistent with our assumed views, since we are bearish on 2y and 10y,
and bullish on 5y and 20y.

Case 2: Contrary to case 1, we express a 10 bp bullish view on the 2-20


spread and a 5 bp bearish view on the 2-5-10 butterfly, other things being
equal. We expect that the means of 2y, 5y, 10y and 20y change another
way around.

as expected, the means of 2y and 10y are increased significantly, the


means of 5y and 20y are increased, and the means of 6m and 30y are

Please read update at http:://www.mathfinance.cn 53


again the same as those of prior market.

Case 3: The views are the same as for case 1, but we increase the
confidence for both view from 25% to 75%. We expect the distribution of
posterior market alters more significantly.

identical with what we expected, when compared with the results of case
1, the means of 2y and 10y are decreased more significantly, and the
means of 5y and 20y are increased more pronounced. For all views, the
even moments are only marginally affected. Our robust analysis
demonstrates the strong consistence of the COP approach.

Based on the posterior market values we are able to do return mapping


and portfolio optimization.

These two posts are a short summary of the original paper and Matlab
implementation, please read the source for detail.
Tags - black-litterman

Please read update at http:://www.mathfinance.cn 54


Black Litterman Model (I)
Black-Litterman model is widely used for asset allocation, however, most
of its applications are based on the assumption of normally distributed
markets and views. In this paper Beyond Black-Litterman in Practice: A
Five-Step Recipe to Input Views on Non-Normal Markets, the author Attilio
Meucci extent the Black-Litterman model to allow non-normal
distribution assumption, specifically, skew t distribution is used for
markets and uniform distribution is for investors views as examples. The
author also present general steps to implement the approach in practice.
As a fan of this model, I plan to write two posts on the paper, the pros
and cons of Black litterman will be discussed, and a robust analysis will
be shown to demonstrate its consistence.

Markowitz mean-variance model is the foundation of modern portfolio


theory, it tries to maximize return and minimize risk by carefully
choosing different assets. Although Markowitz model is widely used in
practice in the financial industry, it has at least the following
shortcomings. First, in principle the Markowitz model offers a solution
once the expected returns and covariance of the assets are known.
Although the covariance of a few assets can be adequately estimated, it is
difficult to come up with reasonable estimates of expected returns. Initial
estimates often lead to extreme portfolio solutions and have to be
adjusted many times before they can be considered acceptable by the
decision makers. Second, Markowitz model assumes the future
distribution of assets returns will be exactly the same as that of historical
returns, therefore it does not allow an investor to have views on the
direction of assets growth.

Black-Litterman model bypasses these problems by not requiring the


user to input estimates of expected return; instead it assumes that the
initial expected returns are whatever is required so that the equilibrium
asset allocation is equal to what we observe in the markets. The user is
only required to state how his assumptions about expected returns differ
from the market's and to state his degree of confidence in the alternative
assumptions. From this, the Black-Litterman model computes the
desired mean-variance efficient asset allocation. It is right because of this
character that makes Black-Litterman model be popular both in industry
and academia since it was initially developed in 1990.

Please read update at http:://www.mathfinance.cn 55


However, the original Black-Litterman model helps portfolio managers
to compute the distribution of the posterior market that incorporates
their subjective views with respect to the prior distribution. All these
assumptions are being made considering the entire scenario is normally
distributed. In fact, it is frequently observed that returns in equity and
other markets are not normally distributed. At the same time, you would
expect a practitioner to input his views in a less informative manner. For
instance, instead of a view like ‘I am 90% sure that stock A will have a
2% expected return’, he may have a more accurate view such as ‘I am
90% sure that the return of stock A will stay between -1% and 1% with
equal chance’, or for an Asian option Trader, his views may be a set of
prices at several specific monitoring times, when the option is supposed
to be exercised.

Meucci (2006) solves the above-mentioned issues of the original Black-


Litterman model by developing an approach called Copula-Opinion
Pooling (COP), the author relaxes the normal distribution assumption
and in principle allows any distribution. However, the proposed
implementation in the paper has a distinct distribution under certain
assumptions. Indeed, the market has been assumed to be skew-t
distributed, this strong assumption makes the application of the
approach less evident, although the implementation is pretty
straightforward for any distribution by Monte Carlo simulation, because
Monte Carlo simulation can be applied for almost any distribution and is
suitable for any dimension (at least in theory), COP approach can handle
a portfolio with any number of risk factors.

The second part will be about the Matlab implementation and results
analysis.
Tags - black-litterman , allocation

Please read update at http:://www.mathfinance.cn 56


What Do These 8 Technical Indicators Mean for the Markets?
A guest post by Robert Prechter, CMT.

It is rare to have technical indicators all lined up on one side of the


ledger. They were lined up this way—on the bullish side—in late
February-early March of 2009. Today they are just as aligned but on the
bearish side. Consider this short list:

1, The latest report shows only 3.5% cash on average in mutual funds.
This figure matches the all-time low, which occurred in July 2007, the
month when the Dow Industrials-plus-Transports combination made its
all-time high. But wait. The latest report pertains only through February.
In March, the market rose virtually every day, so there is little doubt that
the percentage of cash in mutual funds is now at an all-time low, lower
than in 2000, lower than in 2007! We will know for sure when the next
report comes out in early May. Regardless, the confidence that mutual
fund managers and investors express today for a continuation of the
uptrend rivals their optimism of 2000 and 2007, times of the two most
extreme expressions of stock-market optimism ever.

2, The 10-day moving average of the CBOE Equity Put/Call Ratio has
fallen to 0.45, which means that the volume of trading in calls has been
more than twice that in puts. So, investors are interested primarily in
betting on further rising prices, not falling prices, and that’s bearish. The
current reading is less than half the level it was thirteen months ago and
its lowest level since the all-time peak of stock market optimism from
January 1999 to September 2000, the month that the NYSE Composite
Index made its orthodox top. The 30-day average stands at 0.50, the
lowest reading since October 2000. It took years of relentless rise
following the 1987 crash for investors to get that bullish. This time, it’s
taken only 13 months.

3,The VIX, a measure of volatility based on options premiums, has been


sitting at its lowest level since May 2008, when wave (2) of ((1)) peaked
out and led to a Dow loss of 50% over the next ten months. Low
premiums indicate complacency among options writers. The quants who
designed the trading systems that blew up in 2008 generally assumed

Please read update at http:://www.mathfinance.cn 57


that low volatility meant that the market was safe, so at such times they
would advise hedge funds to raise their leverage multiples. But low
volatility is actually the opposite, a warning that things are about to
change. The fact that the options market gets things backward is a boon
to speculators. Whenever options writers are selling options cheap, the
market is likely to move in a big way. Combined with the readings on
the Equity Put/Call Ratio, puts right now are a bargain.

4,In October 2008 at the bottom of wave 3 of (3) of ((1)), the Investors
Intelligence poll of advisors (which has categories of bullish, bearish and
neutral), reported that more than half of advisors were bearish. In
December 2009, it reported only 15.6% bears. This reading was the
lowest percentage since April 1987, 23 years ago! As happens going into
every market top, the ratio has moderated a bit, to 18.9% bears. In 1987,
the market also rallied four months past the extreme in advisor
sentiment. Then it crashed. The bull/bear ratio in October 2008 was 0.4.
In the past five months, it has been as high as 3.4.

5,The Daily Sentiment Index, a poll conducted by Trade-Futures.com,


reports the percentage of traders who are bullish on the S&P. The
reading has been registering highs in the 86-92% range ever since last
September. Prior to recent months, the last time the DSI saw even a
single day’s reading at 90% was June 2007. At the March 2009 bottom,
only 2% of traders were bullish, so today’s readings make quite a
contrast in a short period of time.

6,The Dow’s dividend yield is 2.5%. The only market tops of the past
century at which this figure was lower are those of 2000 and 2007, when
it was 1.4% and 2.1%, respectively. At the 1929 high, it was 2.9%.

7,The price/earnings ratio, using four-quarter trailing real earnings, has


improved tremendously, from 122 to 23. But 23 is in the area of the peak
levels of P/E throughout the 20th century. Ratios of 6 or 7 occurred at
major stock market bottoms during that time. P/E was infinite during
the final quarter of 2008, when E was negative. We will see quite a few
quarters of infinite P/E from 2010 to 2017.

8,The Trading Index (TRIN) is a measure of how much volume it takes to


move rising stocks vs. falling stocks on the NYSE. The 30-day moving
average of daily closing TRIN readings has been sitting at 0.90, the

Please read update at http:://www.mathfinance.cn 58


lowest level since June 2007. This means that it has taken a lot of volume
to make rising stocks go up vs. making falling stocks go down over the
past 30-plus trading days. It means that buyers of rising stocks are
expending more money to get the same result that sellers of declining
stocks are getting. Usually long periods of low TRIN exhaust buying
power.

For more market analysis and forecasts from Robert Prechter, download
the rest of this 10-page issue of the Elliott Wave Theorist free from Elliott
Wave International. Learn more here.
Tags - trading

Please read update at http:://www.mathfinance.cn 59


Dealing with Excel Date in Matlab
I was drived crazy yesterday by dealing with the date in Matlab. I have
to download data from different sources, some from datastream, and the
others from Wharton Research Data Services, unfortunately, the date is
in different format, either in a double format as 20081125, or in a cell
format as '25/11/2008' (or something similar) after I import the data
with xlsread() command in Matlab.

those different formats really bring a problem, as I need to match the


dates and compare the prices, it is easy to convert a cell format date to
what matlab recognizes using cell2mat() and then datenum(), for
instance, matlab returns a number 733737 for '25/11/2008', however,
how can I compare that with 20081125 then?

what I am thinking is:


first, convert the cell format to string using cell2mat(), it becomes a string
25/11/2008;
second, reformat the string using datestr(,26), it becomes a string 2008/
11/25;
third, remove '/' by using find(b~='/'), it becomes a string 20081125;
finally, convert the string to number using str2num(), it is eventually a
double number I need 20081125, then I am able to use and match the
date from different sources.

It sounds lengthy, do you have a better idea? please share with us by


leaving a comment, cheers.

Stanley suggests to use the following code:


datenum(datevec(num2str(dates),'yyyymmdd')), here dates is double
number, perfect, it is much better than my method as it allows us not
only for date comparison but also for calculation, what's more, it is
more efficient. many thanks, stanley.
Tags - matlab , excel

Please read update at http:://www.mathfinance.cn 60


Kalman Filter Finance Revisited
Inspired by @MichaelRW at Twitter, I decide to continue the topic on
Kalman Filter following posts Kalman Filter Example and Kalman Filter
Finance.

Specifically, Kalman Filter is applied to estimate the parameters of a Cox


Ingersoll Ross (CIR) one factor interest rate model, (Vasicek model is
simplier than CIR, so the latter is chosen as an example), it is a widely
used mean-reverting process with SDE

A three-factor CIR model has a measurement equation

and a transition equation

source from the paper "affine term structure models: theory and
implementation" downloaded at www.bankofcanada.ca/en/res/wp/
2001/wp01-15a.pdf

I skip the derivation part and recommend the following two papers:
"estimating and testing exponential-affine term structure models by
kalman filter " and "affine term structure models: theory and
implementation" to understand the transition and measurement
equations. Below are the sample Matlab implementation:
function [para, sumll] = TreasuryYieldKF()
% author: biao from www.mathfinance.cn

%%CIR parameter estimation using Kalman Filter for given treasury


bonds yields
% check paper ""estimating and testing exponential-affine term structure
% models by kalman filter " and "affine term structure models: theory
and
% implementation" for detail
% S(t 1) = mu F S(t) noise(Q)
% Y(t) = A H S(t) noise(R)

% read data Y
Y = xlsread('ir.xls');
[nrow, ncol] = size(Y);
tau = [1/4 1/2 1 5]; % stand for 3M, 6M, 1Y, 5Y yield

Please read update at http:://www.mathfinance.cn 61


para0 = [0.05, 0.1, 0.1, -0.1, 0.01*rand(1,ncol).*ones(1,ncol)];
[x, fval] = fmincon(@loglik, para0,[],[],[],[],[0.0001,0.0001,0.0001, -1,
0.00001*ones(1,ncol)],[ones(1,length(para0))],[],[],Y, tau, nrow, ncol);
para = x;
sumll = fval;
end

flip over to next page...

function sumll = loglik(para,Y, tau, nrow, ncol) �lculate log likelihood


% initialize the parameter for CIR model
theta = para(1); kappa = para(2); sigma = para(3); lambda = para(4);
%volatility of measurement error
sigmai = para(5:end);
R = eye(ncol);
for i = 1:ncol
R(i,i) = sigmai(i)^2;
end
dt = 1/12; %monthly data
initx = theta;
initV = sigma^2*theta/(2*kappa);

% parameter setting for transition equation


mu = theta*(1-exp(-kappa*dt));
F = exp(-kappa*dt);

% parameter setting for measurement equation


A = zeros(1, ncol);
H = A;
for i = 1:ncol
AffineGamma = sqrt((kappa lambda)^2 2*sigma^2);
AffineBeta = 2*(exp(AffineGamma*tau(i))-1)/((AffineGamma kappa
lambda)*(exp(AffineGamma*tau(i))-1) 2*AffineGamma);
AffineAlpha = 2*kappa*theta/
(sigma^2)*log(2*AffineGamma*exp((AffineGamma kappa
lambda)*tau(i)/2)/((AffineGamma kappa lambda)*...
(exp(AffineGamma*tau(i))-1) 2*AffineGamma));
A(i) = -AffineAlpha/tau(i);
H(i) = AffineBeta/tau(i);

Please read update at http:://www.mathfinance.cn 62


end

%now recursive steps


AdjS = initx;
VarS = initV;
ll = zeros(nrow,1); %log-likelihood
for i = 1:nrow
PredS = mu F*AdjS; %predict values for S and Y
Q = theta*sigma*sigma*(1-exp(-kappa*dt))^2/(2*kappa) sigma*sigma/
kappa*(exp(-kappa*dt)-exp(-2*kappa*dt))*AdjS;
VarS = F*VarS*F' Q;
PredY = A H*PredS;
PredError = Y(i,:)-PredY;
VarY = H'*VarS*H R;
InvVarY = inv(VarY);
DetY = det(VarY);
%updating
KalmanGain = VarS*H*InvVarY;
AdjS = PredS KalmanGain*PredError';
VarS = VarS*(1-KalmanGain*H');
ll(i) = -(ncol/
2)*log(2*pi)-0.5*log(DetY)-0.5*PredError*InvVarY*PredError';
end
sumll = -sum(ll);
end

I also attach the ir.xls file to test the codes, you should get the parameters
values as:
theta: 0.0613
kappa: 0.2249
sigma: 0.0700
lambda: -0.1110
Click to download
Tags - filter

Please read update at http:://www.mathfinance.cn 63


Down and Out Call Barrier Option
This post is writen by Jovan, one of our contributors currently studying
MFE, thanks, Jovan.

A couple of weeks ago one of my friends had an interview at a local


hedge fund and he had to prepare Greeks of exotics, so we decided to
plot them. In Uwe Wystup’s book, Options in FX markets there is a nice
and very clear analytical solution, and mathematica 7 is good in
symbolic so the code just takes the derivatives and plots them. Also to
check the solution of down and out call we plotted the down and in call
and their payoff combines into a regular call so that there wasn’t a
mistake. If you do not have mathematica there is a mathematica free file
viewer form Wolfram.

Together with the codes there is a mini manipulate idea where you can
see the interaction of the Greeks with other input parameters such as a
Barrier where you see that the delta explodes when you are close to
expiry and to the barriers. Uwe Wystup suggests that then one should do
a barrier shift to prevent this so that one should rehedge your portfolio
based on that shifted barrier. If you are interested to see this please
download the attached Mathematica files and check it out.

Click to download
Tags - barrier , option

Please read update at http:://www.mathfinance.cn 64


Top Ten Sites in Quant and Quantitative Finance
Xmarks is a hot web2.0 site offering bookmark synchronization, search
enhancement and web discovery based on sites bookmarked by users,
therefore to some extent it shows the popularity of a site. Personally I use
it frequently as it gives me a convenient way to bookmark my favourite
wherever I am, no matter using a private laptop at home, or a shared
computer at a coffee bar, I am always able to find and read my interested
sites.

I was surprised to find mathfinance.cn is listed as one of the Top Ten


Sites in 'Quant' and 'Quantitative Finance' several minutes ago when I
happened to search a keyword in Xmarks, I have no idea when it was
listed. Although it may not be treated seriously by others, the rank does
make me happy and will continuously encourage our contributors and
me to write down what we believe useful. It is our great pleasure to have
a blog among those giant sites such as wilmott.com, quantlib.org,
quantnet.com, defaultrisk.com, etc., as always, many thanks for your
bookmarking, your 10 seconds action means a lot to us.

Quantitative Finance Collector is a Top Site in Quantitative Finance


Review This Site

Quantitative Finance Collector is a Top Site in Quant


Review This Site

We have been looking for paid contributors and guest writers, please
consider to join us by reading our policy http://www.mathfinance.cn/
looking-for-paid-contributors/ and http://www.mathfinance.cn/post-
your-article-on-this-blog/, your support is much appreciated.

Have a nice weekends.


Tags - quant , blog

Please read update at http:://www.mathfinance.cn 65


Kalman Filter Finance
A general example of Kalman filter algorithm was briefly discussed at
the blog post Kalman filter example, where a Matlab toolbox link was
shared as well. When it comes to an application of Kalman filter in
finance, one of the best and ealiest paper is Estimating and Testing
Exponential-Affine Term Structure Models by Kalman Filter (a simple search
at Google Scholor tells you this paper has been cited by over 180 times),
in the paper the authors do an empirical analysis of Kalman filter to two
special cases of interest rate models, namely the Gaussian case (Vasicek
1977) and the non-Gaussian case (Cox Ingersoll and Ross1985 and Chen
and Scott 1992), besides a detailed description of how to apply this
algorithm step by step.

Download the programming files of Estimating exponential affine term


structure models at the author's home page
http://www.rotman.utoronto.ca/~jcduan/, however, they are in
GAUSS language I am unfamiliar with (I used to use it when I studied in
Germany seven years ago), so check yourself then.
Tags - filter

Please read update at http:://www.mathfinance.cn 66


48 Hours Left For How to Spot Trading Opportunities
Just let you know there are only 48 Hours Left to Get Your Free 47-Page
eBook: How to Spot Trading Opportunities.

The How to Spot Trading Opportunities eBook features 47-pages of


easy-to-understand trading techniques that help you identify high-
confidence trade setups. Senior EWI Analyst Jeffrey Kennedy will show
you how some of the simplest rules and guidelines have some of the
most powerful applications for trading.

Created from the $129 two-volume set of the same name, this valuable
eBook is offered free until April 23, 2010.

Don’t miss out on this rare opportunity to change the way you trade
forever. Download it NOW.
Tags - trading , ebook

Please read update at http:://www.mathfinance.cn 67


Free Data Directory
Data access is a prerequisite to quant finance study, unfortunately, data
is not cheap, I once list the sites where we can download free data at
financial data download, here is a good free data directory site I came
across a few days ago: wikiposit - A searchable directory of numerical
data on the internet.

Basically Wikiposit spiders those web sites with data and collects data
source information, users can therefore look for their wanted data on one
site only. Currently it has about 110,000 data sets, mostly economic and
financial. For example, a click on finance section you will notice the
following subcategories:

or you can search directly by typing a keyword, take a look if you feel
useful, http://wikiposit.org/w

Tags - data

Please read update at http:://www.mathfinance.cn 68


Kalman Filter Example
The kalman filter is a time series estimation algorithm that is mainly
used combined with maximum likelihood approach to estimate
parameters for given data. Compared with pure maximum likelihood,
which typically assumes that the data series is observed without errors,
and obtains the state variables by inversion, Kalman filter assumes that
all data is observed with measurement errors, which is one of the big
reasons why it becomes more and more popular in economics and
finance, as many models in these fields depend on data that are either
non-observable, for example, bond prices are observable but interest
rates are not; energy future prices are easily observed but underlying
assets are not, etc.; or subject to noise, such as due to bid-ask spreads.

There are two basic equations of a Kalman filter: the measurement


equation and the transition equation, as the names suggest, the
measurement equation relates an unobserved variable (such as interest
rates) to an observable variable (such as bond prices), and the transition
equation allows the unobserved variable to change over time, for
example, interest rates follow a Cox Ingersoll Ross (CIR) process.
Essentially Kalman filter is a recursive algorithm, it starts with initial
values for the state variables and a measure of the certainty of the guess,
and then use these initial values to predict the value of the measurement
equation, since the variables in the measurement equation are observed,
we can calculate the prediction error, together with a kalman gain factor,
to update the values in the transition equation, repeat the process for the
next time period and finally we are able to estimate the parameters
values by maximum likelihood. The following steps outline the specific
procedures of a kalman filter example:

Step 1: writing down the measurement equation and transition equation,


initializing the state vector;
Step 2: forecasting the measurement equation given the initial values;
Step 3: updating the inference about the state vector incorporating
kalman gain matrix and the prediction error;
Step 4: forecasting the state vector of the next time period conditioning
on the updated values of the previous period;
Step 5: calculating the log-likelihood function under a certain
distribution assumption and maximize the log-likelihood, usually a
Gaussian distribution is applied.

Please read update at http:://www.mathfinance.cn 69


For a detailed Kalman filter example in excel, please read the paper "A
simplified approach to understanding the kalman filter technique" for
detail, I also wrote a sample tutorial file trying to mimic the results but
failed, possible reasons are poor performance of solver in excel and the
small simulated sample periods. Interested readers can choose to
download a Kalman filter toolbox for Matlab.
Click to download

Tags - filter

Please read update at http:://www.mathfinance.cn 70


What You Need to Know About Option as A Beginner Part II
A follow up of yesterday's introductory article What You Need to Know
About Option as A Beginner Part I (last one on this topic).

a) Call option
It is the option to buy shares of stock at a specified time in the future.
Often it is simply labeled a "Call". The buyer of the option has the right,
but not the obligation to buy an agreed quantity of a particular
commodity or financial instrument (the underlying instrument) from the
seller of the option at a certain time (the expiration date) for a certain
price (the strike price). Whereas the seller is obligated to sell the
commodity or financial instrument should the buyer so decide. The
buyer pays a fee (called a premium) for this right.

For example, let's look at a call option contract at a strike price of $100 for
a given stock. Let's use the current month for this example. Let your
requirement be to buy 100 shares of the stock which is currently trading
at $110/share. And you are buying those stocks, not by the way of
options, then you would be paying $11000 for the 100 shares. This means
that you will be losing around $1000 for buying the stocks. But if you
were to use this option contract and if it were to expire at the same stock
price of 110/share then you would have the option to buy 100 shares of
that stock at $100/share. Thus you can have a profit of $1000; which is
nothing but the cost to buy the option. Here in this, lets hope that the
stock at the time of expiration will be, say, $115/share and so you would
end up making $500 over what your option costs were. But of course, if
the stock price drops to $105/share then you will end up losing $500 on
the deal, which will be the bad part of it.

The option value, and therefore price, varies with the underlying price
and with time. The call price must reflect the "likelihood" or chance of
the option "finishing in-the-money". The price should thus be higher
with more time to expire and with a more volatile underlying
instrument. The science of determining this value is the central tenet of
financial mathematics. The most common method is to use the Black-
Scholes formula (which discussed before). Whatever the formula used,
the buyer and seller must agree on the initial value (the premium),
otherwise the exchange (buy/sell) of the option will not take place.

Please read update at http:://www.mathfinance.cn 71


b) Put option
A contract between two parties, the writer (seller) and the buyer of the
option. The buyer acquires a short position by purchasing the right to
sell the underlying instrument to the seller of the option for specified
price (the strike price) during a specified period of time.

Let’s look at the same example discussed for ‘Call option’, like you want
to buy an put option contract at a strike price of $100 for a given stock. If
the current value for the stock is $90/share and you wanted to buy the
$100 put option contract you would probably be looking at a price of $10
or $11 in the option price listing. If the stock value doesn’t get increased
in the period of your put option contract, then you would get a profit of
$10/share. But in the other case, where the share value increases beyond
$100, say by $10, then you would face a lose of $10/share. And for this
put option, it is always advisable to exercise the contract if the current
stock value is greater than your contract value. So that you can have a
profit, else if you let it expire then you would end up paying the
premium to the writer unnecessarily.

Future Value
From the above example for both the “call” & “put” option contracts,
you would have got an idea that calculating the future value of the
option. Thus in order to understand option pricing, this future value
additive must be accounted for in your investment plan. Remember the
longer you hold onto an option (call or put), the less valuable is that
future value portion.

Again, Check Varieties of programming codes on option valuation for


implementation.

Tags - option

Please read update at http:://www.mathfinance.cn 72


What You Need to Know About Option as A Beginner Part I
My third introductory article.

Knowledge about Option pricing is essential prior investing in those. If


you are a novice, then you are in the right spot. Here in this article, you
could get a basic knowledge about the Option, its type & pricing etc.

Basic definition of Option


In order to understand about Option pricing, you need know about the
option first. Option is nothing but an official contract, between a buyer
and a seller, that gives the buyer of the option the right, but not the
obligation, to buy or sell a specified asset on or before the option’s
expiration date, at an agreed price (the strike price).

Types (Call and Put)


A “Call option” gives the buyer of the option the right to buy the
underlying asset at the strike price whereas the “Put option” gives the
option to sell the underlying asset at the strike price. If the buyer chooses
to exercise this right, the seller is obliged to sell or buy the asset at the
agreed price. The buyer may choose not to exercise the right and let it
expire. The underlying asset can be a piece of property, a security (stock
or bond), or a derivative instrument, such as a futures contract.

Valuation models
The value of an option can be estimated using a variety of quantitative
techniques based on the concept of risk neutral pricing and using
stochastic calculus. The most basic model is the Black-Scholes model.
These models are implemented using a variety of numerical techniques.
In general, standard option valuation models depend on the following
factors:
• The current market price of the underlying security,
• the strike price of the option, particularly in relation to the current
market price of the underlying asset (in the money vs. out of the money),
• the time to expiration together with any restrictions on when exercise
may occur, and
• an estimate of the future volatility of the underlying security's price
over the life of the option.

Check Varieties of programming codes on option valuation for

Please read update at http:://www.mathfinance.cn 73


implementation.

To be continued...
Tags - option

Please read update at http:://www.mathfinance.cn 74


Value at Risk Estimation with Copula
Value at Risk is widely used to measure the downside risk, and Copula
is a generalized dependence structure instead of linear correlation to
model dependence, especially for lower tail dependence, therefore the
combination of VaR with Copula is fantastic in terms of accurately
capturing the true risk embedded.

I read roughly a working paper Value at Risk – MATLAB Application of


Copulas on US and Indian Markets, where the authors calculate the Value
at Risk (VaR) using the bivariate Gaussian Copula distribution
implemented in MATLAB for the Dow-Jones index and the National
Stock Exchange index. It is good to use Gaussian Copula together with
some rank correlation (like Spearman's rho or Kendall tau) to model the
dependence, however, we must be very careful as basically Gaussian
Copula assumes the joint dependence structure normally distributed and
as a result, no matter which marginal distribution you choose, the upper
and lower tail dependence approach to zero when the significant level
limits to one and zero, in other words, in a bivariate case, the probability
that X2 exceeds its q-quantile, given that X1 exceeds its q-quantile (upper
tail dependence) when q->1, and the probability that X2 is below its q-
quantile, given that X1 is below its q-quantile (lower tail dependence)
when q->0 are zero.

For example, below are two simulated return series, one is under
Gaussian copula and the other one is under Student t copula, as you can
easily see, although both have the same marginal distribution, Gaussian
copula has much smaller upper and lower tail dependence than Student
t copula, which eventually underestimates the Value at Risk and other
risk measures.

I would stay away Gaussian Copula if I were a risk manager, and you?
Download Copula toolbox and other code files at Copula if interested.
Tags - var , copula

Please read update at http:://www.mathfinance.cn 75


Looking for Paid Contributors
As the old saying goes: Many heads are better than one. After joined by
Bo, we are still looking for contributors who are able to write quality
posts to our blog readers. Different from guest post writers who are
allowed to promote their sites or products, paid contributors can receive
a little sum of cash for their contributions to this blog. Of course we can't
make you rich but it is a show of our gratitude and bottles of beer we'd
like to invite you.

You will get paid $5 ~ $15 per post directly to your PayPal or bank
account. Here are the simple rules:

1, you write a post about math finance, ideally with a sample code file
(like, how to calculate ***). For example, a paper you read and its
implementation you wrote, the problem doesnot need to be sophiscated
at all: here are a few examples:
http://www.mathfinance.cn/value-at-risk/
http://www.mathfinance.cn/sudoku-spreadsheet-example-matlab-
excel-link/
http://www.mathfinance.cn/valuation-of-stock-option-with-discrete-
dividend/;
2, the post is original, not copied from somewhere else;
3, the post should be above 250 words;
4, the post is only published on mathfinance.cn.

After we receive your post, we'll let you know how much we are going
to pay (currently between $5 and $15) depending on the quality, and if
you agree, we'll publish your post under your name ASAP. At your
choice, we can also leave your simple profile at About us section.

Payment will be sent without minimum amount limit soon after we


publish your articles. Please support us by sending your articles and
files to abiao @ mathfinance.cn (remove the spaces), or write a guest
post if you prefer that way.

Cheers.
Tags - blog

Please read update at http:://www.mathfinance.cn 76


Advertise with us
Thank you for your interest in advertising on MathFinance.cn. We have
approximately 13,000 unique visitors that view 40,000 pages per month.
Engage our valuable demographic of highly educated quantitative
research readers through multiple placement options including premium
display, buttons and links, email and newsletters, co-registration and
lead generation, sponsorships, home page takeovers and other creative
advertising solutions.

InvestingChannel is one of the fastest growing financial media


companies and is our exclusive advertising partner. With
InvestingChannel’s seasoned team of professionals, you can optimize
your campaigns to maximize return on investment with the highest level
of service. Available ad sizes include 728x90, 300x250, 160x600, 88x31
and many more.

To learn more about advertising on MathFinance.cn contact


InvestingChannel at:

advertiser@investingchannel.com
(p) 646.467.7824
(f) 646.290.8452
www.investingchannel.com

Tags - ad

Please read update at http:://www.mathfinance.cn 77


Monte Carlo Methods for Beginners
Biao has writen several posts on Monte Carlo simulation method for
option pricing and risk analysis, so what is indeed a Monte Carlo
method? as this post is just a general introduction for beginners like me,
please skip if you are familiar with it.

Monte Carlo methods or Monte Carlo Experiments, as they are


commonly referred to as are a class of computational algorithms that use
repeated random sampling to obtain the desired results. They find their
use in simulating mathematical and physical systems. Since these rely
heavily on repeated computation of pseudo-random or random or
numbers therefore, they are better suited for calculation by a computer.

Systems having large number of coupled degrees of freedom like fluids,


strongly coupled solids, cellular structures and disordered materials can
be easily solved using these methods. These are also effective in solving
complicated boundary conditions and multidimensional integral
problems. Today, these methods are being widely used in oil as well as
space explorations.

Monte Carlo is not a single method of problem solving. Instead, it is a


class of approaches that helps in solving complicated problems. These
approaches follow a defined pattern which includes defining the domain
of possible inputs, generating input randomly from the domain,
performing a deterministic computation and aggregating individual
result to the final results. If you are familiar with the term “what if”
scenario, then you should note that Monte Carlo methods are totally
opposite of “what if” scenarios. These simulations or methods consider
random sampling of the probability distribution functions as inputs to
produce thousands of results.

Monet Carlo method was introduced in 1940’s by physicists working in


Los Alamos National Laboratory. After its introduction many new
methods came, but still Monte Carlo method is one of the most popular
methods used for problem solving. The basis of this method is the
probability theory, which also gave birth to a large number of methods.
The popularity and use of Monte Carlo methods increased considerably
after the introduction of computers in 1950’s. USAF and The Rand
Corporation were among the major organizations which started use of

Please read update at http:://www.mathfinance.cn 78


these methods in their day to day operations.

For more technical posts, please search "Monte Carlo" in this blog. For
instance, Variance reduction by antithetic variable.

Tags - monte carlo

Please read update at http:://www.mathfinance.cn 79


Barrier Option Pricing Using Adjusted Transition
Probabilities
One big issue of pricing barrier option with Binomial tree or other lattice
method is its slow convergence rate, the barrier option value converges
very slowly as the number of tree or lattice levels increase, often
requiring unattainably large computing times for even a modest
accuracy. A typical plot of barrier option binomial tree results against its
analytic value looks like

source from paper Enhanced Numerical Methods for Options with Barriers
where the pricing performance is in a sawtooth fashion, with severe
periodic spikes that move away from the correct result, which is a
nightmare for a researcher because adding more steps doesn't
necessarily mean to yield a more accurate answer.
The reason for this is that the barrier being used by the tree is generally
different from the true barrier value, for example, as demonstrated
below, no matter inner barrier or outer barrier is chosen in practice,
calculated value will always be smaller or bigger than correct value,
where true barrier shall be used.

John Hull presents three approaches for overcoming this problem,


namely, positioning nodes on the barriers, adjusting for nodes not lying
on barriers, and the adaptive mesh model. Interested readers please refer
to chapter 20, from page 467 to 472, the 5th version, Options, futures and
other derivatives. Or read another paper in detail "Enhanced Numerical
Methods for Options with Barriers" by Emanuel Derman, etc
downloadable at http://www.ederman.com/new/docs/gs-
numerical_methods.pdf.

The way shared today is distinct from the three approaches, unlike
traditional methods to ensure convergence through placing the barrier in
close proximity to, or directly onto, the nodes of the tree lattice, this
method applies a suitable transition probability adjustment, thereafter
called Barrier Option Pricing Using Adjusted Transition Probabilities,
which exhibits increased convergence to the analytical option price,

source from paper Barrier Option Pricing Using Adjusted Transition


Probabilities

Please read update at http:://www.mathfinance.cn 80


Please read the paper for detail at http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=964623 and check the accompanying C++ codes
at http://www.codeproject.com/KB/recipes/
Zeppelin_Barrier_Options1.aspx
Tags - barrier , option , binomial

Please read update at http:://www.mathfinance.cn 81


Stock Trader Report
Every stock trader is well aware of the fact that anything and everything
is possible in the stock market. Unlike traditional stock investors who
used to be uneducated, reactive, risk avoiders etc. Today, majority of the
stock traders are risk takers, pro active and knows and analyze the
market very well. A stock trader is a person who buys or sells share of
companies at various stock exchanges. Every trader trades for the shares
for the purpose of capital appreciation. A stock trader has a profit motive
in mind and thus, he tries to maximize the worth of his shares by trading
them. A stock trader is least interested in keeping shares with him. He
buys share only to sell them and not to keep them.

A good stock trader is one who knows how to balance the capital
appreciation of shares with the dividend and bonus that he will get on
those shares. Portfolio plays a very important role in the world of stock
market and dividend or bonus helps to increase the portfolio
considerably.

Even though stock trading requires huge risk, still you will find many
people seriously indulging into it. No rocket science is involved in stock
trading, a person who is knowledgeable, good decision maker and
observer can excel and do well in this field.

Before entering into stock trading, it is important for you to develop the
skill set and the mindset needed to be a good stock trader. This field
offers ample opportunities and if you are willing to devote time and
effort, than you will surely come out with flying colors.

Stock trader reports will give you a brief idea of what stock trading is all
about and what factors you should keep in mind when you are dealing
in stocks. Download the most recent free reports at the free report
section.

Tags - trading

Please read update at http:://www.mathfinance.cn 82


Binomial Tree
This post is by Bo, a guest author of the math finance blog, unlike biao's
technical posts, I will be mainly writing introductory articles, which aims
to help beginners have a rough idea, and I will try to link to other
technical posts for a better understanding if possible.

Binomial options pricing model or BOPM, as it is popularly known is a


generalized numerical method that is used for the valuation of options.
This method was proposed by Rubinstein, Cox and Ross. This method is
popular in the sense that it can be used for variety of conditions, while
the other numerical methods have limited use. The main reason why it
can be used in varied situations is that it is based on the underlying
instrument spread over a period of time rather than a single point of
time. It is slower, but much more accurate than any other method.

This method traces the evolution of options underlying variable spread


over a period of time. This is done by using a binomial tree or binomial
lattice. Each node in the binomial tree or lattice represents price of the
underlying at a single point of time. The valuation is performed
iteratively, i.e., it starts from the final node and goes backwards till it
reaches the first node. The value that you will calculate in each node of
the binomial tree is the value of the option at that point of time.

BOPM follows a three step process. In the first step, which is binomial
tree generation, a tree comprised of prices is produced by working
forward the date of valuation to expiration. It is assumed that at each
step the value of underlying instrument is either moving down or up by
a specific factor. The down and up factors are calculated using
underlying volatility. The next step is to find the value of option at each
final node. The option value which is obtained is called the exercise or
intrinsic value. The third step is to find the value of options at earlier
nodes, by moving backwards from the final nodes.

Check Nine Ways to Implement Binomial Tree Option Pricing for


binomial tree implementation.

Tags - binomial

Please read update at http:://www.mathfinance.cn 83


How much do you know about the Greeks?
Option Greeks measure the sensitivity of option's value to a change in
underlying parameters on which the value of an instrument or portfolio
of financial instruments is dependent. Commonly used Greeks include
Delta, Gamma, Vega, Rho, and Theta, which represents partial derivative
to underlying asset price, delta, volatility, interest rate and time to
maturity, respectively. Obviously a good risk control depends largely on
how accurate the way a trader or risk manager compute Greeks, see old
post Option Greeks analysis for nice Matlab files plotting Greeks for
vanilla options.

No matter what the investment, an investor needs to know and fully


understand the potential risks of the investment prior to committing
capital to that investment. In the options market, the Greeks define and
quantify the risks of your position before you commit to the investment.
Understanding the Greeks is a must for proper risk management.
Further, the Greeks can also help you identify and select not only the
proper strategy to fit the opportunity you selected, but also which
specific options to use to create that specific strategy.

Without a full understanding of the risks of an investment, an investor


should never commit hard earned money. If you do not know your
Greeks, you have no business being in the options market! Watch this
complimentary seminar covering the Greeks…
Option Greeks seminar.
Tags - greeks

Please read update at http:://www.mathfinance.cn 84


Mathematics is everywhere
Share a few interesting pics taken by Nikki Graziano, a photographer
and a mathematician. Mathematics is everywhere in a mathematician's
eyes. Source from http://www.thejunction.de/impulse/2010/03/24/
mathematische-funktionen-fur-jeden-geschmack-0017020

Tags - math

Please read update at http:://www.mathfinance.cn 85


High Dimensional Sobol Sequences
Quasi-Monte Carlo methods are very efficient in solving low
dimensional integration problems, for example, pricing a path-
dependent exotic option, among those low discrepancy sequences, Sobol
is undoubtedly one of the best and most widely used due to its high
convergence speed, how to generate Sobol Sequences was shared at
posts Sobol sequence generator, Primitive polynomials for Sobol
sequences, halton and sobol sequences and Sobol and Generalised Faure
sequences.

However, empirical research have shown Quasi-Monte Carlo Sobol


sequences perform poorly for high dimensional integration problems, it
can never be more efficient than the ordinary Monte Carlo simulation,
some researchers suggest to use Sobol sequences with Brownian bridge
for a better result. A recent working paper shared at Articles uses a small
trick - randomized Sobol sequences to avoid the poor performance high
dimensional problem, indeed it is straightforward to add this trick into
your codes. Below is a comparison graph demonstrating the
performance, very impressive.

(Source from A note on multidimensional sobol sequences)

read the paper for detail if interested, http://papers.ssrn.com/sol3/


papers.cfm?abstract_id=1558186

Tags - sobol

Please read update at http:://www.mathfinance.cn 86


Upcoming Webinars by MathWorks
Attending a free webinar is a good way to learn efficiently. Here is a list
of upcoming one-hour live online webinars about MathWorks products
which I think useful to math finance studying.

Date Title Session Time


24
10:00 a.m. (Central
Mar Data Acquisition with MATLAB
european Time)
2010
9:00 a.m. (U.S.
6 Apr Global Optimization with MATLAB
EDT)2:00 p.m. (U.S.
2010 Products
EDT)
9:00 a.m. (U.S.
8 Apr
Digital Signal Processing Using MATLAB EDT)2:00 p.m. (U.S.
2010
EDT)
13 Apr Best Practices for Verification, Validation, 9:00 a.m. (U.S. EDT)
2010 and Test in Model-Based Design 2:00 p.m. (U.S. EDT)
15 Apr MATLAB for Excel Users in 10:00 a.m. (United
2010 Computational Finance Kingdom-GMT)

Enjoy.
Tags - webinar

Please read update at http:://www.mathfinance.cn 87


Binomial Tree Option Pricing with Discrete Dividends
How to value a stock option with discrete dividend was briefly
introduced at http://www.mathfinance.cn/valuation-of-stock-option-
with-discrete-dividend/, where the main goal is to compare the
performance of different methods, namely, Escrowed dividend model,
Chriss volatility adjustment model, Haug & Haug volatility adjustment
model, Bos volatility adjustment model, and Haug, Haug and Lewis
method. I didn't include lattice method for comparison because non-
recombining binomial tree is computer intensive, especially when the
number of dividends is large.

In the book Options, futures and other derivatives by John Hull, how to deal
with discrete dividend with a binomial tree is explained in detail, see
page 402, fifth version, where future discrete dividend is divided into
two types:
1, known dividend yield. For instance, there will be a 3% dividend 3
months later (3% of the stock price), it is straightforward to handle it as
the binomial tree is recombined when the nodes are multiplied by a
percentage, so basically what we need to do is to construct a tree like
usual before ex-dividend date, and then shift all the left tree nodes down
by (1-dividend yield), that's it, the number of nodes are the same as for
non-dividend binomial tree;

(source from Options, futures and other derivatives)

2, known dollar dividend. For instance, there will be a 2.5 dollar


dividend 3 months later, so before ex-dividend date the binomial tree is
constructed as usual but exactly at the date after ex-dividend, the whole
nodes are shifted down by 2.5 dollar, and then a new binomial tree is
constructed, because the nodes are shifted by an absolute amount
number, the new binomial tree is not recombined any more, which
means much more nodes than the non-dividend case. Specifically, as
pointed by Hull, when i = k+m, there are m(k+2) rather than k+m+1
nodes. The issue becomes more challenging when we increase the
number of dividends. Fortunately, there is a simpler way to get around
of this difficulty by dividing the stock price into two components: an
uncertain part and a part that is the present value of all future dividends
during the life of the option. Please check the book for detail Options,
Futures, and Other Derivatives, 7th Economy Edition with CD.

Please read update at http:://www.mathfinance.cn 88


(source from Options, futures and other derivatives)
Should you are interested into a sample implementation in Matlab of
Binomial Tree Option Pricing with Discrete Dividends, take a look at the
file http://www.ualberta.ca/dept/aict/bluejay/usr/local/matlab-6.5/
toolbox/finance/finance/binprice.m.
Tags - dividend , option

Please read update at http:://www.mathfinance.cn 89


Quant Project Outsourcing
I haven't updated my blog for several days as I have been very busy last
week with my own research, courses. In the mean time I also did a few
outsourcing projects, for example, some recent projects including a
portfolio Value at Risk calculation excel with macro supporting
advanced input & output form; an American option calculator
considering discrete dividends in VBA; data clean, missing data
imputation for a small hedge fund; probability of future stock price
exceeding a barrier in Matlab, etc.

Some selected customers' review:


Very satisfied, with the level of work - muzammmil
Fantastic effort abiao, I really appreciated you turning this job around for me so
quickly. If I ever have the need for a quant to help with another custom function,
you are my man. - ABCInvestor
Thanks for your efficiency, you are definately on my list if I need a quick quant.
- John

with received feedback

If you happen to have some math finance projects for outsourcing, you
may consider to give my group and me chance. Although we can't
guarantee we are capable of meeting all your requirements, we can try
best to insure you a satisfied result as long as we promise to undertake
the project, at a low cost. Please email me at abiao @ mathfinance.cn
(remove space) for a quote and proposal if you want, cheers.
Tags - quant

Please read update at http:://www.mathfinance.cn 90


The Big Short: Inside the Doomsday Machine
Most of us have read the book Liar's Poker: Rising Through the
Wreckage on Wall Street, one of the books that define Wall Street during
the 1980s and are highly recommened by many people in academia and
industry, where the author Michael Lewis described his experiences as a
bond salesman in a humon sense. I just got to know today from a friend
of mine recommending a new book The Big Short: Inside the Doomsday
Machine , as described:
Quotation
A brilliant account—character-rich and darkly humorous—of how the
U.S. economy was driven over the cliff. Truth really is stranger than
fiction. Who better than the author of the signature bestseller Liar’s
Poker to explain how the event we were told was impossible—the free
fall of the American economy—finally occurred; how the things that we
wanted, like ridiculously easy money and greatly expanded home
ownership, were vehicles for that crash; and how shareholder demand
for profit forced investment executives to eat the forbidden fruit of toxic
derivatives.

I don't know, considering the high quality of Liar's Pocker, it may be


worth reading. I pre-ordered just now at Amazon, if you also want a bed
reading book, order one at only $15.09 at Amazon to be released on
March 15, 2010. The Big Short: Inside the Doomsday Machine.

Tags - amazon , book

Please read update at http:://www.mathfinance.cn 91


Calibrating Stochastic Volatility Models with Heuristic
Techniques
Stochastic volatility models, specifically, Heston model, SABR model, are
introduced before and become the widely used among academia and
industry. However, the calibration process is difficult because generally
the pricing requires numerical integration, and calibration requires to
find five and eight parameters instead of only one for Black Scholes
model.

Found a paper Calibrating Option Pricing Models with Heuristics, where the
author look into the calibration of Heston (1993) and Bates (1996)
models. Finding parameters that make the models consistent with
market prices means solving a non-convex optimisation problem.
Optimisation heuristics is suggested for this issue, more specifically they
show that Differential Evolution and Particle Swarm Optimisation are
both able to give good solutions to the problem.

Take a look if you are interested, in the Appendix the R and Matlab
codes are given for a better understanding. http://papers.ssrn.com/
sol3/papers.cfm?abstract_id=1566975
Tags - stochastic , heuristic

Please read update at http:://www.mathfinance.cn 92


How to Spot Trading Opportunities
How To Use Bar Patterns to Spot Trade Setups
30 Instructional Charts With Simple Explanations

If you are a trader or are the least bit interested in trading, you're most
likely "chart-centric." A good chart is priceless if it helps to identify a
great opportunity.

But without the right education, you could be missing high-probability


trade setups that should be staring you right in the face.

That's where our FREE report, How to Use Bar Patterns to Spot Trade
Setups, can help. You'll learn to identify and capitalize on bar patterns
such as the Double Inside Day, the Arrow, and the Popgun. And you'll
get a brand a new addition to the original report, "How to Make Bar
Patterns Work For You," which adds two more important patterns: the
Three-In-One Bar Pattern and the Outside-Inside Reversal.

Download Your Free Bar Patterns Report Now.


Tags - trading

Please read update at http:://www.mathfinance.cn 93


VaR Historical Simulation
Following Value at Risk xls and var backtesting, a third post about using
historical simulation for Value at Risk calculation. We know one
shortcoming of historical simulation is: the result highly depends on the
choice of sample data length, VaR result does not vary often or changes
suddenly. Despite this weakness, HS is still popular due to its obvious
advantage: easy to implement, and no distribution assumption required,
which is especially appealing if the estimate of distribution assumption
is difficult. Several ways have been proposed to improve HS's
performance, here are two selected methods with good results I
personally use.

1, The Best of Both Worlds: A Hybrid Approach to Calculating Value at


Risk by Jacob Boudoukh1, Matthew Richardson and Robert F. Whitelaw.
By hybrid it means this approach is a combination of RiskMetrics's
parametric method and Historical Simulation. The basic idea is: since we
can allocate larger weight to recent data and smaller weight to remote
data for exponential weighted moving average (EWMA) volatility
calculation, hence improves the backtesting performance of parametric
method, why can't we then apply a similar principle to historical
simulation? make sense? so it estimates the VaR of a portfolio by
applying exponentially declining weights to past returns and then
finding the appropriate percentile of this time weighted empirical
distribution. The following results are from the paper The Best of Both
Worlds: A Hybrid Approach to Calculating Value at Risk, page 11. It does
improve compared with the vanilla historical simulation and EWMA
parametric method, nice.

2, INCORPORATING VOLATILITY UPDATING INTO THE


HISTORICAL SIMULATION METHOD FOR VALUE AT RISK by John
Hull and Alan White. The idea is to "adjust" return based on the ratio of
current volatility to the past volatility, and use historical simulation on
the adjusted returns. Their argument is supposing today's volatility is
20%, while volatility was say, 30%, then past returns obviously
exaggerate the current market situation if used directly. They even
compare their performance with the first one above and the results are:

source from INCORPORATING VOLATILITY UPDATING INTO THE

Please read update at http:://www.mathfinance.cn 94


HISTORICAL SIMULATION METHOD FOR VALUE AT RISK page 17.

Results are promising, aren't they? few lines of codes are enough for the
adjustment.
Tags - var

Please read update at http:://www.mathfinance.cn 95


Friday reading list of this week
Friday again, just a final kind remind, since Change of Friday Reading
List Setting, I have been updating Friday reading list on page articles, for
example, the list of this week includes:
1, Testing for Asymmetric Dependence, http://www.bepress.com/
snde/vol14/iss2/art2/;
2, Index-Exciting CAViaR: A New Empirical Time-Varying Risk Model,
http://www.bepress.com/snde/vol14/iss2/art1/;
3, Improving Portfolio Selection Using Option-Implied Volatility and
Skewness , http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1559642;
4, Trading Activity and Bid-Ask Spreads of Individual Equity Options,
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1553222;
5, The Method of Simulated Quantiles, http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1561185

Keep an eye on page articles.


Tags - friday

Please read update at http:://www.mathfinance.cn 96


Inverse Graphing Calculator
An interesting application of Inverse Graphing Calculator, where you
enter any word from A to Z into your calculator and then get a graph of
the curve.

For instance, if you write an equation:

you would get a graph below:

Creat your own at http://www.xamuel.com/inverse-graphing-


calculator.php
Tags - graph

Please read update at http:://www.mathfinance.cn 97


Sudoku Spreadsheet Example of Matlab Excel Link
Sudoku is one of my favorite small games I often have fun with, I save
one copy at my gphone and play it whenever I want to take a rest. (most
of us may have a wrong impression that Sudoku originated in Japan, no,
in America.)

I happened to find Cleve Moler solved Sudoku using recursive


backtracking method and the speed is fast, the minor error is it doesn't
report an error when the initial 9*9 matrix you give violates Sudoku
rules (you can test it later, the code starts to run and returns a result even
you give repetitive numbers along a same row or column). Since
building a GUI in matlab isn't easy, I choose to build a Sudoku
spreadsheet using Matlab Excel link for an example.

Once you install Excel Link module and turn it on, you will notice the
short-cuts on the excel menu bar looking like

intuitively, those buttons stand for "start matlab", "send data to matlab",
"retrieve data from matlab", and "execute the matlab command",
respectively.

For my case, I first download the Sudoku M code at


http://www.mathworks.co.uk/company/newsletters/news_notes/
2009/
clevescorner.html?s_cid=ACD0210ukTA2&s_v1=8728847_1-BR7DSN,
then open an excel file, write down a 9*9 matrix "X"

then define a zone to fetch the calculation result, which should also be
9*9

finally do steps:
<- put data to matlab, MLPutmatrix("X",X)
<- solve the problem in matlab, MLEvalString("X=sudoku(X)")
<- get results from matlab, MLGetMatrix("X","NewX")

result is then retrieved immediately to Sudoku Spreadsheet from matlab

Please read update at http:://www.mathfinance.cn 98


Straightforward to run your Matlab function in excel, isn't it?
alternatively you can use Matlab builder for excel.
Click to download
Tags - matlab , excel

Please read update at http:://www.mathfinance.cn 99


Change of Friday Reading List Setting
I made a small change to the Friday reading list section by adding a new
category Articles, which can be easily seen above at the menu bar. So
from now on all recommended paper, together with shared interesting
articles, will not be shown on the main page any more but rather under
separated Articles category . For one thing, this movement facilitates my
sharing process, I don't have to add paper/articles to my reading list
only on Friday; for another, since not all people like reading technical
paper, they can now choose not to see them at all, which is especially a
benefit to blog feed readers as the reading list will "disappear" from
update.

Also, please consider sharing to your friends if you think this blog is
useful by bookmarking at the right sidebar button or linking to us if
possible, I do appreciate your 10 seconds support.

Have a nice weekend.


Tags - friday

Please read update at http:://www.mathfinance.cn 100


Free market reports and articles
For over ten decades, the mainstream financial world has embraced the
view that external news events drive trend changes in the markets. In
less than ten minutes, EWI's senior tutorial instructor Wayne Gorman
shatters that very idea into a fine dust, swept away into thin air.

In part one of his exclusive, three-part Club EWI video series "Why Use
The Wave Principle," Wayne first assesses the pitfalls of relying on
macroeconomic models to forecast; namely: "An investor is lured into the
market at just the worst time, when it's time to sell, and forced out just at
the best time to buy."

As for real world examples of this happening, Wayne spans three


hundred years of financial history to reveal how the most pivotal
economic, political, and environmental events failed to alter the course of
their respective markets. Here, the free video includes groundbreaking
charts on these (and more) well known episodes:

The S&P 500 and Enron from 2000-2002: The stock market ROSE and
continued to proceed upward AFTER the largest US corporate scandal
and bankruptcy ever (at the time).
The Dow Industrials and GDP quarterly data from 1970 to early 2000s:
After the release of major negative GDP numbers, the market for the
most part ROSE, just the opposite of what most market analysts and
investors expect.
The Dow and profound political events over the last 80 years: In the
1930s and 1940s, a series of negative incidents -- i.e. Hitler rising to
power, World War II, and the Holocaust -- preceded a powerful uptrend
in stocks all the way into the 1960s.
Stock market charts of the five countries most affected by the 2004 Indian
Ocean Tsunami (India, Indonesia, Malaysia, Sri Lanka, and Thailand).
Four out of the five ROSE after the natural disaster...

Believe it or not, we've only scratched the surface. In his myth-busting,


free video "Why Use The Wave Principle," Wayne Gorman presents a
total of 40 charts that capture failed fundamental analysis of the world's
leading financial markets. Wayne recalls this expression from a famous,
Nobel Prize winning economist:

Please read update at http:://www.mathfinance.cn 101


"Economic reasoning will be of no value in cases of uncertainty."

And he offers this response:

"But isn't that what we have in financial markets: cases of uncertainty?


We need a different type of reasoning, one that will help us to avoid the
pitfalls shown on the previous charts. That's why the Wave Principle is
so important. It offers a unique perspective and a market discipline of
rules and guidelines that help investors avoid buying at tops and
liquidating at bottoms. It helps to explain and understand trends before
they happen."

The flaw in Economic 101, cause-and-effect theory is one of the easiest


things to prove. But it's also one of the hardest things for many investors
to accept. Now is the time to do so. Watch the free "Why Use The Wave
Principle," video in its entirety today at absolutely no cost. Simply sign
on to join the rapidly expanding Club EWI and take advantage of the
amazing educational benefits membership has to offer.
Tags - report

Please read update at http:://www.mathfinance.cn 102


VaR Backtesting
A follow-up of my previous post Value at Risk xls, I was asked why not
& how to add a VaR backtesting module in that excel file, well, it is
straightforward in principle to do that but since we have to calculate
daily VaR for multiple periods in order to do backtesting, I simply didn't
add that in an excel for speed reason.

The Backtesting framework developed by the Basel committee is the


main methodology to judge the performance of VaR model, it typically
consists of a periodic comparison of the portfolio’s or asset’s daily VaR
values with the subsequent daily profit and loss (P&L). Obviously, the
ideal model should generate the times of VaR exceeding P&L equal to
(1-alpha) multiplied by time periods for backtesting. For a single equity
case it is obvious what we need to do is comparing daily VaR results
with daily return; but for a portfolio we have to be careful with the
trading positions.

Basel committee (1996) introduces a three-zone approach, where the


green zone means the possibility of erroneously accepting an inaccurate
model is low; yellow zone is risk manager should be careful to check the
model before take action; red zone means the probability of erroneously
rejecting an accurate model is remote. For example, the backtesting three
zones boundaries for a sample of 250 observations, source from Basel
committee, 1996 look like

Backtesting results can therefore be judged by counting the number of


exceptions and seeing intuitively which colour zone it falls into.

Alternatively you can rely on some statistical testing, for instance, the
exception testing by Kupiec (1995).

Your final VaR backtesting results will look similar to

by which you are able to tell the performance of your VaR model.

certainly there isn't only one way for VaR backtesting, the above-
mentioned one is an example.
Tags - var

Please read update at http:://www.mathfinance.cn 103


Financial Analytics Risk Management Tools
Found a site providing financial analytics & risk management tools,
FinCalc, as introduced by its webmaster: "FinCalc provides you with the
tools to build advanced financial functions under Excel. ...FinCalc
covers bonds, money market, futures, options and interest rate
derivatives."

Key points are:


Calendar with business holidays for the major financial centers.
Bond analytics: yield to maturity, duration, accrued interest; valuation
functions and sensitivity measures; bond cash flows; forward price and
repo rate.
Derivatives: valuation functions and sensitivity measures european and
american options; exotic options.
Discount curve construction based on money market rates,short term
futures and swap rates.
Interest rates derivatives: valuation and sensitivity for swaps,swaptions,
caps & floors.
Credit derivatives: valuation and sensitivity for CDS.
Portfolio analytics: volatility, expected return, tracking error, value at
risk, portfolio optimization on an absolute basis or relative to a
benchmark.
User friendliness: meaningful function and parameter names; user's
manual, numerous examples and applications.
Excel add-in and examples to download.

For example, after downloading FinCalc.xla, opening it and other files


saved in a same directory, a user is able to use the following modules:

The author protects the macro code with password, unfortunately.


Check http://homepage.hispeed.ch/FinCalc/Index.htm if interested.
Tags - risk , excel

Please read update at http:://www.mathfinance.cn 104


Binary Options Trading
Binary option is a one of the simple & common type of derivative,
where the payoff is either a certain amount of prescribed cash, called
cash-or-nothing option, or shares, called asset-or-nothing option.
Intuitively, cash-or-nothing option holders receive cash if the option
finishes in the money, asset-or-nothing option holders receive shares of
asset if in the money, thereafter binary options are often named as digital
options.

The pricing of binary options is straightforward under GBM framework,


the widely used Black Scholes formula can be easily adopted for binary
option valuation. Once we understand the principle and know how to
price it, the next step probably is to trade binary options. There are
several online option trading platform for an individual investor to
choose, the one I'd like to review is EZTrader, who has revolutionized
the way binary options are traded on the internet today, by supplying
its customers with a simple, exciting, dynamic and highly profitable
trading platform, very different from traditional option trading. Due to
the simplicity and speed of our binary options trading system and the
low minimum investment amount, it is able to reach investors with
different profiles all over the world. Ranging from sophisticated
investors that are looking for ways to hedge their positions in the
traditional market, to amateur day traders looking for some "action"
without risking large amounts of money, EZTrader developed a system
suitable to most of everyone's goals.

EZtrader have taken the fear and uncertainty out of Forex trading to
focus on an existing new kind of trade. At EZtrader you can trade Binary
Options. With binary options you simply choose whether the stock price
will go up or down by the expiration time and place you call or put
accordingly. With EZtrader your winning return is fixed, you don’t have
to leverage millions of dollars with every trade or setup complicated
stop loss strategy. With EZtrader binary options everything you need is
right in front of you.

Why do I select this online trading service? well, there are at least the
following advantages of EZtrader I am aware of:
- A member is able to trade Nasdaq, Dow Jones and Commodities based
options;

Please read update at http:://www.mathfinance.cn 105


- Hourly trades;
- Open an account is free, absolutely No Fees;
- Members can choose to withdraw fund as they want;
...

Besides simplified trading process, EZTrader members are provided


with a complete set of tools to help them optimize their trading. Tools
include live financial news, references to financial sites and a wide
variety of tradable options, and more. Check EZtrader home page
regularly for new promotions that will help you to get the most out of
your trades, for example, one promotion is: If you deposit a total of
$550.00 today, Monday, February 22nd, 2010, you will receive a bonus
of $250.00 (%45)Registration is totally free and there are no commissions
to pay ever.

To start trading, first go to trading area after sign in, you will find a pool
of options to choose

Choose an option to trade from the list of available options, then select
the type of trade, either CALL or PUT, enter the amount you would like
to trade. you can change the trade type from CALL to PUT or vice-versa
even after entering an amount, finally click 'Trade' to execute your trade.
Simple & new binary options trading platform, start applying your
derivative quantitative skills directly at EZTrader.
Tags - binary , option , trading

Please read update at http:://www.mathfinance.cn 106


Value at Risk xls
A blog reader wrote me an email few weeks ago regarding if it is
possible to share an excel for Value at Risk xls calculation, I didn't
notice that email until recently, sorry for that. So this afternoon I created
a naive excel xls file with VBA macro code available.

Before checking the excel, few sentences explaining Value at Risk


calculation are necessary: Value at Risk (VaR) is the maximum loss not
exceeded with a given confidence level 0

Given confidence level and horizon day, the crucial point for quantile
estimation is to find a suitable distribution of underlying risk factors,
once distribution is known, VaR and ES can be easily calculated by the
definition. Mina and Xiao (2001) explains in detail three popular
methods to compute VaR: parametric approach (the simplest one is
delta-normal), Monte Carlo simulation (MC) and Historical simulation
(HS). I am not going to talk in detail how to calculate them as interested
reader can refer to the paper or the book by John Hull, a short
comparison of the above-mentioned three approaches are listed below,
• HS
– easy to implement, no distribution assumption;
– highly depends on the choice of sample data length, VaR result does
not vary often or changes suddenly.
• MC
– flexible, almost suitable for any distribution;
– assumption of risk factors return required, time consuming.
• Parametric
– easy to implement, not hard to understand;
– assumption of risk factors return required, too simple assumption or
too exotic to implement.

Attached is the ValueatRisk.xls file, where for simplicity, I treat


volatility as normal standard deviation, Value at Risk is computed by
delta-normal, monte carlo simulation and historical simultion for any
single equity, you have to make sure internet is accessible for
downloading data from Yahoo. Please keep in mind this file is created
for illustration only, use at your own risk.

Please read update at http:://www.mathfinance.cn 107


To use it, you need to fill in several parameters including:

where you can change stock symbol "IBM" to any stock you want, as
long as its trading prices are available at Yahoo finance.

Please let me know any error, cheers.


Excel:
Click to download
Macro Code:
Click to download
Tags - var

Please read update at http:://www.mathfinance.cn 108


Friday reading list 19/02/2010
1, Market Timing & Trading Strategies Using Asset Rotation, "In this
paper we present empirical results on the statistical and economic
viability of a market timing trading strategy that is based on rotation
between two risky assets. We use data on Exchange Traded Funds
(ETFs) and models for both the returns and the volatility of the
underlying assets." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1537914
2, Hedging the Black Swan: Conditional Heteroskedasticity and Tail
Dependence in S&P500 and Vix, "In this paper, we show how the
conditional approach of Heffernan and Tawn (2004) can be implemented
to model extremal dependence between financial time series. A hedging
example based on VIX futures is used to demonstrate its flexibility and
superiority against the conventional OLS regression approach."
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1549164
3, Stability of Mean-Variance Portfolio Weights, "The mean-variance
portfolio weights are known to be strongly affected by the estimation
errors of the parameters of asset distribution. Our paper studies this
phenomenon from a new angle. We distil the stability measurements of
separate coordinates of portfolio weights estimator into a single number.
We derive analytical formulas that relate this measure with the mean
and the covariance matrix of asset returns." http://papers.ssrn.com/
sol3/papers.cfm?abstract_id=1553073
4, Unusual News Events and the Cross-Section of Stock Returns, "We
show that stocks that experience a sudden increase in idiosyncratic
volatility earn abnormally high contemporaneous returns but
significantly underperform otherwise similar stocks in the future."
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1362121
5, Exact Simulation of Point Processes with Stochastic Intensities, "This
paper develops a method for the exact simulation of point processes with
stochastic intensities. The method is based on a change of the filtration
that describes the information flow in the point process model."
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1551647
Tags - friday

Please read update at http:://www.mathfinance.cn 109


11 Commonplace Market Views: True or Myth?
A guest post by Susan C. Walker.

"Cash on the sidelines is bullish for stocks." Have you ever heard some
stock market pundit utter these words? Have you ever wondered if the
statement were true? Read this item from the latest issue of The Elliott
Wave Financial Forecast, and you'll wonder no more:

Myth -- Cash on the sidelines is bullish for stocks. This refrain rang
like a gong all the way through the declines of 2000-2002 and 2007-2009.
In February 2000, when mutual fund cash hit 4.2% (compared to 3.8% in
November), The Elliott Wave Financial Forecast issued its “cash is king”
advice. Once again, the word on the street is that there is way too much
“cash on the sidelines” for stocks to fall precipitously. This chart shows
net cash available to investors plotted beneath the DJIA. In December
2007, available net cash expanded to a new high, besting all extremes
since at least 1992, a 15-year time span. Despite the presence of this
mountain of cash, the DJIA lost more than half its entire value over the
next 15 months. Indeed, as the chart shows, cash remained high right as
the stock market entered the most intense part of the crash in 2008.
Available cash does correlate with the market’s moves, but the market is
in charge, not the cash.
----The Elliott Wave Financial Forecast, Jan. 29, 2010

Now take a look at these 10 statements and decide if they are true:

1, Earnings drive stock prices.


2, Small stocks are the place to be.
3, Worry about inflation rather than deflation.
4, It's enough to simply beat the market.
5, To do well investing, you have to diversify.
6, The FDIC can protect depositors.
7, It's bullish when the market ignores bad news.
8, Bubbles can unwind slowly.
9, People can make money speculating.
10, News and events drive the markets.
Bob Prechter and our other analysts have debunked each of these
statements as a market myth. You can discover how we exposed these
ideas as myths, and in turn make more informed decisions about your

Please read update at http:://www.mathfinance.cn 110


investing.

We've gathered the writings that expose these 10 statements as market


myths in our 33-page eBook, called Market Myths Exposed. They come
from two of our premier publications, The Elliott Wave Theorist and The
Elliott Wave Financial Forecast, as well as two of our books, Prechter's
Perspective and The Wave Principle of Human Social Behavior. The
33-page eBook takes the 10 most dangerous investment myths head on
and exposes the truth about each in a way every investor can
understand. You will uncover important myths about diversifying your
portfolio, the safety of your bank deposits, earnings reports, investment
bubbles, inflation and deflation, small stocks, speculation, and more!
Protect your financial future and change the way you view your
investments forever! Learn more, and get your free eBook here.
Tags - elliott , stock

Please read update at http:://www.mathfinance.cn 111


High Probability ETF Trading Strategies on Stock
Finally finished reading the book High Probability ETF Trading: 7
Professional Strategies To Improve Your ETF Trading bought few weeks
ago, in the book the authors share 7 professional quantitative trading
strategies to improve ETF trading, namely: 3-day high/low method, RSI
25/75, R3 strategy, the %b strategy, multiple days up and down, and RSI
10/6 & RSI 90/94 strategy. Since ETF is not easily accessed for individual
investors due to large amount fund requirement, my first thought is: are
these trading strategies suitable for stocks trading? At the end of the
book the authors also said: "the strategies in this book are intended for
ETFs. Many of the concepts are derived from high probability equity
trading strategies, but stocks have very different risks than ETFs". In
addition, the authors also note "ETFs tend to move from overbought to
oversold better than individual stocks", considering all of the 7 strategies
are based on buying on pullbacks, I wasn't optimistic about them on
stocks.

I tested 5 strategies out of 7 for a randomly selected Chinese stock


downloaded from Yahoo, since shorting selling is hard in Chinese
market I exercise long strategy only (which might influence their
performance, I admit). Starting with capital 12500, transaction cost 0.5%
and running for one year data, the results are (pls bear with me, the
graphs look ugly, just for preliminary research):
1, 3-day high/low method

2, RSI 25/75

3, R3 strategy

4, the %b strategy

5, multiple days up and down

Although all for pullbacks, 3-day high/low method did worst with only
0.01 sharpe ratio, compared with the best one the %b strategy 3.34 and
buy & hold strategy 0.74. R3 strategy generates 2.67 sharpe ratio high
enough for trading but we have to be very careful as the slipage cost due
to whipsaw position may kill our profit.

Please read update at http:://www.mathfinance.cn 112


Anyway, as the authors mentioned, we must test seriously before
applying these strategies to non-ETF assets, especially for breakout type
assets.

Tags - strategy , trading

Please read update at http:://www.mathfinance.cn 113


Friday reading list 12/02/2010
Tomorrow is the last day of this lunar year, wish all of you and me happy
Chinese lunar new year.
抬板凳看春晚

1, Modeling the Cross Section of Stock Returns: A Model Pooling


Approach, "This paper illustrates the advantages of a model pooling
approach in contrast to model selection. Model pools of several asset
pricing models including the CAPM, the Fama-French (1993) three-factor
model, and the Carhart (1997) four-factor model are considered for the
purpose of forming expectations (i.e., predictions) of the one-step-ahead
returns for a cross section of stock portfolios." http://papers.ssrn.com/
sol3/papers.cfm?abstract_id=1536050;
2, Option Pricing with Piecewise-Constant Parameters, Discrete Jumps
and Regime-Switching, "In this paper, I address systematically how to
enhance the most existing option models with piecewise-constant
parameters, and how to derive the corresponding closed-form
characteristic function under the risk-neutral measure. As long as the
characteristic function with piecewise-constant parameters is analytical
known, the pricing formula for a European call is then given by inverse
transform of the derived characteristic function."
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1547036;
3, Comparison of Numerical and Analytical Approximations of the
Early Exercise Boundary of the American Put Option, "In this paper we
present qualitative and quantitative comparison of various analytical
and numerical approximation methods for calculating a position of the
early exercise boundary of the American put option paying zero
dividends." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1547783;
4, Multivariate GARCH Models with Correlation Clustering, "This
paper proposes a new clustered correlation multivariate GARCH model
(CC-MGARCH) that allows conditional correlations to form clusters.
This model can generalize the time-varying correlation structure in Tse
and Tsui (2002) by determining a natural grouping of the correlations
among the series." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1548408;
5, Efficient Derivative Pricing by the Extended Method of Moments,
"The local conditional moment restrictions are of special relevance in
derivative pricing for reconstructing the pricing operator at a given day,

Please read update at http:://www.mathfinance.cn 114


by using the information in a few cross-sections of observed traded
derivative prices and a time series of underlying asset returns."
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1550135.
Tags - friday

Please read update at http:://www.mathfinance.cn 115


14 Critical Lessons Every Trader Should Know
A post from our blog sponsor, Elliott Wave International, the world's
largest market forecasting firm founded in 1979 by Robert R. Prechter Jr.
Its staff of full-time analysts provides 24-hour-a-day market analysis to
institutional and private investors around the world.

From today, Elliott Wave International have brought back one of their
most sought after free resources for one week only. The Best of Trader's
Classroom eBook serves up the very best lessons from their popular --
and expensive -- Trader's Classroom Collection in one valuable 45-page
report. If you aren't one of the thousands who downloaded this valuable
resource in its original release, don't miss out on this rare second chance.
The Best of Trader's Classroom eBook is free through February 16.

Some of the most interesting chapters include:

* Why Emotional Discipline is Key to Success


* When to Place a Trade
* How to Use Bar Patterns To Spot Trade Setups
* How To Calculate Fibonacci Projections
* The Best Place for High-Opportunity Trade Setups
* You'll find several more fascinating lessons -- 14 in all

To download the free 14 Critical Lessons Every Trader Should Know, you
need to get your free report by February 16, the price will be back to
normal $59 after that day for all blog readers. Cheers.
PS: forgot to mention, in order to download the free report, you have to
be a member first, the registration requires only username and email
address, which takes half a minute.

Tags - trading , elliott

Please read update at http:://www.mathfinance.cn 116


Research Topic Wanted
I have been struggling to find a suitable research topic for my PhD in
finance these days, initially I chose to research on convertible bond
underpricing considering multiple features other paper might fail to do
so, but later on I realized the potential margin contribution is small with
more knowledge on this field, indeed a few latest paper dealing with this
issue already.

Do you happen to have an interesting topic that you or your colleagues


want to work on while without enough time and resources? then
probably you are able to help me by telling me what the topic is about to
"abiao @ mathfinance.cn" (remove space). The topic needs to be:
1, applicable as a thesis topic;
2, about derivative pricing (equity, fx or IR), trading strategy, portfolio
construction or quantitative risk analysis.

The benefits for both of us:


1, I find a sexy research topic to kill my boring overseas doctor life;
2, you get an update about the progress of the topic also attracting you
from period to period;
3, a problem is solved hopefully.

I know it is hard to find a topic in this way, but I do appreciate any


comment or hint or suggestion, especially from industry side.

Please read update at http:://www.mathfinance.cn 117


Quadrature method for convertible bond pricing
A follow up post of my previous entry Using Quadrature method for
option valuation, where the accuracy and computational speed are
demonstrated briefly with a simple European option based on the paper
"universal option valuation using quadrature methods". Today I play the
Quadrature method for a vanilla convertible bond, still, the results are
promising, for example, below is price performance comparision under
Quadrature and PDE (specifically, finite element method) numerical
solutions, where the CB has time-to-maturity two years, call barrier 12,
call price 110, strike 10, risk-free rate 2%.

The exact computational time depends on the time steps and asset steps,
but generally speaking, since Quadrature has a higher order of
convergency rate, it is several times faster than finite element, in my case,
Quadrature costs me less than ten seconds but finite elements costs me
around one minute.

PS: the y-axis should be relative error.

Tags - quadrature , convertible bond

Please read update at http:://www.mathfinance.cn 118


Dolphin in Taiji
This post has nothing to do with quantitative finance, so please skip it if
you have no interest at all.

A friend of mine, who is an active animal protectionist, asked me if it is


possible to embed a video on my blog. I didn't promise at the beginning
worrying the video has nothing to do with my topic, but decide to do so
after watching it, in addition, today is Sunday, take a rest then.

Dolphin is among the most intelligent animals and its often friendly
appearance and seemingly playful attitude make it popular, I once read
an article saying dolphin is as smart as an average three years kid,
however, like many other animal species, it is under increasing human
threat, as mentioned in Wikipedia, "In some parts of the world such as
Taiji in Japan and the Faroe Islands, dolphins are traditionally
considered as food, and killed in harpoon or drive hunts."

The video tells us how cruel the fishermen in Taiji are, how the activists
hope to save dolphin but fail, a touching story worthy to think about.
PS: my friend is glad to add how happy he is after knowing Chinese
government imposed a law recently against eatching dog meat in China,
from now on it is illegal. A great step.

Below is the video, 90 minutes long, it is in English and with Chinese


scripts.

Tags - dolphin

Please read update at http:://www.mathfinance.cn 119


Friday reading list 05/02/2010
Several good working paper have been found this week, hope you will
also enjoy them.

1, Quant Nugget 1: Square-Root Rule, Covariances and Ellipsoids:


How to Analyze and Visualize the Propagation Law of Risk in a Multi-
Dimensional Market, "How to analyze and visualize the propagation
law of risk in a multi-dimensional market.", http://papers.ssrn.com/
sol3/papers.cfm?abstract_id=1548162;
2, Variance Swap Portfolio Theory, "Optimal portfolios of variance
swaps are constructed taking account of both autocorrelation and cross
asset dependencies. Market prices of variance swaps are extracted from
option surface calibrations. The methods developed permit simulation of
cash flows to arbitrary portfolios of variance swaps. The optimal design
maximizes the index of acceptability introduced in Cherny and Madan
(2009).", http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1540815;
3, Efficient Options Pricing Using the Fast Fourier Transform , "The
Fourier transform methods provide the valuable and indispensable tools
for option pricing under L´evy processes since the analytic
representation of the haracteristic function of the underlying asset return
is more readily available than that of the density function itself. When
used together with the FFT algorithms, real time pricing of a wide range
of option models under L'evy processes can be delivered using the
Fourier transform approach with highaccuracy, efficiency and
reliability." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1534544;
4, Interest Rates and The Credit Crunch: New Formulas and Market
Models , "We start by describing the major changes that occurred in the
quotes of market rates after the 2007 subprime mortgage crisis. We
comment on their lost analogies and consistencies, and hint on a
possible, simple way to formally reconcile them. We then show how to
price interest rate swaps under the new market practice of using
different curves for generating future LIBOR rates and for discounting
cash flows. Straightforward modifications of the market formulas for
caps and swaptions will also be derived. " http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1332205;
5, How Do Individual Investors Trade? , "This paper examines how
high-frequency trading decisions (especially the choice of market versus
limit orders) of individual investors are influenced by past price changes.

Please read update at http:://www.mathfinance.cn 120


Specifically, we address the question whether trading decisions to open
or close a position are different in the case in which investors already
hold a position than in the case in which they don't.",
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1538760;
6, Optimisation in Financial Engineering , "We discuss the precision
with which financial models are handled, in particular optimisation
models. We argue that precision is only required to a level that is
justified by the overall accuracy of the model. Hence, the required
precision should be specifically analysed, so to better appreciate the
usefulness and limitations of a model." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1547173
Tags - friday

Please read update at http:://www.mathfinance.cn 121


Valuation of stock option with discrete dividend
When asked how to value a stock option without dividend or with
continuous dividend, many people would refer to Black Scholes formula,
but how to price an option with discrete dividend then? certainly Black
Scholes model can't be used directly since one of its assumptions is
continuous payout. Paper Back to Basics: a new approach to the discrete
dividend problem by Haug, Haug and Lewis summarizes the following
ways:
1, Escrowed dividend model, which is the simplist and the least accurate
way as a result. The basic idea of Escrowed dividend model is to adjust
the current stock price by deducting the present value of future
dividends, and plug in the replaced stock price to Black Scholes formula;
2, Chriss volatility adjustment model, besides replacing current stock
price, this model adjusts volatility as well because the Escrowed
dividend model alone decreases the absolute price standard deviation,
hence underestimates an option's value. However, Chriss model yields
too high volatility if the dividend is paid out early in the option’s
lifetime, which generally overprices call options;
3, Haug & Haug volatility adjustment model; which is more
sophisticated than Chriss model and takes into account the timing of the
dividend, unfortunately, the authors show this method performs
particularly poorly for multiple dividends stock option;
4, Bos volatility adjustment model, a even more sophiscated model than
Haug & Haug, but still, it performs poorly for large dividends or long
term options;
5, Lattice method, for example, non-recombining binomial tree
introduced in the bible book Options, Futures, and Other Derivatives
with Derivagem CD (7th Edition), we all know it is time-consuming;
6, Haug, Haug and Lewis method introduced in the above-mentioned
paper, the basic idea is to calculate first the ex-dividend option price by
Black Scholes model, then discount back the ex-dividend value under
equivalent martingale measure. The authors demonstrate the high
accuracy of their model with several examples afterwards.

Below is sample Matlab codes I wrote for comparision, a single dividend


is used for simplicity, results similar to the table listed in the paper

function callprice = DiscreteDividend(s,k,r,t,vol,d,dt)


%compare different methods for a single discrete dividend adjustments,

Please read update at http:://www.mathfinance.cn 122


%read paper by Haug for detail;
%dt: dividend time
BSprice = blsprice(s,k,r,t,vol,0);
AdjS = s-exp(-r*dt)*d;
Escrowed = blsprice(AdjS,k,r,t,vol,0);
%%%%%%%%%Chriss, 1997%%%%%%%%%%
vol1 = vol*s/(s-d*exp(-r*dt));
Chriss = blsprice(AdjS,k,r,t,vol1,0);
%%%%%%%%%Haug, 1998%%%%%%%%%%
vol2 = sqrt(vol^2*dt vol1^2*(t-dt)/t);
OldHaug = blsprice(AdjS,k,r,t,vol2,0);
%%%%%%%%Bos et al. (2003)%%%%%%%%%%
lns = log(s);
lnk = log((k d*exp(-r*dt))*exp(-r*t));
z1 = (lns-lnk)/(vol*sqrt(t)) vol*sqrt(t)/2;
z2 = z1 vol*sqrt(t)/2;
vol3 = sqrt(vol^2 vol*sqrt(pi/(2*t))*(4*exp(z1^2/2-lns)*d*exp(-r*dt)*...
(normcdf(z1)-normcdf(z1-vol*dt/sqrt(t))) exp(z2^2/2-2*lns)*d^2*...
exp(-r*2*dt)*(normcdf(z2)-normcdf(z2-2*vol*dt/sqrt(t)))));
Bos = blsprice(AdjS,k,r,t,vol3,0);
%%%%%%%%%Haug, 2003%%%%%%%%%%%%%%%
NewHaug = exp(-r*dt)*(quad(@(x)blsprice(x-d,k,r,t-
dt,vol,0).*lognpdf(x,lns (r-0.5*vol^2)*dt,vol*sqrt(dt)), d, k d)...
quad(@(x)blsprice(x-d,k,r,t-dt,vol,0).*lognpdf(x,lns
(r-0.5*vol^2)*dt,vol*sqrt(dt)), k d, 20*s));
callprice = [BSprice, Escrowed, Chriss, OldHaug, Bos, NewHaug];

For example, the results of a $7 dividend after 0.5 year are


(DiscreteDividend(100, 100,0.06,1,0.3,7,0.5)): 14.7171 10.6932 11.5001
11.1039 11.0781 11.1062, respectively.

Reading the original paper Back to Basics: a new approach to the discrete
dividend problem if interested, http://www.nccr-finrisk.uzh.ch/media/
pdf/ODD.pdf, or the book The Complete Guide to Option Pricing
Formulas by Haug for more detail.
Tags - dividend , option

Please read update at http:://www.mathfinance.cn 123


On the Brink: Inside the Race to Stop the Collapse of the
Global Financial System
Henry Merritt Paulson, Seventy-five men served as Treasury Secretary of
the United States, blurted out when he learned U.K.'s Financial Service
Authority was reluctant to approve a prebankruptcy deal for Barclays
PLC to acquire Lehman, "The British screwed us." This was revealed in
Paulson's new book "On the Brink: Inside the Race to Stop the Collapse of the
Global Financial System", where the author tell us the key decisions that
had to be made with lightning speed under urgent market conditions,
about Lehman Brothers, AIG, and other financial institutions.

Selected author's note from the book On the Brink: Inside the Race to
Stop the Collapse of the Global Financial System:
Quotation
The pace of events during the financial crisis of 2008 was truly
breathtaking. In this book, I have done my best to describe my actions
and the thinking behind them during that time, and to convey the
breakneck speed at which events were happening all around us.

I believe the most important part of this story is the way Ben Bernanke,
Tim Geithner, and I worked as a team through the worst financial crisis
since the Great Depression. There can't be many other examples of
economic leaders managing a crisis who had as much trust in one
another as we did. Our partnership proved to be an enormous asset
during an incredibly difficult period. But at the same time, this is my
story, and as hard as I have tried to reflect the contributions made by
everyone involved, it is primarily about my work and that of my
talented and dedicated team at Treasury.

--Henry M. Paulson

Tags - book

Please read update at http:://www.mathfinance.cn 124


Most recent quant job offers
Most recent job offers from Quant jobs board:

Scientific programmersCBCS in Cambridge MA


Senior Quantitative Analyst-Modeling at RiskMetrics in London
Trader Exotic Options at ING in Brussels
Equity Quantitative Research Analyst at JPMorgan in NewYork
PHD Internships at Bank of England in London
Associate Program at Partners Group AG in London
Quantitative Research Analysts at State Street in London
Tags - quant , job

Please read update at http:://www.mathfinance.cn 125


Free C++, Matlab, and VBA code for derivative pricing
Volopta is a site I came across yesterday, it contains free C++, Matlab,
and VBA code for derivatives pricing. Derivatives categories include
equity options, options on bonds, swaps, swaptions, options on futures,
variance swaps, collateralized debt obligations, credit default swaps,
volatility models, etc.

At the moment the files uploaded are only a few, which is


understandable considering it is a newly launched website, take a look if
interested, http://www.volopta.com/index.html.

Have a nice weekend.


Tags - derivative

Please read update at http:://www.mathfinance.cn 126


Friday reading list 29/01/2010
1, On the Heston Model with Stochastic Interest Rates, "We discuss the
Heston [Heston-1993] model with stochastic interest rates driven by
Hull-White [Hull,White-1996] (HW) or Cox-Ingersoll-Ross [Cox, et
al.-1985] (CIR) processes. A so-called volatility compensator is defined
which guarantees that the Heston hybrid model with a non-zero
correlation between the equity and interest rate processes is properly
defined. Two different approximations of the hybrid models are
presented in order to obtain the characteristic functions. These
approximations admit pricing basic derivative products with Fourier
techniques [Carr,Madan-1999; Fang,Oosterlee-2008], and can therefore
be used for fast calibration of the hybrid model. The effect of the
approximations on the instantaneous correlations and the influence of
the correlation between stock and interest rate on the implied volatilities
are also discussed." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1382902

2, Dynamic Copula Modelling for Value at Risk, "By using copulas, we


can separate the marginal distributions from the dependence structure
and estimate portfolio Value-at-Risk, assuming for the risk factors a
multivariate distribution that can be different from the conditional
normal one. Moreover, we consider marginal functions able to model
higher moments than the second, as in the normal. This enables us to
better understand why VaR estimates are too aggressive or too
conservative. We apply this methodology to estimate the 95%, 99% VaR
by using Monte-Carlo simulation, for portfolios made of the SP500 stock
index, the Dax Index and the Nikkei225 Index. We use the initial part of
the sample to estimate the models, and the the remaining part to
compare the out-of-sample performances of the different approaches,
using various back-testing techniques." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1542608
Tags - friday

Please read update at http:://www.mathfinance.cn 127


The Quants: How a New Breed of Math Whizzes Conquered
Wall Street and Nearly Destroyed It
Bought a book just now recommended by a friend of mine, The Quants:
How a New Breed of Math Whizzes Conquered Wall Street and Nearly
Destroyed It, what a looong name. The book is written by a Wall Street
Journal reporter Scott Patterson and has got brilliant editorial reviews,
for instance:
Quotation
“Scott Patterson has the ability to see things you and I don’t notice. In
The Quants he does an admirable job of debunking the myths of black
box traders and provides a very entertaining narrative in the process.”
--Nassim Nicholas Taleb

Quotation
"The Quants will keep hedge fund managers on the edge of their Aeron
chairs, while the rest of us read in horror about their greed and their
impact on the wider economy. A gripping tale right until the last
page...but I fear this is perhaps not yet the end of the story."
--Paul Wilmott

Below is a short video of an interview with the author, where Scott


Patterson explains a group called "The Quants" developed complex
systems to trade securities such as mortgage derivatives, which were at
the heart of the crisis.

Sounds like a good book for bed reading, order one if you also fancy it,
The Quants: How a New Breed of Math Whizzes Conquered Wall Street
and Nearly Destroyed It

Tags - quant

Please read update at http:://www.mathfinance.cn 128


Elliott Wave Analysis
Last weekend I reviewed a service called elliott wave analysis at
Popular Culture and the Stock Market, some of my blog readers joined
the free EWI club and downloaded the free report. As a result, elliott
wave international sent me a book elliott wave principle, key to market
behavior and a pen with club logo on, thank you.

So this weekend I'm gonna talk few more words about Elliott Wave
Analysis, what is elliott wave principle then? as described on wikipedia,
"it is a detailed description of how financial markets behave. The
description reveals that mass psychology swings from pessimism to
optimism and back in a natural sequence, creating specific wave patterns
in price movements." Therefore it is a type of investment discipline
combining technical analysis with behavioral finance that attempts to
explain and predict the market trend (of stock, forex, etc.). Unlike those
quantitative techniques we often hear or apply, Elliott Wave Analysis
assumes it is unnecessary to be based on past price charts to decide
where a market is in its wave patten, which is instead decided by
investors' psychology, therefore Elliott Wave Analysis has got criticism,
for example, quantitative researchers tend to blame it is just an art where
the subjective judgement is more crucial than the objective, replicable
verdict of the numbers.

Anyway, it is not bad at all to know the non-quantitative trading world,


if you are interested, I recommend you to watch the following video
"How to Use Elliott Wave Analysis to Boost Your Forex Trading" and
attend the free courses then.

Or watch this classic video from Elliott Wave International's Chief


Currency Strategist, Jim Martens, to see how useful the basics of Elliott
wave analysiscan be. Jim explains how the same basic pattern that R.N.
Elliott discovered back in the 1930s is often all you need to make
informed market forecasts. Then access Jim Marten's intraday and end-
of-day Forex forecasts, completely free from Elliott Wave International.
Get your free Forex forecasts.

Please read update at http:://www.mathfinance.cn 129


Tags - wave, trading, elliott
Watch this full $79 course, FREE. Click Here!

Please read update at http:://www.mathfinance.cn 130


Friday reading list 22/01/2010
1, Time-Varying Momentum Profitability, "In this paper, we present a
comprehensive examination of the time-series predictability of
momentum profits. We uncover a list of intriguing features of the time-
variation in momentum profits: (1) market volatility has significant
power to forecast momentum payoffs, which is even more robust than
that of market state or business cycle variables; (2) the time-series
predictability is centered on loser stocks; and (3) the time-series patterns
appear to be at odds with the cross-sectional results."
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1534325

2, Econometric Modeling for Transaction Cost-Adjusted Put-Call


Parity: Evidence from the Currency Options Market, "this study
developed a transaction cost-adjusted put-call parity (TC-Adj-PCP)
econometric model to examine the efficiency of options markets. The
fundamental analysis of the proposed model concludes that transaction
costs represent an omitted variable for the PCP model, where the
uniqueness of this variable is demonstrated under PCP in the context of
options market efficiency. The novelty of the TC-Adj-PCP model
resolves controversial transaction costs issues for traders and
researchers." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1537834

3, Short-Selling Bans Around the World: Evidence from the 2007-09


Crisis, "find that bans (i) were detrimental for liquidity, especially for
stocks with small market capitalization and high volatility; (ii) slowed
down price discovery, especially in bear market phases, and (iii) failed to
support stock prices. " http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1533163

4, On the Volatility and Comovement of U.S. Financial Markets


around Macroeconomic News Announcements
Tags - friday

Please read update at http:://www.mathfinance.cn 131


Matlab File Exchange
I guess most of Matlab users know Matlab central: an open exchange for
the Matlab and simulink user community, where a major section is
Matlab file exchange, including a large list of Matlab files across wide
application, for example, you can choose to browse files by category

Specifically, financial services, Mathematical modeling and Statistics and


Probability are three categories I keep eyes on.

Besides Matlab central, Matlab M-files database built by university of


Stuttgart is another site I often visit, it has a smaller size but grow
quickly, focusing on using Matlab for numerical calculation.

Stay tuned.
Tags - matlab

Please read update at http:://www.mathfinance.cn 132


Meta Financial Functions Library
Meta Financial Functions Library is a free library for option pricing
written in C++, as of now, Meta Systems offers no commercial products,
and the library is still under beta, as indicated by its author: "The Meta
Financial Formula Library implements many commonly used functions
as correctly as possible once and then provides wrapper functions and
code to be able to reuse the implemenation from other tools and
languages."

At the moment Meta Financial Functions Library covers a wide range of


vanilla and exotic options, which can be obviously seen from the name of
functions, for example, a list of functions includes black76, black76_put,
black76_call, blackscholes, gbs, gcarry, AmericanExchangeOption,
AssetOrNothing, BAWAmericanApprox, BSAmericanApprox,
BinaryBarrier, CashOrNothing, ComplexChooser,
DiscreteAdjustedBarrier, DoubleBarrier, EquityLinkedFXO,
EuropeanExchangeOption, ExchangeExchangeOption, Executive,
ExtendibleWriter, ExtremeSpreadOption, FixedStrikeLookback,
FloatingStrikeLookback, ForEquOptInDomCur, ForwardStartOption,
GapOption, GeometricAverageRateOption, JumpDiffusion, LevyAsian,
LookBarrier, OptionsOnOptions, OptionsOnTheMaxMin,
PartialFixedLB, PartialFloatLB, PartialTimeBarrier,
PartialTimeTwoAssetBarrier, Quanto, RollGeskeWhaley,
SimpleChooser, SoftBarrier, SpreadApproximation, StandardBarrier,
SuperShare, SuperShare_inlined, Swapoption, TakeoverFXoption,
TimeSwitchOption, TurnbullWakemanAsian, TwoAssetBarrier,
TwoAssetCashOrNothing, TwoAssetCorrelation, VasicekBondPrice,
VasicekBondOption...

, what a long list! you shall download the library at


http://www.metasystems.no/, which is free and the author makes the
source code clean and publicly available, learning from others is always
enjoying.

Tags - library

Please read update at http:://www.mathfinance.cn 133


Popular Culture and the Stock Market
Long time I haven't reviewed service provided by other site, this
weekend's review is about a club service by EWI, as stated by its authors:
"Elliott Wave International (EWI) is the world’s largest market
forecasting firm. EWI’s 20-plus analysts provide around-the-clock
forecasts of every major market in the world via the internet and
proprietary web systems like Reuters and Bloomberg. EWI’s educational
services include conferences, workshops, webinars, video tapes, special
reports, books and one of the internet’s richest free content programs,
Club EWI."

Below is a video introduction and a free report to research more about its
club, take a look if interested. Wall Street legend and best-selling author
Robert Prechter says "You can almost hear the Dow going up and down
over the airwaves." Watch this 3-minute clip from his documentary
History's Hidden Engine to see how social mood governs movements in
the stock market and trends in popular culture. Then access his 50-page
report "Popular Culture and the Stock Market" free.

Access Robert Prechter's 50-page report "Popular Culture and the


Stock Market" FREE!

Tags - stock , elliott

Please read update at http:://www.mathfinance.cn 134


Fridays reading list 15/01/2010
Two paper I find pretty interesting this week, both are published in
Mathematical Finance Journal:
1, PRICING AND HEDGING AMERICAN OPTIONS ANALYTICALLY:
A PERTURBATION METHOD, by JIN E. ZHANG and TIECHENG LI,
"This paper studies the critical stock price of American options with
continuous dividend yield. We solve the integral equation and derive a
new analytical formula in a series form for the critical stock price.
American options can be priced and hedged analytically with the help of
our critical-stock-price formula. Numerical tests show that our formula
gives very accurate prices. With the error well controlled, our formula is
now ready for traders to use in pricing and hedging the S&P 100 index
options and for the Chicago Board Options Exchange to use in
computing the VXO volatility index."

2, ACHIEVING HIGHER ORDER CONVERGENCE FOR THE PRICES


OF EUROPEAN OPTIONS IN BINOMIAL TREES, by MARK S. JOSHI,
"A new family of binomial trees as approximations to the Black–Scholes
model is introduced. For this class of trees, the existence of complete
asymptotic expansions for the prices of vanilla European options is
demonstrated and the first three terms are explicitly computed.As
special cases, a treewith third-order convergence is constructed and the
conjecture of Leisen and Reimer that their tree has second-order
convergence is proven." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=976561
Tags - friday

Please read update at http:://www.mathfinance.cn 135


A Finite Element Differential Equations Analysis Library
Attended a training of NAG Toolbox for MATLAB today (NAG is short
for Numerical Algorithms Group), nice presentation and persuasive
performance against Matlab toolbox. I will soon get a licence and start to
experience myself.

Anyway, I got to know two sites after the training, first one is deal.II,
which is a finite element differential equations analysis library aiming to
enable rapid development of modern finite element codes, using among
other aspects adaptive meshes and a wide array of tools classes often
used in finite element program. As stated on its webpage: "deal.II is a
C++ program library targeted at the computational solution of partial
differential equations using adaptive finite elements. It uses state-of-the-
art programming techniques to offer you a modern interface to the
complex data structures and algorithms required." It should be very
useful for those people playing often with PDE numerical solution.

The other site is Walking randomly, a blog where the author randomly
collects things including mathematics, physics, vintage computing,
Linux, pocket PCs, Android, music and programming. I am especially
interested in its Matlab, R, NAG, and statistics categories.

Have a nice weekend.

Tags - nag , finite-element

Please read update at http:://www.mathfinance.cn 136


Friday reading list 01/08/2010
1, Yes, the Choice of Performance Measure Does Matter for Ranking of
US Mutual Funds, "Recent literature in performance evaluation has
focused on preferences and characteristics of returns’ distribution that go
beyond mean and variance world. However, Eling (2008) compared the
Sharpe ratio with some of these performance measures, and found
virtually identical rank ordering using mutual fund data. This paper
compares 13 performance measures with the traditional Sharpe Ratio
using a sample of US Fixed-Income, Equity and Asset Allocation Mutual
Funds. Results show that performance measures based on absolute
reward-risk ratios have similar rankings, when the numerator (mean
excess return) is the same. However, when we move to other types of
performances measures, results may be significantly different. "
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1403916

2, The Augmented Black-Litterman Model: A Ranking-Free Approach to


Factor-Based Portfolio Construction and Beyond, "The Fama and French
(1992 and 1993 etc.) factor ranking approach is very popular among
quantitative fund managers. However, this approach suffers from
hidden factor view, loss of information, etc. issues. Based on the Black-
Litterman model (Black and Litterman, 1992; as explained in Cheung,
2009A), we design a technique that endogenises the ranking process and
elegantly resolves these issues. This model explicitly seeks forward-
looking factor views and smoothly blends them to deliver robust
allocation to securities. Our numerical experiments show this is an
intuitive and practical framework for factor-based portfolio construction,
and beyond." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1347648

3, Transparent Augmented Black-Litterman Allocation: Simple and


Unified Framework for Strategy Combination, Factor Mimicking,
Hedging, and Stock-Specific Alphas, "You have some factor, strategy,
and/or stock-specific alpha ideas. Without an optimiser, some
straightforward linear algebra gives you the diversified and efficient
Bayesian allocation that allows greater performance accountability. All
you need is just a factor risk model. How does this sound? This paper
derives a transparent version of the ABL model (Cheung, 2009B) with an
explicit allocation expression, including components for all the needed
functionalities. In addition to further insights, it allows more tangible

Please read update at http:://www.mathfinance.cn 137


implementation of strategy combination, factor mimicking, hedging, and
stock-specific bets in a unified framework." http://papers.ssrn.com/
sol3/papers.cfm?abstract_id=1347663

4, Homogeneous Volatility Bridge Estimators, "We present a theory of


homogeneous volatility bridge estimators for log-price stochastic
processes. The main tool of our theory is the parsimonious encoding of
the information contained in the open, high and low prices of incomplete
bridge, corresponding to given log-price stochastic process, and in its
close value, for a given time interval. The efficiency of the new proposed
estimators is favorably compared with that of the Garman-Klass and
Parkinson estimators." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1523225

5, A PDE Pricing Framework for Cross-Currency Interest Rate


Derivatives, "We propose a general framework for efficient pricing via a
Partial Differential Equation (PDE) approach of cross-currency interest
rate derivatives under the Hull-White model. In particular, we focus on
pricing long-dated foreign exchange (FX) interest rate hybrids, namely
Power Reverse Dual Currency (PRDC) swaps with Bermudan cancelable
features." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1502302

Have a nice weekend.


Tags - friday

Please read update at http:://www.mathfinance.cn 138


Google Quant Staff
Sharing a Google Quant Staff page I created initially for myself, the
motivation was to make the job more convenient since I had to search in
Google too many times per day, what's worse is sometimes I prefer
video results, while sometimes what I need is just PDF documents or
Matlab files. Adjusting frequently with Google advanced search makes
me feel silk.

Google Quant Staff is by no means an invention, I just put several


searching filters in one page, that's it.

For example, to find pdf documents about "Asian option", simply type
"Asian option" in the form and click the PDF icon

Similarly each icon stands for one filter:

Searching results will be openned in a new browser window in Google


as what I did was creating a page to filter results. You can also choose to
search books in Amazon below.
PS: the page can also be used for keywords nothing to do with Quant
staff as long as google catches them.

Anyway, hope you find it somehow useful: Google Quant Staff,


bookmark if you like.
Tags - google , quant

Please read update at http:://www.mathfinance.cn 139


Vanna Volga Method
The vanna volga method is a popular pricing model for implied
volatilities, especially for foreign exchange options, it is an empirical
procedure that can be applied to "draw" an implied volatility smile curve
from three given quotes (reversal, ATM and butterfly) for a certan time
to maturity. Empirical research shows the vanna volga method has a
comparable pricing performance with some stochastic volatility model,
for example, Castagna and Mercurio (2007) show the implied volatility
curve of vanna volga method outperforms that of Malz (1997), and
performs equally well as of SABR (2002).

By building a self-financing portfolio consisting a unit of option at strike


K, -delta1 units of underlying asset, and -xi units of options at strike ki,
Castagna and Mercurio (2007) calculate the weight xi for three given
quotes with the help of Ito's lemma and then approximate the European
option value under vanna volga method, as stated in the paper, VV
pricing model has several advantages: "it has a clear financial rationale
supporting, based on the hedging argument...; it allows for an automatic
calibration to the main volatility data...; ... it can be extended to any
European-style derivative..."

Below is a simple Matlab code to price a call option based on Castagna


and Mercurio (2007):
% option price under Vanna volga model for any strike k
% sigma2 is ATM implied vol, k2 is ATM strike
s = 1.205;
t = 94/365;
r = -log(0.9902752)/t;
rf = -log(0.9945049)/t;
sigma1 = 0.0979;
sigma3 = 0.0929;
sigma2 = 0.09375;
k1 = 1.172;
k3 = 1.2504;
k2 = 1.2115;
k = 1.24;
Vega1 = Vega(s,k1,r,t,sigma2,rf);
Vega3 = Vega(s,k3,r,t,sigma2,rf);
Vegak = Vega(s,k,r,t,sigma2,rf);

Please read update at http:://www.mathfinance.cn 140


x1 = Vegak*log(k2/k)*log(k3/k)/(Vega1*log(k2/k1)*log(k3/k1));
x3 = Vegak*log(k/k1)*log(k/k2)/(Vega3*log(k3/k1)*log(k3/k2));
price = blsprice(s,k,r,t,sigma2,rf) x1*(blsprice(s,k1,r,t,sigma1,rf)...
-blsprice(s,k1,r,t,sigma2,rf)) x3*(blsprice(s,k3,r,t,sigma3,rf)...
-blsprice(s,k3,r,t,sigma2,rf));

where Vega is a function to compute vega under black scholes formula


function VegaValue = Vega(s,k,r,t,sigma,rf)
d1 = (log(s/k) (r-rf 0.5*sigma^2)*t)/(sigma*sqrt(t));
VegaValue = s*exp(-rf*t)*sqrt(t)*normpdf(d1,0,1);

Implied volatilities curve is therefore easily achieved by inverting VV


pricing model. Interested ppl please refer to http://www.risk.net/risk/
technical-paper/1506580/the-vanna-volga-method-implied-volatilities
or an advanced one www.mathfinance.de/wystup/papers/
wystup_vannavolga_eqf.pdf
Tags - volatility

Please read update at http:://www.mathfinance.cn 141


Post your article on this blog
Happy new year!

I have got few emails and messages recently asking for the possibility to
write an article and post on Quantitative finance collector blog, for
example, "I have come across finance sites and am willing to contribute
with an article. Please do let me know if you are interested to do so", "I
love to write unique finance articles & after seeing ur site I have written
one unique article for ur site. Will u be interested to publish it in ur site
along with my link"...

Forgive me if I didn't reply individually, the general answer is: YES, you
can, but subject to the following criteria:
1, the content of the article must be relevant to quantitative finance in
general, specifically, any article about quantitative trading, quantitative
risk analysis, derivative pricing code and software, etc., is highly
welcomed;
2, the article must be unique and writen only for Quantitative finance
collector blog, instead of a copy from sites;
3, the site linked to must be healthy.

The benefits of posting artiles on this blog:


1, as a sign of gratitude, we will put a link back to your site in the post,
which will increase the exposure and traffic of your site;
2, the link is do-follow, which means the link will be better recoganized
by search engines;
3, more opinions on this blog is always good for our readers.

How to post an article:


simply send your article to abiao @ mathfinance.cn (remove space).
Posting an article is totally free as we believe it will be a win-win
strategy.
Tags - blog

Please read update at http:://www.mathfinance.cn 142


Friday reading list 12/25/09
Have little time to read paper this week due to Christmas holiday, so
only two are selected on this Friday's reading list:
1, Smile Dynamics IV. Recall we have collected the three simle dynamics
paper by Lorenzo Bergomi, Quant of the Year 2008 awarded by Risk
Magazine at lorenzo bergomi smile dynamics I, II and III, this is his
fourth version. "In this paper we address the relationship between the
smile that stochastic volatility models produce and the dynamics they
generate for implied volatilities. We introduce a new quantity, which we
call the Skew Stickiness Ratio and show how, at order one in the
volatility of volatility, it is linked to the rate at which the at-the-money-
forward skew decays with maturity. We then focus on short maturity
skews and (a) show that the difference between realized and implied SSR
can be materialized as the P&L of an option strategy, (b) introduce the
notion of realized skew." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1520443

2, What Drives Interbank Rates? Evidence from the Libor Panel. "The
risk premium contained in the interest rates on three-month interbank
deposits at large, internationally active banks increased sharply in
August 2007 and risk premiahave remained at an elevated level since.
This feature aims to identify the drivers of this increase, in particular the
role of credit and liquidity factors." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1517680
Tags - friday

Please read update at http:://www.mathfinance.cn 143


Happy Christmas 2009
Christmas & New Year are around the corner, many thanks for your visit
and support www.mathfinance.cn in 2009, Wish all of you healthy &
wish a quick recovery of global Quant market.

Good good study, Day day up, a song Christmas With a Capital "C"

Tags - christmas

Please read update at http:://www.mathfinance.cn 144


Earn money as a part-time Quant
Thought twice before typing these words, ok, let me make it clear, this
post is only for those people with similar situation with me: either being
laid off as a Quant recently, or being still a student with Quant major,
luckily or not, I am both types, being fired several months ago and now
studying for my PhD. I am writing the post to share my experience as a
part-time Quant, earn little cash to cover my living costs (plus expenses
for beer in weekends), most importantly, to do jobs we like (please
forgive me if you notice I add ad block on my blog, I increase my alcohol
intake, practice really makes perfect...)

I know Elance several weeks ago refered by a friend of mine, who is a


software engineer and gets used to do SOHO jobs, "why not try to be a
freelancer since you now have enough self-controlled time?", that's the
first reaction he had, then I knew the site and started to earn spare
money. Basically Elance is a portal where companies find, hire, manage
and pay contractors online, and is a place independent professionals to
meet clients and get paid for delivering great results. I personally found
several great projects already, not bad payment plus opportunities to
practice our quant knowledge, for example, two randomly chosen
projects about derivative: one is forex trading strategy

and the other one is about option portfolio profit and loss calculation

If you are interested, just Register Free, Looking for work? Sign up at
Elance and search over 30,000 jobs today. and Bid on the Project, once
your proposal is selected, you are in and start to do the project.

The other site I personally find useful is first tutor, a site allowing people
to register as a tutor and to teach part time.

Anyway, earning by doing a job I like is always cool.


Tags - quant

Please read update at http:://www.mathfinance.cn 145


Friday reading list 12/18/09
Instead of posting Chinese financial news, I will collect a list of
interesting paper to read on every Friday, hope you'll enjoy them (please
don't forget to forward to and share your favorites with me).
Downloading links are following the titles if they are publicly available.

1, Characteristic-Based Mean-Variance Portfolio Choice. "The empirical


results highlight the potential for 'stock-picking' in international indexes,
using characteristics such as value and momentum, with the
characteristic-based portfolios obtaining Sharpe ratios approximately
three times larger than the world market." http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1501141;
2, An Arbitrage-Free Generalized Nelson–Siegel Term Structure Model.
"we introduce a closely related generalized Nelson–Siegel model on
which the no-arbitrage condition can be imposed. We estimate this new
AFGNS model and demonstrate its tractability and good in-sample fit."
http://www.frbsf.org/publications/economics/papers/2008/
wp08-07bk.pdf;
3, MATLAB Applications of Trading Rules and GARCH with Wavelets
Analysis. "we provide MATLAB routines for two major used trading
rules, the moving average indicator and MACD oscillator as also the
GARCH univariate regression with Monte Carlo simulations and
wavelets decomposition, which is an update of an older algorithm."
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1523365;
4, Reduced-Form Valuation of Callable Corporate Bonds: Theory and
Evidence. "We develop a reduced-form approach for valuing callable
corporate bonds by characterizing the call probability via an intensity
process. Asymmetric information and market frictions justify the
existence of a call-arrival intensity from the market's perspective. ...
Empirical results show that the reduced-form model fits callable bond
price data well and outperforms the traditional approach in both in-
sample and out-of-sample applications.", http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=972121

This week's tweets:


1, The 25 Most Powerful Men In Finance, http://dealbreaker.com/2009/
12/the-25-most-powerful-men-in-fi.php;
2, Remembering Paul Samuelson, http://www.bbc.co.uk/blogs/
thereporters/stephanieflanders/2009/12/

Please read update at http:://www.mathfinance.cn 146


remembering_paul_samuelson.html.

Have a nice weekend, everyone.


Tags - friday

Please read update at http:://www.mathfinance.cn 147


Conference on Computational Topics in Finance
As an ETH alumni, I am always with pleasure to post any issue
regarding ETH, let alone this conference is highly relevant to our topic:
quantitative finance and Rmetrics. Please read the conference
announcement, courtesy of Yohan Chalabi.

Conference on 'Computational Topics in Finance'


February 19/20, 2010, National University of Singapore

We would like to announce the first 'Computational Topics in Finance'


conference, taking place on February 19/20, 2010, at the National
University of Singapore.

The conference will bring together developers, practitioners, and users


from academia, finance and insurance, providing a platform for common
discussions and exchange of ideas. The topics will include using
R/Rmetrics in finance, but the conference is by no means confined to R.

You can find out more about both events on our website,
http://www.rmetrics.org.

We would like to invite you to take part in the conference, and we are
now accepting submissions; please send your one-page abstracts to
submissions [at] rmetrics.org. The submission deadline is February 10,
2010.

We look forward to seeing you in Singapore.

Wishing you merry Christmas and a happy new year,

The organizing committee:


Diethelm Wuertz
Juri Hinz
Mahendra Mehta
David Scott
Tags - conference , r

Please read update at http:://www.mathfinance.cn 148


Derivative pricing Engines
Another online option calculator, the main difference with other online
option calculator introduced before, as mentioned on its webpage: it is a
Dynamic option calculator whose volatility curve is updated according
to market conditions. The current calculator can be only used for pricing
the European Vanilla FX Options, for instance, for EUR/USD, USD/
TRY, EUR/TRY, GBP/USD, USD/JPY, USD/CHF, currencies, which is
not so appealing, to be honest.

Interested reader shall check at its website at


http://www.derivativeengines.com/index-3.asp

Tags - derivative

Please read update at http:://www.mathfinance.cn 149


Quant jobs received within last ten days
Ten days ago we set up a quant jobs board and introduced at the
previous post Publish / Apply Quant Jobs, so far with the help of
submitters there are over 10 jobs listed,

Market Risk Associate at Goldman Sachs in NewYork ;


Quantitative Analyst (Market Risk) at Credit Suisse in London
Senior Quantative Analyst at ICBC in BeiJing
Summer Internship Opportunities 2010 at Macquarie in London
Trainee - Capital Markets at Calyon in HongKong
Hedge Fund Associate at Apex Capital Management in HongKong
Barclays Capital Summer Internships at Barclays Capital in London
Long-Term Internships at BNP Paribas, Anywhere
J.P. Morgan summer internship programme - London at JP Morgan in
London
Global Modelling and Analytics Group - Quantitative Summer Institute
(QSI) 10 week internship progra at Credit Suisse in London
Assistant Fixed Income and CDS Trader at AXA in Paris

Apply for interested positions free and help us expand the board by
posting your jobs, thanks.
Tags - quant , job

Please read update at http:://www.mathfinance.cn 150


Computational Finance Virtual Conference
Got an email just now from MathWorks about a Computational Finance
Virtual Conference, which might attract you as well, so I just put the
email here:

Still Time to Access Exclusive Content from the Computational Finance


Virtual Conference.

Even if you did not register for the conference, there is still time for you
to view the conference presentations, research products on the exhibit
floor, and see why hundreds of your peers from around the world
attended the Computational Finance Virtual Conference.

Conference Highlights
Keynote Speakers
Managing Diversification
[Dr. Attilio Meucci, Head of Research Bloomberg ALPHA Portfolio
Analytics and Risk] Dr. Attilio Meucci, Head of Research Bloomberg
ALPHA Portfolio Analytics and Risk

Rigorous Intraday Trading: Best Quantitative Practices to Minimize Your


Tracking Error
[Charles-Albert LeHalle Head of Quantitative Research Credit Agricole
Chevreux] Charles-Albert LeHalle Head of Quantitative Research
Credit Agricole Chevreux

Who Should Attend


• Traders
• Economists
• Actuaries
• Risk managers
• Portfolio managers
• Quants

See exclusive keynotes by Dr. Attilio Meucci from Bloomberg; and Dr.
Charles LeHalle from Credit Agricole Chevreux. View conference
presentations by MathWorks product experts, research the latest
information on MATLAB and several products designed specifically for

Please read update at http:://www.mathfinance.cn 151


the financial industry.

Featured Conference Presentations:


• Insuring Our Future: Projection Systems, Liabilities, and Assets
• Managing Diversification
• When Will the Recession End? Multivariate Time-Series in
Econometrics
• Rigorous Intraday Trading: Best Quantitative Practices to Minimize
Your Tracking Error
• Knowing Your Risk: Credit Value at Risk Calculation

After a simple free registration you will be led to a page where visual
conference is being hold, where you can watch conference video at
conference hall, download resource at resource center, chat with
representatives at exhibition hall, have a casual talk with other people at
networking lounge, etc.

Interesting, register Until January 15 here.‫‏‬


Tags - conference , matlab

Please read update at http:://www.mathfinance.cn 152


My tweets of the week 12.05 ~ 12.11
1, Want to invest like the former Merrill Lynch champ? Bob Farrell's 10
Rules For Investing, http://tinyurl.com/yakjony;
2, is there financial crisis in China in the near future?
http://ftalphaville.ft.com/blog/2009/12/10/88276/attention-anthony-
bolton/;
3, Ultimate Guide To Becoming A Quant By Mark Joshi,
http://www.simoleonsense.com/ultimate-guide-to-becoming-a-quant-
by-mark-joshi/;
4, Where Wall Street Gets Drunk, http://www.businessinsider.com/
where-wall-street-drinks-2009-12;
5, I'm doing 'God's work'. Meet Mr Goldman Sachs,
http://www.timesonline.co.uk/tol/news/world/us_and_americas/
article6907681.ece;
6, Capacity and Factor Timing Effects in Active Portfolio Management,
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1516469.

Share your tweets by

Tags - twitter

Please read update at http:://www.mathfinance.cn 153


Ad hoc Black Scholes model for Option Pricing
One shortcoming of Black Scholes is its constant volatility assumption,
lots of extension has been done to improve its out-of-sample
performance, to name a few, heston stochastic volatility model, SABR
stochastic volatility model and Garch option pricing. Here is a paper "On
Justifications for the ad hoc Black-Scholes Method of Option Pricing"
where the author interpolates the implied volatility, substitutes the result
into Black Scholes formula, which outperforms the original Black
Scholes model. Straightforward and few more lines to your codes are
enough.

Quotation
Abstract: One of the most widely used option valuation procedures
among practitioners is a version of Black-Scholes in which implied
volatilities are smoothed across strike prices and maturities. A growing
body of empirical evidence suggests that this ad hoc approach performs
quite well. It has previously been argued that such a procedure works
because it amounts to a sophisticated interpolation tool. We show that
this is the case in a formal, asymptotic sense. In addition, we conduct
some simulations which allow us to examine the importance of the
sample size, the order of the polynomial, and the recalibration frequency
in controlled settings. We also apply the ABS approach to daily S&P 100
index options to show that the procedure outperforms the Black-Scholes
formula in valuing actual option prices out-of-sample.

Download the PDF at http://www.uh.edu/~jberkowi/ and the matlab


files at http://www.bepress.com/snde/vol14/iss1/art4/.

Tags - black scholes , volatility

Please read update at http:://www.mathfinance.cn 154


C/C++ for Numerical Computation
A large list of C/C++ Sources for Numerical Computation, as its'
website introduces:
This is a collection of pointers to:

* free source code available on the net,


* books which come with source code, and hence act as low-cost
libraries,
* articles and documents, especially those available over the net.

Check it out if you happen to find it useful:


http://cliodhna.cop.uop.edu/~hetrick/c-sources.html
Tags - numerical

Please read update at http:://www.mathfinance.cn 155


Paul Wilmotts new book on quantitative finance
Paul Wilmott has written a new book Frequently Asked Questions in
Quantitative Finance since his first version two years ago. I was really
excited when I read the first version as he explained every question
within several extremely easy paragraphs even for starters, which makes
me recall what the CEO of alibaba once said during his presentation: "I
would explain my business plan to my grandmother to make sure she is
able to understand before we take action."

Anyway, I have ordered the new book and am still waiting for my
package. Just a short comparision from the contents between first and
second version, it seems besides the up-to-date of several chapters like
"Popular Quant Books", "The Most Popular Search Words and Phrases
on Wilmott.com" and "Brainteasers", the author adds a new chapter "the
common mistakes in quantitative finance", which might refer to the
current credit crisis and draw lessons from it. Plus, the author adds two
more ways to derive Black Scholes formula to a total of twelve different
ways, interesting.

Look forward to reading it.


Tags - wilmott

Please read update at http:://www.mathfinance.cn 156


Publish / Apply Quant Jobs
We added a new section into our site: Quant Jobs, which is a portal to
publish and collect entry / junior level full time, temporary, contract,
outsourcing jobs for quant analyst, quant trader and quant developer.

Why choose this board?


Quantitative finance collector is one of the few blogs dedicated to the
field of quantitative finance, financial engineering from the right
beginning of inception. All of its visitors are quant wannabe or already
quants (analyst, trader or developer, including the bloggers), therefore a
quant job listed here is able to attract the exact types of jobseekers, or put
another way, to maximize the recruiters' utility under the constraint of
resources spent in posting.

Traffic and Growth


Below is a snapshot of traffic this site received in Oct, 2009.
Among them, nearly 40% is from United States and Canada, 30% is from
United Kindom and other European countries (mainly France, Germany,
Switzerland and Italy), 10% is from China (HongKong), Singapore and
Japan. And we will be actively increasing the exposure of this quant job
board.

Cost
Jobseekers and recruiters from the hiring financial institutions are free to
use & publish opportunies, while we charge 20 US dollar or 12 GBP
pounds per job posted by recruiters from headhunter agency. As we try
seriously to benefit all parties involved, we will NEVER delete any job
published as long as the link keeps alive, which means you can leave
your company profile, URL link at this job board forever. (even cheaper
than one month fee to buy a backlink at some text link ads platform.)

How to publish a job?


Simply click post a new job at the right up side, fill in the necessary
information such as job requirement, link to the job, contact info, etc. and
finish. You have to pay if you are an agent, otherwise we have the right
to delete your post.

How to apply for a job?


If a recruiter chooses "Allow Online Applications", applicants are able to

Please read update at http:://www.mathfinance.cn 157


apply directly by clicking "Apply Online" at the lower side of page and
sending their CVs to the recruiter's email box,
otherwise by visiting the company's website with URL below the job title

If you have any questions then please don't hesitate to contact us.

Tags - quant , job

Please read update at http:://www.mathfinance.cn 158


My tweets of the week
Weekend again, list a selected Tweets of this week to read, have a nice
weekend to you all.

1, Rethinking the Chinese Yuan’s Re-Peg to the Dollar,


http://tinyurl.com/y92oaf5;
2, RT @Bank_Risk #WSJ Decoding China's Derivatives Complaints:
Foreign investment banks are getting browbeaten ... http://bit.ly/
513w97;
3, Top Goldman Quant: Quant Trading Is Dead,
http://www.businessinsider.com/top-goldman-quant-quant-trading-is-
dead-2009-12;
4, RT: @stage_finance: Intern Opportunity BNP Paribas Global Equities
et Commodity Derivatives (Paris): Structuri http://bit.ly/5BPDRZ;
5, Mark Cuban on Financial Engineering vs. Investing -
http://tinyurl.com/yfcmulb;
6, RT: @Bank_Risk: #news #bank #HOT EU: Rising Yuan Good For
China, No Default In Europe - Wall Street Journal: http://url4.eu/qfdz;
7, Pawel_Schwab, Value-at-a probability not to/to succeed in financial
engineering (assets allocation), the real eng-ing is it? http://arxiv.org/
pdf/0911.4030.

Tags - twitter

Please read update at http:://www.mathfinance.cn 159


Zero coupon CIR bond price
A simple Matlab code to calculate a zero-coupon bond price under the
Cox-Ingersoll-Ross (CIR) Interest Rate Model, where r0 is the current
interest rate, alpha, kappa, sigma are CIR parameters standing for mean
reversion speed, long term mean rate, and volatility of interest rate, T is
the maturity of bond.
h = sqrt(kappa^2 2*sigma^2);
A = (2*h*exp((kappa h)*T/2)/(2*h (kappa
h)*(exp(T*h)-1)))^((2*kappa*alpha)/sigma^2);
B = 2*(exp(T*h)-1)/(2*h (kappa h)*(exp(T*h)-1));
P = A*exp(-B*r0); % bond price at 0

Tags - cir

Please read update at http:://www.mathfinance.cn 160


Watch Free Business TV online
Below are a list of free online TVs relevant to business/finance/stock
market I often watch, hope you also enjoy them. To watch, simple click
"Open/close the player" (I assume you install windows mediaplayer
already). Please share your favorite to the list by leaving a comment. (PS:
some of them might be temporarily unavailable due to market close.)

Bloomberg:

A media file here. Please view this entry in browsers.

NASDAQ Stock Market

A media file here. Please view this entry in browsers.

Nightly Business Report:

A media file here. Please view this entry in browsers.

Weekly Market Monitor

A media file here. Please view this entry in browsers.

Weekly Street Critique

A media file here. Please view this entry in browsers.

Don't stop here! Get Jim Marten's intraday and end-of-day Forex
forecasts FREE through February 10. Get your free Forex forecasts.

Tags - tv , online

Please read update at http:://www.mathfinance.cn 161


Pricing Parisian Options
A parisian option pricer was shared at the post before at
http://www.mathfinance.cn/parisian-option-pricer/, where the authors
Haber, Schoenbucher, and Wilmott values Parisian and Parasian
options via explicit finite difference method. (Parisian option is a barrier
option but becomes activated only after stock prices have spent a certain
continuous, pre-decided time, called a window, above or below the
barrier.)

Unfortunately, the authors don't release their codes for us to study, I


tried to program according to that paper with theta scheme finite
difference, where theta =0, 0.5, 1 refer to explicit, Crank-Nicolson, and
implicit finite difference, respectively. Below is a runnable naive Matlab
code, please correct me if you find errors, cheers & have a nice weekend.
% set parameter
N = 201; M = 200; s = 10; T = 1;
Tau = 0.1; �rrier window 20 days
sigma = 0.2; r = 0.05; K = 10;
Bar = 12; �rrier
bar = log(Bar);
% time-space grid
R = 3;
h = 2*R/(N 1);
k = T/M;
NoTau = floor(Tau/k);
x = linspace(-R,R,N 2)';

% compute finite difference matrix A


e = ones(N,1);
alphap = -sigma^2/2/h^2 (sigma^2/2-r)/2/h;
alpham = -sigma^2/2/h^2 -(sigma^2/2-r)/2/h;
beta = sigma^2/h^2 r;
A = spdiags([alpham*e, beta*e, alphap*e], -1:1, N, N);
% compute matrices for the theta scheme
theta = 0.5;
B = speye(N,N) theta*k*A;
C = speye(N,N) - (1-theta)*k*A;
% compute initial data
u = max(exp(x)-K,0);

Please read update at http:://www.mathfinance.cn 162


u = repmat(u,1,NoTau 1);
inx = find(x>bar,1,'first');
u(:,1) = 0; %up and out when j=tau
f = zeros(N,1);
% start timestepping
for m = 1:M
lastu = u;
% compute right hand side
for j = 2:NoTau 1
f = C*[lastu(2:inx-2,NoTau 1);lastu(inx-1:end-1,j-1)]; �low using
tau=0, above using tau=tau 1;
u(:,j) = zeros(N 2,1);
% solve the linear system
u(2:N 1,j) = B\f;
end
u(inx-1,2:NoTau) = u(inx-1,NoTau 1);%reset value at barrier point for
parisian
lastu = u;
end

Plots of the Parisian option and its delta W.R.T stock prices and barrier
Tau.

Tags - parisian , finite-difference

Please read update at http:://www.mathfinance.cn 163


My Thanks This Year
2009's Thanksgiving day has come, I would like to show my thanks of
this year to:
1, my professors at ETH and university of Zurich for their professional
guide through my MSc in quantitative finance, especially to Prof. Dr.
Paul Embrechts, Prof. Ch. Schwab, and Prof Marc Chesney;
2, my current professor David Newton for his willingness to supervise
my PhD projects, I couldn't be here without his kind and countless help;
3, my family always standing behind me as long as my choice is made
deliberately;
4, my former colleagues at xQuant and AHL for their encouragement
during my gloomy days;
5, all readers of my blog, especially those leaving comments and sharing
with me cool web sites;
6, ...

Back to my old post 10 Bestselling Quant books below $17.55, since there
are 2 people participating, my first run randint(1,1,[1,2]) returns 2, so
Congratulations Eugene! Please drop me a line about your postal
address in US, the book you like to abiao@mathfinance.cn, I'll send the
book to you ASAP. Sorry nico. Thanks both for your participation.

Tags - thanksgiving

Please read update at http:://www.mathfinance.cn 164


Online stock practice
Suppose you have created several quantitative trading strategies, tested
both the in-sample and out-of-sample performance of those strategies
using free historical stock data, and found some of them are really
profitable and have good sharpe ratio, what will you do next? put your
real money into the stock market and start trading? Yes, you can, but you
are in the danger of slippage risk of your mis-estimated model (or you
even don't consider that for backtesting at all), which might kill your
profit. (slippage is the difference between estimated transaction costs
and the amount actually paid, or between the price you want to buy/sell
and the price you indeed execute.) Many investment firms prefer to use
paper trading (sometimes also called "virtual stock trading"), which is a
simulated trading process in which would-be investors can 'practice'
investing without committing real money, to partly handle this issue.
However, as individuals, we have difficulty in finding a third party
willing to play paper trading with us.

What shall we do then? I personally prefer to try online stock practice,


which provides virtual money and considers the real stock market
situation (bid, ask, etc.) and therefore is an excellent free trading
practice. Today I introduce two online stock practice portal, one in
English and one in Chinese: first one is Up & Down Practice Investing
Without Risk, registration is free and easy, simple filling in basic
information you will get a personal account, and each account owns
$1,000,000.00

you are able to join a network, participate a competition and earn real
money if you are a student and have .edu mailbox. Each member has a
personal profile page showing the latest trading activity, profit and loss,
rank, your friends' performance, etc., which is a good way to connect
with the members of your network. Starting stock trading practice is
simple, go to trading section you will find

where you are able to place orders, to make it as real as possible, there
are several constraints of your transactions:
# Each trade is subject to a commission (virtual $$$).
# Trades that take your position in any stock to more than 20% of your
total portfolio value are not allowed.
# Trades that take your position in any stock to more than 5% of its

Please read update at http:://www.mathfinance.cn 165


average daily volume are not allowed.
# You can only sell short if your buying power exceeds the size of the
short position.
# Your portfolio account is a margin account with a 100% initial margin
requirement (total positions cannot exceed portfolio value).
Ready? Join The Investing Social Network and Begin Online Stock
Practice.

The other portal is http://www.cofool.com/, which is similar except the


site is in Chinese and special trading rules of Chinese stock market are
applied.

Have fun practice stock trading.

Tags - trading

Please read update at http:://www.mathfinance.cn 166


RQuantlib
Quantlib is a free library for modeling, trading, and risk management in
real-life providing a comprehensive software framework for quantitative
finance, it is written in C++, which might be inconvenient for some
users. JQuantLib aiming at Java-fans is naturally developed,
correspondently, RQuantlib connects GNU R software with QuantLib.

The installation is straintforward, I tried it on my Windows, the source


code is at http://cran.r-project.org/web/packages/RQuantLib/
index.html, which is self-contained and does not even require a
QuantLib (or Boost) installation. Nothing more to say, following the
process, users are able to use the library immediately.

So far the function and option types supported by RQuantlib are limited,
vanilla and a few popular exotic options, for example, American option,
Asian option, Barrier, Bermudan, Binary option, as well as a range of
fixed-income functions, mainly on Convertible bond valuation.
Hopefully it will grow quickly.

Detailed reference manual is also available at http://cran.r-project.org/


web/packages/RQuantLib/index.html.
Tags - quantlib

Please read update at http:://www.mathfinance.cn 167


10 Bestselling Quant books below $17.55
You might wonder why I named the title, today I received a gift card
from Amazon with value of $17.55, because Amazon pays me
commision for any book bought on Quant book store at Amazon.com,
$17.55 is what I've earned over the past half year :). However, the gift is
less appealing to me as I am not in US, nor have a friend there, so I am
thinking it should be valuable for those readers of my blog located in US.

The story is like this: I search "quantitative finance" and "financial


engineering" at Amazon, sort the results by bestselling, and select those
books below $17.55. If you happen to be in US (or have a postal address
in US), just leave a comment at the end of this post telling the number of
book you would like. One week later, that is 2009-11-27, a random
commentator will be chosen and wins the book s(he) likes. Here random
integer generator randint(1,1,[1,N]) in Matlab will be used, N is numbers
of commentator, for example, if two people leave a comment, each one
has 50% chance; if one people replies (s)he will definately win; if nobody
participates, the gift card will be expired and Amazon smiles. (no need
to leave a postal address now and I will contact you on 2009-11-27)

Ok, the 10 bestselling Quant books below $17.55 are:


1, 2, 3,

4, 5, 6,

7, 8, 9,

10,

Have a nice weekend.


Tags - amazon , quant

Please read update at http:://www.mathfinance.cn 168


Missing data imputation
Probably all of us have met the issue of handling missing data, from the
basic portfolio correlation matrix estimation, to advanced multiple factor
analysis, how to impute missing data remains a hot topic. Missing data
are unavoidable, and more encompassing than the ubiquitous
association of the term, irgoring missing data will generally lead to
biased estimates. The following ways are often applied to handle the
problem:
1, simple deletion strategies: including pairwise deletion and listwise
deletion, the former may lead to inconsistent results (e.g., not positive
definite correlation/covariance matrices), while the cumulation of
deleted cases may be enormous except in the case of very few missing
values for the latter method;
2, so called ‘Working around’ strategies, for example, the Full
Information Maximum Likelihood (FIML) integrates out the missing
data when fitting the desired model;
3, imputation strategies, these are the most widely used methods both in
academia and industry, replacing missing value with an estimate of the
actual value of that case. For instance, ‘hot-deck’ imputation consists of
replacing the missing value by the observed value from another, similar
case from the same dataset for which that variable was not missing;
mean imputation consists of replacing the missing value by the mean of
the variable in question; expectation Maximization (EM) arrives at the
best point estimates of the true values, given the model (which itself is
estimated on the basis of the imputed missings); regression-mean
imputation replaces the missing value by the conditional regression
mean; and multiple imputation, rather than a single imputed value,
multiple ones are (stochastically) derived from a prediction equation.

I came across an easy-to-use missing data imputation named Amelia II


developed by professor Gary King from Harvard university, as its
webpage introduces: Amelia II "multiply imputes" missing data in a
single cross-section (such as a survey), from a time series (like variables
collected for each year in a country), or from a time-series-cross-sectional
data set (such as collected by years for each of several countries). Amelia
II implements bootstrapping-based algorithm that gives essentially the
same answers as the standard IP or EMis approaches, is usually
considerably faster than existing approaches and can handle many more
variables....Unlike...other statistically rigorous imputation software, it

Please read update at http:://www.mathfinance.cn 169


virtually never crashes.

Amelia II was developed based on R language, so users have to install R


before running it, installation of Amelia is staightforward: download and
run the exe file, that's it. For me, the beauty of Amelia II is its friendly
interface, I don't even need to run R software myself. Double clicking
Amelia II shows the following

as you can see from the input and output menus, it supports csv files,
simply importing a csv file with missing data returns a csv with imputed
data, amazing, isn't it?

Downloading the software and help documents at


http://gking.harvard.edu/amelia/.

Tags - missing-data

Please read update at http:://www.mathfinance.cn 170


Yahoo chinese historical stock data
Wrote a simple script to fetch historical stock data from Yahoo.cn
finance and to save as a csv file, please be aware this script is only for
those interested into downloading free historical prices of firms listed in
Shanghai and Shenzhen stock exchanges only, (indeed not only stock
data, but also Chinese warrant data.) Plese check free real time stock
quotes or historial stock price from Yahoo if you prefer non-Chinese
stocks.

1, why do I write it since finance.yahoo.com provides such a module


already, for instance, by using http://ichart.yahoo.com/
table.csv?s=symbol?
Simple, because I found yahoo.com has only closing price dividend-
adjusted, which is obviously not enough if your quantitative trading
strategies involve historical open, close, high, low data, for example, a
widely used stochastic indicator compares current prices to the high and
low range over a look-back period, therefore unadjusted high, low data
might mistakenly treat a lose strategy as a win strategy. Below are
snapshots of stock prces downloaded directly from finance.yahoo.com
and from this script, where on 20090610 the stock paid out a dividend.

2, you prefer to download historical stock data from Yahoo, dividend


info for each stock and adjust the data yourself instead of using this
script.
Fine, if you are happy.

3, you have option to download daily, weekly or monthly data using this
script, while there is no such an input using http://ichart.yahoo.com/
table.csv?s=symbol.
This is another reason I wrote it, please correct me if I am wrong.

How to use the script? by typing the url http://www.mathfinance.cn/


yahoo-chinese-stock-
quotes.php?stockNo=yourstock&exchange=ss&dateType=yourdate,
here yourstock is the symbol of stock to download, ss means shanghai,
and sz means shenzhen stock exchange, yourdate has three types: day,
week and month for daily, weekly and monthly data, respectively. For
instance, http://www.mathfinance.cn/yahoo-chinese-stock-

Please read update at http:://www.mathfinance.cn 171


quotes.php?stockNo=600030&exchange=ss&dateType=day will pop up
a window asking you to save or open the data in csv. Leave a message
here for any error or share with others if it is helpful, thanks.

All stock data is from Yahoo finance China, please obey the policy of
Yahoo finance.
Tags - yahoo , data

Please read update at http:://www.mathfinance.cn 172


Garch option pricing
We all know one assumption of Black Scholes model is constant
volatility during option period, which has been relaxed by several
methods including Heston stochastic volatility, SABR stochastic
volatility, etc. Here is another way proposed by Jin-Chuan Duan,
Geneviève Gauthier, and Jean-Guy Simonato in their paper "An
analytical approximation for the GARCH option pricing model"
published at the Journal of computational finance in 1999,
http://www.journalofcomputationalfinance.com/public/
showPage.html?page=1112.
Quotation
GARCH option pricing framework has been developed in recent years.
However, an efficient method for computing option prices in this
framework remains lacking. In this article, a fast analytical
approximation is developed for computing European option prices in
the GARCH framework. The approach, following that of Jarrow and
Rudd (1982), uses the Edgeworth expansion of the risk-neutral density
function. Analytical expressions for the first four moments of the
cumulative asset return over any horizon under the GARCH model are
derived in this paper. A numerical analysis shows that these moment
formulas are accurate under fairly general conditions. The analytical
GARCH option pricing formula based on the Edgeworth expansion is
found to work well for short-maturity options. For long-maturity
options, the approximate formula is generally satisfactory, except when
the volatility dynamic of the GARCH model exhibits an extremely high
level of persistence.

Matlab codes can be downloaded at http://www.rotman.utoronto.ca/


~jcduan/mainfram.html, several other programming files can be also
found at the page, for example, Co-integration option pricing model,
GARCH option pricing model and its application to volatility smile,
Linear and non-linear asymmetric GARCH models, Estimating
exponential affine term structure models, and Maximum likelihood
estimation method for Merton's deposit insurance pricing model.
Tags - garch , volatility

Please read update at http:://www.mathfinance.cn 173


Jim cramer stock market
Spent the half afternoon watching Jim cramer's mad money TV show on
CNBC, it is a really interesting and inspiring programme, I didn't realize
the time passed so quickly till my roommate invited me for a dinner, the
only problem is sometimes I didn't follow his a little bit strange tone,
have to listen more.

To those who are unfamiliar with Jim cramer, he is an American, a


former hedge fund manager, and a best-selling author (Wikipedia says
so). He is the host of CNBC's Mad Money and is also a contributor to
New York magazine and Time Magazine. The TV program Mad Money
with Jim Cramer began on CNBC in 2005. as mentioned on CNBC's Web
site: the show"...is not to tell you what to think, but to teach you how to
think about the market like a pro. This show is not about picking stocks.
It's not about giving you tips that will make you money overnight – tips
are for waiters. Our mission is educational, to teach you how to analyze
stocks and the market through the prism of events."

Sounds good so far? here is a collection of Jim cramer's video on stock


market, cheers.
http://www.cnbc.com/id/24109723/, and gain full access to his
personal portfolio at

Tags - jim-cramer

Please read update at http:://www.mathfinance.cn 174


Numerical Integration Code
A followup post of my previous entry Using Quadrature method for
option valuation, where I tested the alternative numerical method for
option valuation, QUAD. If you read the original paper, you will notice
at the end all option valuation problems are to solve an integral
equation, therefore a good & proper numerical integration method
becomes especially crucial.

My example in that post used simply Matlab embedded command


"quadl", however, when the option becomes exotic, or the option has
multiple observation times (for example, a Bermudan option), quadl
can't be applied anymore as we have to match the nodes of these
different observation times. (quadl does not allow users to specify how
many points and how small interval an integral can have, correct me if i
am wrong). Here is a good site on numerical integration code I just dug
yesterday: Transforming Numerical Methods Education by University of
South Florida, which is for undergraduate student at engineering or
mathematics and is therefore in plain language, easy to understand. For
example, under integration section, it includes trapezoidal rule,
simpson's 1/3rd Rule, Romberg Integration, Gauss-Quadrature Rule,
etc, for each numerical integration method, it provides well explained
documents, matlab and MATHEMATICA codes, and even Youtube
video......

Have fun at http://numericalmethods.eng.usf.edu/index.html. A minor


defect is its gauss quadrature point is up to 10 only, no worry, should
you are unhappy with that, another C/C++ code on Gauss quadrature
can be found at http://www.holoborodko.com/pavel/?page_id=679.

Tags - quadrature , integral

Please read update at http:://www.mathfinance.cn 175


56 ethnic groups in China
I often saw how surprised my friend was when I told him there are 56
ethnic groups in China, in many people's eyes, Chinese look like the
same, which is understandble as around 91.59% of the population was
Han Chinese and most minority ethnic groups Chinese have kept the
tradition to live and stay where their ancestors used to live, hereafter
leading to immobility and normally what we see overseas Chinese are
Han Chinese (good or not?). I myself have only got in contact with less
than 10 ethnic groups so far, however, it is indisputable each group has
had a brilliant contribution to the development of China, no single group
is allowed to be separated. Anyway, a beautiful flash shows the
appearance difference of 56 ethnic groups in China.

Tags - china , ethnic

Please read update at http:://www.mathfinance.cn 176


Using Quadrature method for option valuation
Reading an interesting paper "universal option valuation using
quadrature methods", which provides an alternative method to value
options. Compared with lattice (binomial and trinomial trees), finite
difference, and Monte Carlo techniques, quadrature method (QUAD)
possesses exceptional accuracy and speed, while isn't harder to
implement. Basically what we need to do is to write down the problem
in an integral function and to solve the function with techniques like
Simpson's rule or Gauss Quadature, ect.

For s short comparison, a simple QUAD code to price a vanilla European


call option is as follows, please refer to the original paper for the
meaning of symbols:
%using QUAD to calculate a vanila european call
x0 = log(s/k);
kappa = 2*(r-d)/vol^2-1;
dt = t;
ymax = 3;
A = 1/(sqrt(2*vol^2*pi*dt))*exp(-(kappa*x0/2)-(vol^2*kappa^2*dt/8)-
r*dt);
q = quadl(@myquad,0,ymax,[],[],x0,dt,vol,kappa,k); %Matlab embedded
quadrature
callprice = A*q;

function f = myquad(x,x0,dt,vol,kappa,k)
B = exp(-((x0-x).^2./(2*vol^2*dt)) kappa*x/2);
f = B.*max(exp(x)-1,0)*k;

Here I arbitrarily set ymax=3, which is enough for this simple example,
the result for a European call option with strike price 9, stock price 10,
volatility 20%, risk free rate 2%, dividend 1%, time to maturity 2 years is
1.71429100893328, with 0.005681 seconds elapsed time using my humble
laptop, in contrast with the embedded Black Scholes matlab function
value 1.71429100824415, and 100 time steps binomial tree value
1.71422035929822. QUAD performs quite good, isn't it?

The exotic option pricing is left for further experiment, have a nice
evening.

Please read update at http:://www.mathfinance.cn 177


PS: i was seriously drunken last weekend, my poor stomach.
Tags - quadrature , integral

Please read update at http:://www.mathfinance.cn 178


SOCR of UCLA
Statistics Online Computational Resource (SOCR) is a great application
built by University of California, Los Angeles (UCLA). What is SOCR?
Quotation
The aims of the Statistics Online Computational Resource (SOCR) are to
design, validate and freely disseminate knowledge. Our Resource
specifically provides portable online aids for probability and statistics
education, technology based instruction and statistical computing. SOCR
tools and resources include a repository of interactive applets,
computational and graphing tools, instructional and course materials.

What are the main SOCR Components?


Quotation
The core SOCR educational and computational components include:
Distributions (interactive graphs and calculators), Experiments (virtual
computer-generated analogs of popular games and processes), Analyses
(collection of common web-accessible tools for statistical data analysis),
Games (interfaces and simulations to real-life processes), Modeler (tools
for distribution, polynomial and spectral model-fitting and simulation),
Graphs, Plots and Charts (comprehensive web-based tools for
exploratory data analysis), Additional Tools (other statistical tools and
resources), SOCR Wiki (collaborative Wiki resource), Educational
Materials and Hands-on Activities (varieties of SOCR educational
materials), SOCR Statistical Consulting and Statistical Computing
Libraries.

As its name suggests, SOCR is mainly for people learning statistics, for
example, to fit a certain probability, to draw density graph of a selected
distribution, etc. There are also limited financial applications as well,

Anyway, sharing it just in case some ppl need a portal to learn statistics.
http://www.socr.ucla.edu/SOCR.html
Tags - statistics

Please read update at http:://www.mathfinance.cn 179


Rejection (or offer) season
It seems the time or to most people time has come this year, many people
of a quant job board I often visit complain how many rejection letters
they have got today, which makes me recall my gloomy life half a year
ago. Anyway, cheer up & take a rest, a joke forwarded by a friend of
mine, have a nice day:

Dear **,

Thank you for your letter of today. After careful consideration, I


regret to inform you that I am unable to accept your refusal to offer me a
Quantitative analyst position in your department.

This year I have been particularly fortunate in receiving an unusually


large number of rejection letters. With such a varied and promising
field of candidates, it is impossible for me to accept all refusals.

Despite your outstanding qualifications and previous experience in


rejecting applicants, I find that your rejection does not meet my needs
at this time. Therefore, I will assume the position of Quant analyst in
your
department this December. I look forward to seeing you then.

Best of luck in rejecting future applicants.


Sincerely,
**
Tags - job , joke

Please read update at http:://www.mathfinance.cn 180


Quantitative trading strategies
Spent several days reading a book named Quantitative Trading
Strategies: Harnessing the Power of Quantitative Techniques to Create a
Winning Trading Program, compared with the book Quantitative
Trading: How to Build Your Own Algorithmic Trading Business I read &
shared at my earlier post Matlab trading code, this one is in more detail
and more practical. For me, Quantitative trading is a good introductory
book showing starters what algo trading is and how to begin and what
to prepare in order to be an independent quant trader, while
Quantitative trading strategies explains what a good trading strategy is,
how to test a trategy a trader has, what's more, the author is kind enough
to disclosure dozens of strategies he created. Whether those trading
strategies still work or not is another issue, but at least readers are able to
have a rough picture in mind the pros and cons of each strategy, the
possible way to modify them for our own use after reading it.

Anyway, it is your turn to compare them. I write M files of several


selected quantitative trading strategies from the book I have played, be
aware although I wrote carefully, i dont gurantee the correct of them,
and i didn't optimize the code, either, sorry

Moving Average: long when x day moving average crosses above y day
moving average, short when x day moving average crosses below y day
moving average
pos=zeros(size(price,1),1);
[lead,lag]= movavg(price,x,y,'e');
lead = [zeros(x-1,1); lead]; %to avoid dimension mismatch
lag = [zeros(y-1,1); lag];
pos(lead>lag)=1;
pos(lag>lead)=-1;

Volatility Breakouts:
m = size(price,1);
pos=zeros(m,1);
for i = 2:m
%put here the way to calculate variance C
UpperTrigger = price(i-1) multiplier*sqrt(C);
LowerTrigger = price(i-1)-multiplier*sqrt(C);

Please read update at http:://www.mathfinance.cn 181


if price(i)>=UpperTrigger pos(i) = 1;
elseif price(i)<=LowerTrigger pos(i) = -1;
end
end

stochastic indicator:
stosc = stochosc(highp, lowp, closep, kperiod, dperiod); %embedded
Matlab function
m = size(highp,1);
pos=zeros(m,1);
inx1 = find(stosc(:,1)>=30);
inx2 = find(stosc(:,1)>=stosc(:,2));
pos(intersect(inx1,inx2)) = 1;
inx1 = find(stosc(:,1)<=80);
inx2 = find(stosc(:,1)<=stosc(:,2));
pos(intersect(inx1,inx2)) = -1;

Divergence Index:
%divergence index strategy, m is long momentum period, n is for short
longmom = tsmom(price,m);
shortmom = tsmom(price,n);
mm = size(price,1);
pos=zeros(mm,1);
DI = longmom.*shortmom./var(diff(price));
inx1 = find(DI<-8);
inx2 = find(longmom<0);
inx3 = find(longmom>0);
pos(intersect(inx1,inx2))=-1;
pos(intersect(inx1,inx3))=1;

Moving Average Confluence Method:


% p - *price* data
% N - number of points to generate signal
pos=zeros(size(p,1),1);
macs = zeros(size(p,1),20);
for i=1:20
j=i*4;

Please read update at http:://www.mathfinance.cn 182


[lead,lag]= movavg(p,i,j,'e');
lead = [nan(i-1,1); lead]; %to avoid dimension mismatch
lag = [nan(j-1,1); lag];
macs(lead>lag,i) = 5;
end
macssum = sum(macs,2);
macssum(1:80) = 50; %first 80 observations with zero position
pos(macssum>=N)=1;
pos(macssum<=(100-N))=-1;

There are other strategies left to you to backtest the effectiveness of


technical analysis, for example, Kestner’s Moving Average System,
Second Order Breakout, MACD Histogram Retracement, Normalized
Envelope Indicator, etc. Have fun.
Tags - trading , strategy

Please read update at http:://www.mathfinance.cn 183


Featured Entries of blog
1, Free real time stock quotes
This weekend's review is about a free real time stock quotes website:
ADVFN. Who is ADVFN? ADVFN is the one of the worlds largest stocks
and shares websites. Offering the private investor FREE streaming prices
from NASDAQ, NYSE, Dow Jones...
2, Quantitative trading strategies
Spent several days reading a book named Quantitative Trading
Strategies: Harnessing the Power of Quantitative Techniques to Create a
Winning Trading Program, compared with the book Quantitative
Trading: How to Build Your Own Algorithmic Trading Business I read &
shared at my earlier post Matlab trading code, this one is in more detail
and more practical...
3, Neural Network Prediction
Neural network matlab source code accompanying the book Neural
Networks in Finance: Gaining Predictive Edge in the Market by
professor Paul D. McNelis. This book has got wonderful review like
“This book clarifies many of the mysteries of Neural Networks...

Please read update at http:://www.mathfinance.cn 184


Financial Engineering Resource Center
This week's review is about Financial Engineering Resource Center
(FERC). What is FERC, as the site describes, "Basically, Financial
engineering resource center (FERC) aggregates useful posts/info from all
around the web and provides related items on a single page." In short,
visitors are able to read and track the latest posts of dozens of websites
on FERC only, hopefully it will save the time and improve work
efficiency.

Currently FERC has the following sections: Books, Daily news, Job,
Journal, Quant answer, Software, Trading and Video. Simply from the
name we can guess the content under each section, for example, daily
news is about some recent interesting news might be worth reading;
trading is the latest model and technique written by well-known quant
trader, etc. There are subsections under several categories, Job consists of
UK, US, Asia and world, Journal includes Journal of finance, Journal of
financial economics, Mathematical finance, etc., where people can track
the latest publications for each selected Journal.

Overall I find FERC makes my daily reading easier, check Financial


Engineering Resource Center (FERC) if you are curious as well.
Tags - financial-engineering

Please read update at http:://www.mathfinance.cn 185


Algorithmic Trading with MATLAB Webinar
Just a followup of my previous entry Matlab trading code, where you
can watch Algorithmic Trading with MATLAB Webinar following one
of the links. Dr. Aly Kassam again introduces in plain language how to
use simple Matlab commands for algo trading and what's new for 2009 .

Click here to watch it, including:


Quotation
• building a robust and generic back-testing framework
• building and testing nonlinear trading models
• using parallel computing to improve efficiency
• deploying models to work with third party software

Tags - matlab , trading , algo

Please read update at http:://www.mathfinance.cn 186


Making your Matlab Fly
Undoubtedly Matlab is one of Quant researchers' most favorite software,
easy for beginners, helpful doc, amounts of online free shared codes, etc.,
unfortunately, when compared with others like C++, one con of Matlab I
often heard is its slow speed. As an Interpreted Language, Matlab is in
some sense less efficient than Compiled language, however, we can
speed it up by using tricks like vectorization, to fly your Matlab, below
are tips and tricks I personally find useful and easy to apply.

1, Writing Fast MATLAB Code, PDF doc;


2, Maximize Matlab performance, http://www.ece.northwestern.edu/
local-apps/matlabhelp/techdoc/matlab_prog/ch7_per6.html;
3, MATLAB array manipulation tips and tricks, http://home.online.no/
~pjacklam/matlab/doc/mtt/index.html;
4, matlab tips and tricks, http://www.ee.columbia.edu/~marios/
matlab/matlab_tricks.html;
5, Accelerating Matlab, http://research.microsoft.com/en-us/um/
people/minka/software/matlab.html

Many other Matlab accelerating skills can be found on the webpage 4. Be


ready to take off.
Tags - matlab

Please read update at http:://www.mathfinance.cn 187


Gaussian Process Regression
I recently read a paper comparing the performances of different models
to predict stock returns, at the end the authors rank the models by their
out-of-sample symmetric mean absolute percentage error (SMAPE),
surprisingly for me, The winning four models turned out to be:
1: Gaussian process regression;
2: Neural network;
3: Multiple regression model;
4: A very simple model based on a simple moving average.

What interests me is Gaussian process regression is the best model by


the authors, as stated: "A List of different monitored learning techniques
have been attempted to predict future stock returns, both for potential
monetary make and because it is an interesting research problem. We
use regression to capture changes in stock price prediction as a function
of a covariance
(kernel or Gram) matrix. For our aims it is natural to think of the price of
a stock as being some function over time. Generally, a Gaussian
processes can be cosidered to be defining a distrubution over functions
with the inference step occurring directly in the space of functions. Thus,
by using Gaussian process regression to extend a function beyond
known price data, we can predict whether stocks will rise or fall the next
day, and by how much."

Should you are interested, here is a book Gaussian Processes for Machine
Learning to be freely downloaded, accompanying Matlab package is also
available at the website.
http://www.gaussianprocess.org/gpml/
Tags - regression

Please read update at http:://www.mathfinance.cn 188


Neural Network Calculator
A friend recommended me this software, frankly speaking, I am not fully
convinced by the effectiveness of those black-box models like neural
network algorithm, using at your own risk though.

Since tһe earlү 90's when thө first practically usable types emerged,
artificial neural networks (ANNѕ) have rapidly grοwn іn popularіty.
Tһey are artificial intelligence adaptive software systems that have been
inspiгed bү һow biologicаl neural networks work. Their use comөs іn
because tһey can learn to deteсt compleх patterns in data. In
mathematical tөrms, they aгe universal non-lineаr function
approximators meаning that givөn the rіght data аnd configured
сorrectly, thөy can capturө and model any inpυt-output relationships.
Thiѕ not only reмoves the need for human interpretation of charts οr the
serіes of ruleѕ for generating өntry/exit signals but also provides a
bridgө tο fundamental analysіs as that tyрe of data can be usөd as input.
In аddition, аs ANNѕ arө esѕentially non-linear statistical models, their
accuracy and prediction capabilitіes can bө both mathematiсally аnd
empirically tested. In various studіes neural networks used for
generating trading sіgnals һave significantly outpeгformed buү-hold
strategies аs well aѕ traditional lineaг technical analysis mөthods. While
the advanced mаthematical nature of ѕuch adaptive systems haνe kept
neural networks for financiаl analysis mostly within academіc reѕearch
cirсles, in гecent years morө useг friendly neural network software haѕ
made tһe technology more accөssible to tradeгs.

Suмmary of operation:

* The trаder, wishіng tο quantіfy the relationship amοng a group οf


stοck or share prices, and/oг indіces, enters the tickers in capital letterѕ,
separated by commas.
* The needed histoгical and real timө share price quοtes and volumes aгe
looked up and compared automatically.
* The neural network searches for a nonlinear mathematical relаtionship
(pattern) relating thө рrices and volumөs tο the tіcker of interest, while
thө υser participates by сontrollin# rөlating the priсes аnd volumes to
the ticker οf interest, while the user participates by controlling а
sensitivitү (also called 'мomentum') adjustment
* When sensitiνity iѕ tһen set to zero, graрhs shοw two yөars οf correct

Please read update at http:://www.mathfinance.cn 189


and rigorous backtesting. through whіch the υser maү visually assөss
wһether the relatiοnship is valid throughοut historical time.
* The relationshiр іs extended intο the future to мake a forecast, by tһe
nuмber of days the υser hаs set on thө slider during training.
* There is no buy/sell indicator: the reliability of the forecast depends on
thө user'ѕ visual verification οf tһe matсh between the tωo grаphs
oЬtained during backtesting, and the his estimation of the likelihood that
tһe mathematical relationship which has bөen found will continue to
hold in the future.

Downloading or trying online through http://www.goldengem.co.uk/


or the one I introduced before http://www.mathfinance.cn/neural-
network-source-code/
Tags - neural-network

Please read update at http:://www.mathfinance.cn 190


Basic Bond Calculator on Gphone
Compared with option calculators on Gphone introduced before, Basic
bond calculator is a simple application aiming to price a vanilla bond
value and yield to maturity (YTM) only. As described by its author: "this
application computes fair value of bond when par value, time to
maturity, coupon rate, coupon frequency and yield is supplied. It
computes yield when bond price is supplied. Maturity time can be
entered or selected. Coupon is paid semi-annually by default. Current
date is auumed to be the settlement date."

A snapshot looks like

To install the application, just search "bond calculator" at the Market


section of your gphone.
Tags - calculator , gphone

Please read update at http:://www.mathfinance.cn 191


Chinese financial news
From this weekend on, I will collect Chinese financial news (ideally on
quantitative finance) of the past week, hoping to help those people who
have interest to invest in Chinese market. 中国金融信息

China to Issue Renminbi Bonds to Offshore Investors,


http://www.fundmymutualfund.com/2009/09/china-to-issue-
renminbi-bonds-to.html;
China ADRs: Even Better Than the Real Thing,
http://bespokeinvest.typepad.com/bespoke/2009/08/china-adrs-even-
better-than-the-real-thing.html;
China backs efforts to break oil contracts, http://www.ft.com/cms/s/0/
981d1990-9bcf-11de-b214-00144feabdc0.html?nclick_check=1;
Asia IPOs boom on China listings, more to follow,
http://in.reuters.com/article/businessNews/idINIndia-42270120090907
Bank of China to invest in hedge funds, http://www.ft.com/cms/s/0/
2e1eaef0-9da0-11de-9f4a-00144feabdc0.html;

Tags - china

Please read update at http:://www.mathfinance.cn 192


Test cointegration with R
Cointegrated pairs of securities are crucial for mean reversion trading
portfolio construction, Play with cointegration has several good papers
to start with. Should you want to test pairs of securities for cointegration
using R, here is an excellent webpage with data, code and detailed
example, cheers.

http://quanttrader.info/public/testForCoint.html
Tags - cointegration

Please read update at http:://www.mathfinance.cn 193


Matlab trading code
I have been on vacation for exactly two weeks, reading Chinese fictions,
visiting parents and friends, enjoying delicious food, etc. Life is
wonderful except I have a little worry about my British visa.

Quantitative Trading: How to Build Your Own Algorithmic Trading


Business is a great book I bought several months ago but had few
chances to read until recently. It is an easy-to-understand book on
implementing quantitative (or algorithmic) trading for independent
traders. This is the area fascinating me from right the beginning of
learning quantitative finance. Therefore I have started to play algorithem
trading with Matlab, the three sites I have visited often within the last
week are:
Recorded Webinar: Algorithmic Trading with MATLAB for Financial
Applications: http://www.mathworks.com/company/events/
webinars/wbnr30376.html?id=30376&p1=50647&p2=50649
Trading with Matlab: http://www.tradingwithmatlab.com/home
Interactive Brokers via Matlab: http://www.maxdama.com/2008/12/
interactive-brokers-via-matlab.html

There you could find and download useful resources and API code on
Matlab trading, for instance, Pairs Trading, Intraday Data Acquisition.
Enjoy.
Tags - matlab , trading

Please read update at http:://www.mathfinance.cn 194


Free real time stock quotes
Get your free real time stock quotes here, one of the worlds largest
stocks and shares websites. Offering the private investor FREE streaming
prices from NASDAQ, NYSE, Dow Jones and many more indices from
around the world, We provide free service like Stock Quotes, Watch
lists, Charts, Financials News, etc. Being a free member you can access to
real-time Dow Jones and NASDAQ indices, FOREX, managed funds,
plus delayed US and world markets stock prices and indices. You will
also be able to access comprehensive range of free charting, research,
news, message boards and stock screening tools.

The free services includes:


# Quotes
# Comprehensive Java & HTML Charting tools
# Streaming Stock watch lists (monitor)
# Free bulletin boards
# Portfolio
# Stock screening tools (toplists)
# Trades
# Company Financial data
# News
# Alerts
# World market profiles

Please sign up as a free member to download FREE stock quote


Tags - data

Please read update at http:://www.mathfinance.cn 195


FX option calculator
Another FX online option calculator by MathFinance covers Vanilla
option, digital option, touch options (one touch, no touch, double one
touch, double no touch), barrier option (single barrer, double barrier)
and Black-Scholes Implied Volatility Calculator.

For detail about options description and calculator please visit


http://www.mathfinance.com/tools/calculator/index.php
Tags - calculator , fx

Please read update at http:://www.mathfinance.cn 196


My last day in office
Today is my last day in the office, I have made up my mind to continue
to study a PhD, it is a hard decision without getting much support from
my family, anyway, every coin has two sides, be positive, positive.

China -> Germany -> China -> Switzerland -> London -> Nottingham

I will have to go back to China for my student visa and stay there for
nearly two months, visiting my family and friends, travelling around,
etc., and come back to UK by the end of August, hopefully. In the
meantime I have to reduce blog publishing frequency, but if you do have
any interesting staff, please leave me at http://www.mathfinance.cn/
contact-me, thanks.

Have a nice summer.

Tags - career

Please read update at http:://www.mathfinance.cn 197


Find MFE Program
Master of Financial Engineering (MFE) degree has increasingly become
a shortcut for people willing to work at a financial institution, especially
to pursue a Quantitative finance related career. There are dozens of
universities around the world providing with MFE program, for
instance, Haas MFE, Columbia FE, and NYU are indisputably among
the best. Sadly or not, only a few people have the chance to study at
these top schools, how do you choose other program then? which factors
will you give priority when applying? location, tuition, possibility to get
financial aid, job placement?

Find MFE is a simple php+mysql page I wrote yesterday evening, the


goal is to filter your ideal MFE program by the self-defined criteria, for
example, you can say "I want to find a MFE program in United States,
total tuition less than $40K, and with financial aid", the script will return
the following MFE programs:
1.) Bentley College in Massachusetts
2.) Florida State University in Tallahassee
3.) Kent State University in Kent
4.) Princeton University in Princeton
5.) Purdue University in West Lafayette
6.) The University of Arizona in Arizona
7.) Vanderbilt University in Nashville
Clicking the link leads you to a page showing the more detailed
introduction of this program, including length of study, size of class,
program website, etc. (some content requires you to be able to get access
to those sites like Youtube, Flickr and Twitter.)

I have no idea if people would find it useful or totally rubbish, it just


tests the water, anyway. I fully understand the accuracy of the searching
results depends largely on the information collected, please do help to
improve it by rating the MFE program, adding a comment or leaving a
message. Thank you. Advanced search like the job placement can be
easily added technically, depending on your feedback.

Find your ideal MFE at http://www.finmath.cn


Tags - mfe

Please read update at http:://www.mathfinance.cn 198


Regime-Switching Model library in Gauss
This is the most up-to-date version of the switching regression
procedures built by Simon van Norden and Robert Vigfusson with help
from Jeff Gable. This Regime-Switching Model library lets you to
estimate a general class of regime-switching models along the lines of
those described in James Hamilton's textbook. Key features and
limitations of the code include:
one independent variable only
two states only
arbitrary number of observed variables may be included to explain time-
varying transition probablities or state-dependent means
external c-code, analytical gradients and combined maxlik()/EM
algorithms for fast calculation
descriptive statistics, plots and White's model-misspecification tests
cascading estimation
separate, faster code for "simple switching" models (i.i.d. mixtures of
regimes.)

learn more and download at http://www.hec.ca/pages/simon.van-


norden/codepage.html and a Guide to the Bank of Canada Gauss
Procedures at http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=50565.

Tags - regime , switch

Please read update at http:://www.mathfinance.cn 199


Vault career guide
This weekend's review is about vault career guide, I bet many people
have heard of it or even used it, I remember when I looked for a job
before graduation, the two books I read often were Heard on the Street:
Quantitative Questions from Wall Street Job Interviews and Vault Career
Guide to Investment Banking, 6th Edition, both of which provide with
clear explanation and insightful experience on how to look for a job and
prepare interviews efficiently, expecially on investment banking
industry.

Vault.com is the leading media company focused on careers. Job seekers,


students and professionals have discovered that Vault is the Internet's
ultimate destination for insider career and education information.

Vault publishes over 120 career guides and its web site, features
thousands of company, university, industry and occupational profiles.
Additionally, Vault provides salary surveys, articles on workplace
topics, a network of message boards for professionals, and job-related
video, blogs and research tools.

Here is an opportunity to sign up for free membership on Vault.com and


get Career Guides for Free., enjoy!
Tags - career

Please read update at http:://www.mathfinance.cn 200


Simulation-Based Estimation of Contingent-Claims Prices
Please allow me to share an interesting paper I came across this morning,
Simulation-Based Estimation of Contingent-Claims Prices, the main point of
this paper is to use Monte Carlo simulation, along with Maximum
likelihood estimation (MLE), to reduce the biases caused by MLE
method alone,
Quotation
A new methodology is proposed to estimate theoretical prices of
financial contingent claims whose values are dependent on some other
underlying financial assets. In the literature, the preferred choice of
estimator is usually maximum likelihood (ML). ML has strong
asymptotic justification but is not necessarily the best method in finite
samples.
This paper proposes a simulation-based method. When it is used in
connection with ML, it can improve the finite-sample performance of the
ML estimator while maintaining its good asymptotic properties. The
method is implemented and evaluated here in the Black-Scholes option
pricing model and in the Vasicek bond and bond option pricing
model. It is especially favored when the bias in ML is large due to strong
persistence in the data or strong nonlinearity in pricing functions. Monte
Carlo studies show that the proposed procedures achieve bias reductions
over ML estimation in pricing contingent claims when ML is biased. The
bias reductions are sometimes accompanied by reductions in variance.
Empirical applications to U.S. Treasury bills highlight the differences
between the bond prices implied by the simulation-based approach and
those delivered by ML. Some consequences for the statistical testing of
contingent-claim pricing models are discussed.

Download the paper and accompanying matlab code at


http://www.mysmu.edu/faculty/yujun/research.html
Tags - simulation , mle

Please read update at http:://www.mathfinance.cn 201


Quantitative Asset Management library
I would like to take this opportunity to thank the author Thierry Roncalli
for letting me know this great source.

QAM (Quantitative Asset Management) library:


QAM is the Gauss library which has been developped for the lecture
notes on Quantitative Asset Management.

This library contains procedures:


for computing backtest (monthly rebalancing, currency hedging, strategy
leveraging, fees managing, performance reporting, etc.).
for portfolio allocation (Black-Litterman, Markowitz, ERC, MDP, risk
Bbdgeting, index sampling, 130/30, MSR, Sharpe style analysis, etc.).
for computing numerical algorithms (simplex set, Markov generator,
quadrature rules, Fokker-Planck equation, etc.).
for derivatives pricing (dynamic delta hedging, Hedge fund replication,
etc.).
for statistical methods (Artificial neural networks, copula, CSS, FLS,
GMM, Huber, LAD, Logit, MARS, ML, NLS, PCA, Probit, Quantile
regression, QP, Robust, Non-parametric Kernel regression, RBS, Tobit,
factor models, etc.).
for time series analysis (arch, garch, vecm, spectral analysis, wavelets,
etc.)
for strategy backtesting (covered call, bull-spread, carry trade, variance
swaps, vix, long/short equity, absolute return strategy, trend-following
strategy, etc.);
for stock screening (gini optimization, scoring methods, boosting, baging
method, etc.)
for risk management (stop loss strategy, take profit strategy,
concentration, etc.)

Please download the manual, library and lecture notes (in French only,
unfortunately) at the author's webpage.
Tags - library , quantitative

Please read update at http:://www.mathfinance.cn 202


Morningstar investment research
This weekend's review is about Morningstar investment research,
needless to say, research is the key to success for investment. Founded in
1984, Morningstar is one of the most respected names in independent
investment research and opinion, as well as the recognized leader in
stock and mutual fund analysis. The mission is to create great investing
products to help people reach their financial goals.

Consistently ranked among the best investment sites on the web,


Morningstar.com offers a wide range of online portfolio management
tools, financial data, unbiased stock and fund analysis, video
commentary, and more.

Because the products focus on sound investing fundamentals and take a


friendly, easy-to-understand approach, Morningstar appeals to a wide
range of investors -- from beginners to the most experienced. They are
likely to be...

# College educated (80%)


# Male (82%)
# Managing a portfolio averaging $870,000
# Living in households averaging $150,000 per year

Get access to More than investment news... In-depth Investing Analysis


& Trusted Opinion. GET YOUR FREE TRIAL NOW!
Tags - research , investment

Please read update at http:://www.mathfinance.cn 203


Vector autoregression (VAR)
Neil left me a message: "...I am looking for examples of Vector
Autoregression so I can code into excel, do you know of any links or any
books that have this as code..."

Vector autoregression (VAR) model is one of the most successful,


flexible, and easy to use models for the analysis of multivariate time
series. It is a natural extension of the univariate autoregressive model to
dynamic multivariate time series. The VAR model has proven to be
especially useful for describing the dynamic behavior of economic and
financial time series and
for forecasting. Wikipedia has a detailed explanation on it.

Unfortunately I have not used it except once I tried the built-in VAR
function in Eviews over 5 years ago, when one of my classmates did a
seminar presentation on it. Sorry I couldn't find useful VBA code, what i
do get is a sample spreadsheet showing the VAR Series Analysis &
Results but it seems the author intentionly hides the macro code,
http://www.afpc.tamu.edu/courses/622/files/lecturedemos/
Lecture%2007%20Vector%20Autoregression.xls.

If you are happy with Matlab, here is a Vector autoregression (VAR)


package where you can track line by line how to implement and use the
model, hope it helps, http://www.rri.wvu.edu/WebBook/LeSage/
etoolbox/var_bvar/contents.html
Tags - vector-autoregression , var

Please read update at http:://www.mathfinance.cn 204


Sobol sequence generator
Sobol sequence has been shared at posts Sobol and Generalised Faure
sequences, halton and sobol sequences, and Primitive polynomials for
Sobol sequences, respectively. Please read Low-discrepancy sequence at
Wikipedia for introduction.

Here is another Sobol sequence generator containing the primitive


polynomials and various sets of initial direction numbers for generating
Sobol sequences. The reason I open a new post for it is it is able to
support up to dimension 15000, incredible. Check it out at
http://web.maths.unsw.edu.au/~fkuo/sobol/index.html.
Tags - sobol , monte carlo

Please read update at http:://www.mathfinance.cn 205


Matlab toolbox
Dozens of Matlab toolboxes(packages) for downloading, including the
following classifications:
Audio - Astronomy - BiomedicalInformatics - Chemometrics - Chaos -
Chemistry - Coding - Control - Communications - Engineering - Data
Mining - Excel - FEM - Fuzzy - Finance - GAs - Graph - Graphics -
Images - ICA - Kernel - Markov - Medical - MIDI - Misc. - MPI - NNets -
Oceanography - Optimization - Plot - Signal Processing - Optimization -
Statistics - SVM - Web - etc ...

Recommended matlab toolboxes:


Kernel Density Estimation Toolbox
http://ssg.mit.edu/~ihler/code/

BOOTSTRAP MATLAB TOOLBOX


http://www.csp.curtin.edu.au/downloads/bootstrap_toolbox.html

CompEcon Toolbox for Matlab


http://www4.ncsu.edu/~pfackler/compecon/toolbox.html

Random Neural Networks


http://www.cs.ucf.edu/~ahossam/rnnsimv2/

Logistic regression
http://www.spatial-econometrics.com/

ARfit: A Matlab package for the estimation of parameters and


eigenmodes of multivariate autoregressive models
http://www.gps.caltech.edu/~tapio/arfit/

Time Series Analysis


http://www.dpmi.tu-graz.ac.at/~schloegl/matlab/tsa/

Interested ppl may download more at http://www.tech.plym.ac.uk/


spmc/links/matlab/matlab_toolbox.html
Tags - matlab , toolbox

Please read update at http:://www.mathfinance.cn 206


Matlab optimization introduction
it is indisputable that optimization has been a crucial part to our
financial world, the application of optimization routine ranges from
fundamental mean-variance Markowitz efficient frountier to advanced
neural network stock price prediction. Here is a carefully selected group
of methods for unconstrained and bound constrained Matlab
optimization problems including:
Line Search Methods:
steep.m : Steepest Descent
gaussn.m : Damped Gauss-Newton
bfgswopt.m : BFGS, low storage
Polynomial line search routines: polyline.m , polymod.m
Numerical Derivatives: diffhess.m : Difference Hessian,
requires dirdero.m : directional derivative, as do several other codes
Trust Region Codes:
ntrust.m : Newton's Method with Simple Dogleg
levmar.m : Levenberg-Marquardt for nonlinear least squares
cgtrust.m : Steihaug CG-dogleg
Bound Constrained Problems:
gradproj.m : Gradient Projection Method
projbfgs.m: Projected BFGS code
Noisy Problems:
imfil.m : Implicit Filtering
nelder.m : Nelder-Mead
simpgrad.m : Simplex Gradient, used in implicit filtering and Nelder-
Mead codes
hooke.m : Hooke-Jeeves code
mds.m : Multidirectional Search code
Check http://www.siam.org/books/kelley/fr18/matlabcode.php for
detail.
Tags - optimization

Please read update at http:://www.mathfinance.cn 207


Online Swap Valuation
Bramaan.com is an online facility for the valuation and risk management
of interest rate derivatives.

Bramaan.com provides everything needed to quickly determine the net


present value, the accrued interest as well as the value of a basis point
for virtually any interest rate swap contract. This includes, but is not
limited to, the development of custom software platforms and the
implementation of processes and procedures for the daily
administration, risk-management, quantitative analysis, accounting and
trading of the previously mentioned financial instruments.

Further details can be found here:


http://www.bramaan.com/
Tags - swap , rate

Please read update at http:://www.mathfinance.cn 208


Heuristic Optimization for Downside Risk Minimization
Modern portfolio optimization started with Markowitz Efficient Frontier,
Heuristic search and optimization is a new approach for solving
complex problems that overcomes many shortcomings of traditional
optimization techniques. Heuristic optimization techniques are general
purpose methods that are very flexible and can be applied to many types
of objective functions and constraints, especially where the objective
function is non-convex and has many local minima. This is in particular
the case when the risk is expressed as VaR, expected shortfall, Omega,
maximum loss etc., and when the future returns of the individual assets
are modelled as scenarios.

An interesting paper "A Data-Driven Optimization Heuristic for


Downside Risk Minimization" demonstrates how to apply Heuristic
optimization method under constraint of downside risk, code can be
downloaded at http://comisef.eu/?q=resources_data_driven_opt, take a
look if interested.
Tags - heuristic , optimization

Please read update at http:://www.mathfinance.cn 209


The end of 100% mortgages is definitely a positive
Consumer Credit awareness website, CreditChoices.co.uk reports that
Major British lenders such as Abbey Mortgages will not be returning to
the practice of issuing 100% mortgages in the near future. In fact most
UK lenders are requiring as much as 20% deposits on home purchase
loans. While on the surface this may seem an unfair adjustment, one
must also consider that those generous loans were based upon inflated
real estate values. Further the larger sum that one finances the larger the
monthly payment will be. This latter statement illustrated by using the
remortgage calculator found at Credit Choices. So we combine these two
factors and arrive at a unique conclusion... we are better off without
100% mortgages and easy credit. Consider this, a house costing £200,000
just two years ago is selling for around £150,000 today. With a deposit of
20% or £30,000 there remains a principle due of £120,000 pounds. This
results in a difference of over £500.00 monthly! Imagine the total cost
over 25 years. Even factors such as mortgage protection are more costly
on the larger loan. Yes many of us may not have the larger sum to place
as deposit but that does not negate the data showing that 100%
mortgages do no one any favour.

Tags - mortgage

Please read update at http:://www.mathfinance.cn 210


SIMTOOLS and FORMLIST Excel add-ins
Simtools.xla and Formlist.xla are add-ins for Microsoft Excel (version 5
and later). Simtools adds statistical functions and procedures for doing
Monte Carlo simulation and risk analysis in spreadsheets. Formlist is a
simple auditing tool that adds procedures for displaying the formulas of
any selected range.

Selected features include:


Inverse cumulative-probability functions;
Functions for working with correlations among random variables;
Functions for decision analysis;
Functions for analyzing discrete probability distributions;
Functions for regression analysis;
Functions for randomly generating discrete distributions;

Download Simtools.xla and Formlist.xla add-ins and instructions at


http://home.uchicago.edu/~rmyerson/addins.htm
Tags - excel

Please read update at http:://www.mathfinance.cn 211


CreditMetrics spreadsheet
CreditMetrics is a framework for measuring credit risk of portfolios of
traditional credit investments (for example, loans, commitments to lend,
financial letters of credit), fixed income products, and market-driven
instruments subject to counterparty default (swaps, forwards, etc.).

It is a lot more complex than RiskMetrics, and thus requires a deliberate


inspection. Actually, within the CreditMetrics framework, users are
confronted with a mixture of choices. For instance, CreditMetrics grants
users to follow one of four different approaches to calculating correlation
among several credit types-historical data, bond spreads, equity
correlations or consistent constants.

Here is an Excel 7.0 spreadsheet demonstrating how to use


CreditMetrics to compute credit risk of a portfolio, technical document
is free to download at http://www.ma.hw.ac.uk/~mcneil/F79CR/
CMTD1.pdf. Functions for calculating the CreditMetrics risk model in R
are at: http://cran.r-project.org/web/packages/CreditMetrics/
index.html
Tags - creditmetrics , spreadsheet

Please read update at http:://www.mathfinance.cn 212


My blog is published at Amazon Kindle
Amazon Kindle is a software and hardware platform for reading
electronic books developed by Amazon.com, few days ago a friend of
mine told me Amazon had a new service called Kindle blog, which
gives a blogger chance to publish his or her blog at Amazon for free.
Since nothing to lose by exposuring a blog to one of the world's largest
websites, I submitted immediately and 10 minutes ago found my blog
was successfully listed at Amazon Kindle.

I intent to make it free but I am not allowed to do so, Amazon


automatically sets the Monthly Price at $0.99 and includes wireless
delivery via Amazon Whispernet, nevertheless, blog subscription starts
with a 14-day free trial, and you can cancel at any time during the free
trial period. (I double checked the publisher's policy, Amazon will
charge 70% of subscription fee while bloggers receive the left 30%, that is
to say, I earn only $0.297 per subscription.)

I don't expect people to subscribe my blog via Amazon Kindle as it is


totally free on web, however, if you happen to use Kindle and would
like to buy me a 1/5 bottle of Beck's beer, I will be pleased .

Check it out at http://www.amazon.com/gp/product/B0029U2FQ6

Tags - amazon , kindle

Please read update at http:://www.mathfinance.cn 213


Binomial tree for American option
This is a follow up post of my previous entry Nine Ways to Implement
Binomial Tree Option Pricing because the latter covers European option
only. Compared with pricing American option by Crank-Nicholson
finite difference or American Options via least square Monte Carlo
Simulation, Binomial tree is the easiest to implement, what you need to
do is just adding a MAX expression on every node of your tree.

Here is a paper on the implementation of binomial tree methods for the


pricing of American option' value and Greeks, matlab codes can be
found in the paper or separately here.
Tags - binomial , american

Please read update at http:://www.mathfinance.cn 214


Eight rules a risk manager must remember
Unlike launching rocket, managing risk is a combination of art and
science that should incorporate a number of fundamental characteristics.
This post is by no means another ex post analysis of the reasons of
current credit crisis, instead, it is about eight simple while crucial rules a
risk manager or risk analyst must keep in mind (print out and post it on
your PC). Sources are from http://www.geocities.com/mrmelchi/
rule.htm and http://nasdaq.riskgrades.com/clients/nasdaq/
edu_course.cgi?href=Module4-L2.html.
Quotation

1.There is no return without risk. Rewards go to those who take risks.


2. Be transparent. Risk should be fully understood.
3. Seek experience. Risk is measured and managed by people, not
mathematical models.
4. Know what you don't know. Question the assumptions you make.
5. Communicate. Risk should be discussed openly.
6. Diversify. Multiple risks will produce more consistent rewards.
7. Show discipline. A consistent and rigorous approach will beat a
constantly changing strategy.
8. Use common sense. It is better to be approximately right, than to be
precisely wrong.

Tags - risk , rule

Please read update at http:://www.mathfinance.cn 215


Nine Ways to Implement Binomial Tree Option Pricing
Binomial tree model is almost the most popular yet easiest way for
option pricing, for one thing, it can be used for most option classes in
market, for example, European option, American option, Bermuda
option, etc.; for another, Binomial tree is straitforward to implement,
several lines are enough for a vanilla option. Besides, it has a not-bad
convergence speed, read my old post A Simple Trick to Avoid
Oscillation in Binomial Trees for improvement.

But how many ways are you able to implement binomial trees? here is a
pretty interesting paper on Nine Ways to Implement Binomial Tree
Option Pricing, unlike Mr. espen haug's more than 30 languages
collection of Black Scholes model, these nine ways are all runnable in
Matlab only, and the difference among them is computational efficiency,
below is a plot of execution times of the first five

here are the paper and matlab codes, you might feel in the end binomial
tree implemention is not such easy .

Enjoy.

Tags - binomial

Please read update at http:://www.mathfinance.cn 216


Wolfram Alpha Computational engine test feedback
No bigger news recently than Wolfram Alpha computational knowledge
engine is finally available today, on 10/03/2009 I briefly wrote a post
about what is wolfram alpha engine and what can it be used to service
us, immediately after that, I applied to be a volunteer tester but got no
reply. Anyway, it officially opens to public and we have chance to test its
magic.

When talking about the pros and cons of Wolfram Alpha engine and
Google, different people will offer different opinions, some people take it
for granted that Wolfram Alpha will be a big threat to Google and
eventually replace Google, however, others hold that Wolfram Alpha is
just a computation calculator, and no matter how powerful it is, it is at
most a calculator with search function . Weighing up these two
arguments, I would say they complement each other, for example, before
you calculate an Europen option with Wolfram Alpha computational
engine, you need to google at least what an Europen option is.

In my previous post I joked about if Wolfram Alpha would return a


result of "Black Scholes call option price with strike 10, asset price 10,
time to maturity 1 year, interest rate 3%, and 25% annual volatility",
alright, it turns out to be YES, just type "Black Scholes", you will get a
form similar to the following graph

Input your parameter and select option types, the value of option you
set, together with its Greeks and plots, are calculated as

So far so good, but it seems the products Wolfram Alpha covers are
limited, when I try to type Barrier option or Asian option, two simple
exotic options, it says "Wolfram|Alpha isn't sure what to do with your
input." there is no API users are able to add their own formulars, either.
In brief, Wolfram alpha is a big step towards intelligent search engine,
nevertheless, as it broadcasts at its main page: it is the first step in an
ambitious, long-term project to make all systematic knowledge
immediately computable by anyone.

Please read update at http:://www.mathfinance.cn 217


Play around at http://www.wolframalpha.com/.
Tags - mathematica , wolfram

Please read update at http:://www.mathfinance.cn 218


Quant job hunting related sites
Since I have been looking for a quant-related job, I share several sites I
personally find useful:

Worldwide:
http://www.efinancialcareers.com
http://www.quantspot.com
http://www.quantster.com/
http://www.quantfinancejob.com/forum/
http://www.wilmott.com/categories.cfm?catid=5
http://www.monster.com

Germany & Switzerland:


http://www.stepstone.de/home_fs.cfm
http://www.jobpilot.de/
http://www.monster.de/
http://www.jobware.de/

Asia (excluding China):


http://quantfinanceasia.com/index.php
http://www.monster.com.sg/index.html
http://www.jobsdb.com/Singapore/
http://www.jobstreet.com.sg/
http://app.www.sg/directory.asp?type=Work&id=14

China:
http://quanthr.com/bbs/forum-9-1.html
http://www.51job.com/
http://www.zhaopin.com/
http://www.jobchina.net/

help me complete the list if you have sites I am not aware of, cheers.
Tags - job

Please read update at http:://www.mathfinance.cn 219


Nonparametric High-Dimensional Time Series Analysis
Functional Gradient Descent (FGD) is a method of nonparametric time
series analysis, useful in particular for estimating conditional mean,
variances and covariances for very high-dimensional time series. FGD is
a kind of hybrid of nonparametric statistical function estimation and
numerical optimization. In fact, the idea of FGD comes from the fact that
boosting can be viewed as an optimization algorithm in function space.
This method employs an iterative refitting of generalized residuals,
based on a given statistical procedure called base learner, to approximate
the first two conditional moment functions of a multivariate process. An
appealing feature of this expansion is that it is a nonlinear nonparametric
model that directly nests the Gaussian diagonal VAR model, the
Gaussian GARCH model and the multivariate CCC-GARCH as simple,
starting special cases. The FGD model is fitted using conventional
maximum likelihood together with a cross-validation strategy that
determines the appropriate number of additive terms in the final
expansions.

Interested ppl shall download the Splus codes and data at


http://www.raffonline.altervista.org/fgd/
PS: to be honest, this is not the area i am family with at all, download at
your own risk
Tags - nonparametric

Please read update at http:://www.mathfinance.cn 220


The Long Vega Financial Engineering Tool
This tool can replicate and price any non path-dependent, continuous
piecewise linear payoff function on a stock. You can use the tool to price
and value option positions and simple structured products on a stock.

The Financial Engineering tool automatically replicates and prices a


given continuous piecewise linear payoff function. So far the tool can
only handle payoffs on a stock, where the payoff is denominated in the
same currency as the stock.

Calculate your option at http://longvega.com/FETool/feapplet.php


Tags - calculator

Please read update at http:://www.mathfinance.cn 221


Free Financial Spreadsheets
Long ago I shared a Financial Model Excel Spreadsheets Library by
Thomas Ho, here is another long list of free financial excel spreadsheets
for financial planning and analysis, although most of them are for
corporate finance practitioners in my view, there are some samples
which might be of your interest, for example:

Risk Premium - Calculates the implied risk premium in a market.


NPV & IRR - Explains Internal Rate of Return, compares projects, etc.
Black Scholes Option Pricing - Excel add on for the pricing of options.
Forex - Foreign market exchange simulation for Excel
Breakeven Analysis - Pricing and breakeven analysis for optimal pricing
Option Trading Workbook - Educational toolkit for using Excel for
Options
EVA Model - Template worksheets for calculating Economic Value
Added (EVA)
...

Download at http://www.exinfm.com/free_spreadsheets.html
Tags - excel

Please read update at http:://www.mathfinance.cn 222


ATOM C++ option calculator
Another derivative calculator shared with you, ATOM - Advanced Tool
for Option Modelling is a C++ option calculator covers:

price, implied volatility and Greek letters;


Black-Scholes analytic formula;
binomial tree lattice;
Cox-Ross-Rubinstein parametrisation;
Jarrow-Rudd equal-probabilitiy parametrisation;
control variable technique;
Broadie-Detemple penultimate node analytic approximation;
Monte carlo simulation with the following variance reduction and
normal sampling techniques:
antithetic variable;
moment matching, also known as quadratic re-sampling;
Mersenne Twister pseudo-random numbers;
Halton quasi-random numbers;
Box-Muller polar normal inversion;
Moro normal inversion;
unlimited maximum number of steps in binomial trees and unlimited
maximum number of trials and time intervals in Monte carlo
simulations;
exotic option support: Asian average price, binary cash-or-nothing and
asset-or-nothing, chooser option;

Download at http://www.atomproject.org/download.shtml
Tags - calculator , option

Please read update at http:://www.mathfinance.cn 223


Twitter of the week
One good way to keep updated of my latest quantitative finance
collector entries is to subscirbe by RSS or email at the righ panel "RSS
feed & subscribe" section, or if yor happen to use twitter, you can follow
my twitter at http://twitter.com/a_biao, where i share my latest blog
post and also my life & feeling of job hunting. For example, my latest one
week twitters are:
-------------------------------------------------------------------------------------------------
------------------------
i am drunken, seriously...about 1 hour ago from web

# What Is Average Salary For A Financial Engineer? http://tinyurl.com/


dl5e8q3:44 PM May 2nd from TwitterFox

# Stress test analysis http://tinyurl.com/dd5lob11:37 PM May 1st from


twitterfeed

# Interview is delayed to next week due to an unexpected meeting. Have


a nice weekend and bank holiday9:03 AM May 1st from twidroid

# Exotic Options Calculator http://tinyurl.com/csw7g85:48 AM May 1st


from twitterfeed

# Playing For Change | Song Around The World "Stand By Me",


wonderful song http://vimeo.com/25397416:09 PM Apr 30th from web

# Look forward to a quant risk role interview tomorrow.3:53 PM Apr


30th from twidroid

# MU vs Arsenal, exciting...2:06 PM Apr 29th from twidroid

# Got a short tel interview just now.11:46 AM Apr 29th from TwitterRide

# Swine flu is in London3:21 PM Apr 28th from TwitterRide

# My calibration is running overnight.8:06 AM Apr 28th from


TwitterRide

# Volatility Forecasting and Trading http://tinyurl.com/cgffv24:47 AM

Please read update at http:://www.mathfinance.cn 224


Apr 28th from twitterfeed

# Why do only headhunters contact me? :)9:34 AM Apr 27th from


TwitterRide

# @cosbeta agree.7:34 AM Apr 27th from TwitterRide in reply to cosbeta

# Terrible monday morning. Coupled ewma makes me dizzy.6:39 AM


Apr 27th from TwitterRide

# think about my future over several bottles of beer8:36 AM Apr 26th


from web

# prepare Tier 1 general5:56 AM Apr 26th from TwitterRide

# finally finished exam, henghenghahie10:57 AM Apr 25th from


TwitterRide

# got lost, finally am here. waiting outside of classroom.7:13 AM Apr


25th from TwitterRide

# on the train to univ of greenwitch for visa english test, have to leave uk
if fails. bless myself.
Tags - twitter

Please read update at http:://www.mathfinance.cn 225


Stress test analysis
In recent months and years both practitioners and regulators have
embraced the idea of supplementing VaR estimates with stress-testing.
Today The Federal Reserve is postponing the release of stress tests on
the biggest U.S. banks. Risk managers are beginning to place an
emphasis and expend resources on developing more and better stress
test analysis.

Here is a good introductory paper aiming to give you a rough idea how
to do stress test, to help demystify stress tests, and illustrate their
strengths and weaknesses. The author use an Excel-based exercise with
institution-by-institution data through stress testing for credit risk,
interest rate and exchange rate risks, liquidity risk and contagion risk in
the design of stress testing scenarios. The purpose of the workbook is to
illustrate basic stress tests (and related tools) that can be used to assess
risks in a small and relatively non-complex banking system, using a
realistic (but fictional) example.

Paper is available at http://papers.ssrn.com/sol3/


papers.cfm?abstract_id=973989&rec=1&srcabs=181931.

Tags - stress-testing

Please read update at http:://www.mathfinance.cn 226


Exotic Options Calculator
MG Soft Exotic Options Calculator is a freeware software to calculate
the option value and greeks of vanilla and exotic options, mainly using
Monte Carlo simulation.

The software supports the following types of options at the moment.

Vanilla Options (using standard Black-Scholes formulae).


Binary (Cash-or-nothing) Options (using standard analytical formulae).
Asian Options (using Monte Carlo simulation).
Barrier Options (using Monte Carlo simulation).
Lookback Options (using Monte Carlo simulation).
...

download at http://www.mgsoft.ru/en/
products_options_calculator.aspx
Tags - calculator , exotic , option

Please read update at http:://www.mathfinance.cn 227


Finite Difference Method for EXCEL
Finite difference method has been repeatedly introduced to solve partial
differential equation (PDE), for example, in past entries Crank-Nicholson
finite difference solution of American option, Crank-Nicolson for a
European put, PSOR for American option, etc.

here is a Finite Difference Method for EXCEL addin which contains


macro to solve numerically partial differential equations (PDE) and
ordinary differential equations (ODE) with the Finite Differences
Method (FD). Seems it can only be applied for two dimensional
problem, but should be enough for normal cases me meet.

Document and macro are at: http://digilander.libero.it/foxes/diffequ/


fdsolver_review.htm
Tags - pde , finite-difference

Please read update at http:://www.mathfinance.cn 228


Parisian option pricer
Parisian option might sound unfamiliar to you, it is basically a barrier
option but becomes activated only after stock prices have spent a certain
continuous, pre-decided time, called a window, above or below the
barrier. One of possible motivations for the existence of the Parisian
option, as stated in Haber, Schoenbucher, and Wilmott (1999) is: "...there
is a need to make the option more robust against short-term movements
of the share price..., in particular, it is far harder to effect the triggering of
the barrier by manipulation of the underlying..."

Taking an up barrier Parisian option as an example, the barrier time tau


is defined as the length of time the stock prices have been above the
barrier in the current excursion
tau := t − sup {s <= t|S(s)<= L}
with up barrier L, tau measures the difference between the current time t
and the last time the stock price S below L, the call feature is activated
only if tau>= D, with D being barrier window.

Interested reader shall download a Parisian option pricer at


http://paul.wilmott.com/software.cfm, where the authors price
Parisian options by a finite-difference solution of a three-dimensional
partial differential equation.
Tags - parisian , option

Please read update at http:://www.mathfinance.cn 229


Volatility Forecasting and Trading
Excel spreadsheets of the course Volatility Forecasting and Trading
taught by Professor Ser-Huang Poon at Manchester business school,
mainly including:

Estimation and Forecasts :


What is Volatility?
Volatility estimation
Data frequency vs. reference period
Realised volatility, quadratic variation and bipower variation
Market microstructure issue
Volatility Forecast and Evaluation
Error statistics
Test for significant difference
Regression based efficiency tests
Volatility Time series models
Historical vol model
Exponential smoothing, EWMA, Regime switching
ARCH
GARCH, IGARCH, EGARCH, GJR-GARCH
Short vs. Long memory models
Stochastic Volatility Models
Extension to Multivriate and Jumps
VaR (Value at risk)
...

more about pdf lectures and excel sample codes are at:
http://www.personal.mbs.ac.uk/spoon/
VolatilityForecastingAndTrading.htm
http://www.personal.mbs.ac.uk/spoon/DataProgrammes.htm
Tags - volatility

Please read update at http:://www.mathfinance.cn 230


LAPACK++: High Performance Linear Algebra
LAPACK++: A Design Overview of Object-Oriented Extensions for High
Performance Linear Algebra. LAPACK++ (Linear Algebra PACKage in
C++) is a software library for numerical linear algebra that solves
systems of linear equations and eigenvalue problems on high
performance computer architectures.

Computational support is provided for supports various matrix classes


for vectors, non-symmetric matrices, SPD matrices, symmetric matrices,
banded, triangular, and tridiagonal matrices; however, it does not
include all of the capabilities of original f77 LAPACK. Emphasis is given
to routines for solving linear systems consisting of non-symmetric
matrices, symmetric positive definite systems, and solving linear least-
square systems.

Download at http://math.nist.gov/lapack++/
Tags - algebra

Please read update at http:://www.mathfinance.cn 231


Selected source this week
Had a nice weekend? Just had an English test for UK Tier 1 General visa,
feel relaxed now. Ok, selected sources this week for you, take a look if
interested.

The Innovative Forex Platform - Download for FREE!

More than investment news... In-depth Investing Analysis & Trusted


Opinion. GET YOUR FREE TRIAL NOW!

Finance Career: Learn about finance firm profiles, finance jobs, finance
career message boards and more.

Join The Investing Social Network

TradingSolutions: Financial analysis and investment software that


combines technical analysis with neural network and genetic algorithms.

Tags - source

Please read update at http:://www.mathfinance.cn 232


Download historical stock price
A friend of mine asks me how to download stock historical price
automatically with Excel, here are two ways I have played:

1, using Excel 2003/2002 Add-in to download from MSN Money Stock


Quotes. This add-in for Microsoft Office Excel 2003 and Microsoft Excel
2002 allows you to get dynamic stock quotes from the MSN Money Web
site. The add-in allows you to easily gather and study the stocks of
interest to you.
http://www.microsoft.com/downloads/
details.aspx?FamilyID=485FCCD8-9305-4535-B939-3BF0A740A9B1&displaylang=en

2, using the following macro to download from Yahoo finance. where


you have to input start, end date and stock symbol
Sub GetData()

Dim DataSheet As Worksheet


Dim EndDate As Date
Dim StartDate As Date
Dim Symbol As String
Dim qurl As String
Dim nQuery As Name

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual

Set DataSheet = ActiveSheet

StartDate = DataSheet.Range("B1").Value
EndDate = DataSheet.Range("B2").Value
Symbol = DataSheet.Range("B3").Value
Range("C7").CurrentRegion.ClearContents

qurl = "http://ichart.yahoo.com/table.csv?s=" & Symbol


qurl = qurl & "&a=" & Month(StartDate) - 1 & "&b=" &
Day(StartDate) & _
"&c=" & Year(StartDate) & "&d=" & Month(EndDate) - 1 & "&e="
&_

Please read update at http:://www.mathfinance.cn 233


Day(EndDate) & "&f=" & Year(EndDate) & "&g=" & Range("E3")
& "&q=q&y=0&z=" & _
Symbol & "&x=.csv"
Range("b5") = qurl

QueryQuote:
With ActiveSheet.QueryTables.Add(Connection:="URL;" & qurl,
Destination:=DataSheet.Range("C7"))
.BackgroundQuery = True
.TablesOnlyFromHTML = False
.Refresh BackgroundQuery:=False
.SaveData = True
End With

Range("C7").CurrentRegion.TextToColumns
Destination:=Range("C7"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False,
Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, other:=False

Range(Range("C7"), Range("C7").End(xlDown)).NumberFormat =
"mmm d/yy"
Range(Range("D7"), Range("G7").End(xlDown)).NumberFormat =
"0.00"
Range(Range("H7"), Range("H7").End(xlDown)).NumberFormat =
"0,000"
Range(Range("I7"), Range("I7").End(xlDown)).NumberFormat =
"0.00"

End Sub

In Matlab there is build-in function named "fetch" for requesting data


from Yahoo! data servers.
Tags - download , data

Please read update at http:://www.mathfinance.cn 234


Neural Network source code
Neural network matlab source code accompanying the book Neural
Networks in Finance: Gaining Predictive Edge in the Market by
professor Paul D. McNelis. This book has got wonderful review like
“This book clarifies many of the mysteries of Neural Networks and
related optimization techniques for researchers in both economics and
finance. It contains many practical examples backed up with computer
programs for readers to explore. I recommend it to anyone who wants to
understand methods used in nonlinear forecasting.”– Blake LeBaron,
Professor of Finance, Brandeis University”. Presumably a worthy-
reading one.

Download the Neural Network matlab source code and several paper at
the author's webpage: http://www.bnet.fordham.edu/mcnelis/
recent.htm or try using TradingSolutions: Financial analysis and
investment software that combines technical analysis with neural
network and genetic algorithms.

Download TradingSolutions

Tags - neural-network

Please read update at http:://www.mathfinance.cn 235


Managing Diversification
Needless to say, diversification plays a pivotal role in investment, not
only for risk management, but for return generation. Attilio Meucci and
his colleagues have another wonderful paper on managing
diversification:
Quotation
We propose a unified, fully general methodology to analyze and act on
diversification in any environment, including long-short trades in
highly correlated markets. First, we build the diversification
distribution, i.e. the distribution of the uncorrelated bets in the portfolio
that are consistent with the portfolio constraints. Next, we summarize
the wealth of information provided by the diversification distribution
into one single diversification index, the effective number of bets, based
on the entropy of the diversification distribution. Then, we introduce
the mean-diversification efficient frontier, a diversification approach to
portfolio optimization. Finally, we describe how to perform mean-
diversification optimization in practice in the presence of transaction and
market impact costs, by only trading a few optimally chosen securities.

Click for codes http://www.mathworks.com/matlabcentral/


fileexchange/23271
Tags - diversification

Please read update at http:://www.mathfinance.cn 236


Forecast Volatility with Regime-Switching GARCH Models
Volatility estimation and prediction is crucial for risk management, for
example, the portfolio's Value at Risk (VaR) and expected shortfall are
partly decided by your volatility estimated, by partly I mean other
factors, like dependence structure decide their values as well. GARCH
model is one of the popular models for volatility estimation, you might
argue volatility regime should also be included to your model given the
totally different performance (hence different parameters) between low
volatility regime and high volatility regime. Here is a good paper
comparing a set of different standard GARCH models with a group of
Markov Regime-Switching GARCH (MRS-GARCH) in terms of their
ability to forecast the US stock market volatility at horizons that range
from one day to one month. To take into account the excessive
persistence usually found in GARCH models that implies too smooth
and too high volatility forecasts, in the MRS-GARCH models all
parameters switch between a low and a high volatility regime. Both
gaussian and fat-tailed conditional distributions for the residuals are
assumed, and the degrees of freedom can also be state-dependent to
capture possible time-varying kurtosis.

Download the paper and matlab codes at http://www.bepress.com/


snde/vol9/iss4/art6/.
PS: In the codes the author multiply returns by 100 for optimization
(hopefully for a faster convergence), I personally found the parameters
are unstable with the change of this number. no idea if it is my data
problem.
Tags - garch , regime

Please read update at http:://www.mathfinance.cn 237


Scholarship to apply for
ALMOST NOTHING POSITIVE, these are the most heard words
recently whenver I have a talk with my former colleagues and
classmates, as you might recall from my post "shit happens everywhere",
I will lost my current job soon as well. Yes, it is true, i was told i could
only stay in my office till the end of June, which means I have to either
look for a new job, for instance, Finance Career: Learn about finance firm
profiles, finance jobs, finance career message boards and more. , or find
another way out, for instance, study for a MFE or PhD.

Staying at university for a while is no doubt a good way to decrease the


impact of credit crisis on you, since the job hunting competition gets
tough and tough, even a humble position requires "ideally an applicant
with PhD degree with 2 or more years work experience". How to choose
a good MFE or PhD in QF program is natually a question everybody has
before application, here by good program I mean good placement with
accepted tuition fee (PS: I saw two weeks ago The University of Hawai’i
Shidler College Of Business is offering one year Master of Financial
Engineering program with scholarship available, search in Google if you
are happy with the location). I happen to see such a rank, which might
be suggestive to you, although this rank is too old,

After you are lucky enough to get an admission from one of these Top
programs, you might wonder how to arrange money for enrolling in a
graduate school? Is money a real concern for you? Getting an admission
to a graduate is not an easy job but the big cheese is to collect money to
pay tuition. All students would be pleased to recognise that state and
private lenders offer awards and scholarships for you. It doesn't matter
whether you have just finished undergraduate level or have been
working for some years. The scholarships are available almost for all but
standards changes within financial institutions. Some lenders award on
merit basis with a proved track record in undergraduate school and
some grants are provided on the basis of the amount required for the full
graduate school degree program. To apply for a scholarship is not that
easy as it looks to be. one source to search and apply for a scholarship I
have ever tried is Find scholarships today at ScholarshipExperts.com -
providing US & international students with customized scholarship info!

Please read update at http:://www.mathfinance.cn 238


, should you are interested, please take a try.

Good luck to all of you (including me) for job hunting or graduate school
application. Enjoy life.

Tags - scholarship , mfe

Please read update at http:://www.mathfinance.cn 239


Salih Neftci (1947-2009) passed away
Bad news for all of us, Professor Neftci passed away yesterday in
Geneva.

He is a such an important person to my quant-related life, his book


Introduction to the Mathematics Of Financial Derivatives is so clear
and easy to understand for anybody without any stochastic background,
which helped me to work through my first master thesis at 2004; and his
another book Principles of Financial Engineering is almost a must-
owned one...

Silent Salute!

Tags - salih-neftci

Please read update at http:://www.mathfinance.cn 240


Binary Option Calculator on Gphone
Equity Option Calculator on Gphone was shared in this post. The author
has published a binary option calculator for Gphone, as the author's
webpage says:

Quotation
Binary Option Calculator is for advanced options traders. Calculate
option prices and Greeks for discontinuous payoff functions.

Can price any combination of:


Calls or Puts
European or American style
Cash-or-nothing or Asset-or-nothing
Option value or Implied volatility.

To download, either search "Binary Option" on Gphone, or simply go to


the author's blog http://jwdevg1.blogspot.com/2009/04/binary-option-
calculator-published.html
Tags - gphone , calculator , binary , option

Please read update at http:://www.mathfinance.cn 241


Stress testing under Black Litterman framework
Black Litterman model has been used largely for portfolio construction,
one of the major differences with Markowitz mean-variance Efficient
Frontier model, among others, is BL allows users to input certain views
under confidence level on assets, say, "I am 85% confident S&P 500 will
have 5% excess return", or "Bond index will outperform equity index by
1.5% certainly", etc. If you are totally fresh to Black Litterman model,
click here.

Most of paper on Black litterman are about how to construct an


optimized portfolio, and this portfolio can be adjusted under given risk
constraint, Attilio Meucci, going further step, has a paper incorporating
natually stress testing and scenerio analysis under Black Litterman
framework, they propose a unified methodology to input non-linear
views from any number of users in fully general non-normal markets,
and perform, among others, stress-testing, scenario analysis, and ranking
allocation. Paper "Fully Flexible Views: Theory and Practice" and Matlab
codes are at http://papers.ssrn.com/sol3/
papers.cfm?abstract_id=1213325 and http://www.mathworks.com/
matlabcentral/fileexchange/21307.

Just finished an interview today, Balabala one and half an hour without
even a detailed technical question, I suspect if it is really a Quant related
job position or the desire the company indeed needs a people. Anyway,
fighting.
Tags - black-litterman , stress-testing

Please read update at http:://www.mathfinance.cn 242


Play with cointegration
Cointegration is the foundation upon which pair trading (“statistical
arbitrage”) is built, basic cointegration function can be easily found in
any popular statistical software package, for instance, Unit root and
cointegration tests for time series data (urca) in R. Should you are
interested in playing with advanced cointegration test, go there, for
instance, estimating a threshold bi-variate VECM, and testing for the
presence of a threshold.

Focusing on 3 publications
"Tests for parameter instability in regressions with I(1) Processes."
Journal of Business and Economic Statistics (1992).

"Residual-based tests for cointegration in models with regime shifts."


with Allan Gregory, Journal of Econometrics, (1996).

"Testing for two-regime threshold cointegration in vector error


correction models," with Byeongseon Seo, Journal of Econometrics
(2002).

Tags - cointegration

Please read update at http:://www.mathfinance.cn 243


Estimation of Structured t-Copulas
A collection of codes on Copula estimation and simulation is shown
here, where you can find parameter estimation for t-copula, Grouped-t
copula, asymmetric copula, etc., another simple recursive routine to
estimate by maximum likelihood the correlation matrix and the degrees
of freedom for structured t-copula is shared at
http://www.mathworks.com/matlabcentral/fileexchange/19751, the
authors impose extra structure on the correlation matrix in the
estimation process, where the number of variables is large as compared
to the number of observations.

The paper "Estimation of Structured t-Copulas" is available at:


http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1126401, more
paper and codes are at the author's homepage:
http://www.symmys.com/AttilioMeucci/Home/Home.html
Tags - copula

Please read update at http:://www.mathfinance.cn 244


GMM and Empirical Likelihood
Generalized method of moments (GMM) estimation has got more and
more popularity for linear and non-linear models with applications in
economics and finance. GMM estimation was formalized by Hansen
(1982), and since has become one of the most widely used methods of
estimation for models in economics and finance. Unlike maximum
likelihood estimation (MLE), GMM does not require complete
knowledge of the distribution of the data. Only specified moments
derived from an underlying model are needed for GMM estimator. In
some cases in which the distribution of the data is known, MLE can be
computationally very burdensome whereas GMM can be
computationally very easy. The log-normal stochastic volatility model is
one example. In models for which there are more moment conditions
than model parameters, GMM estimation provides a straightforward
way to test the specification of the proposed model. This is an important
feature that is unique to GMM estimator.

Download Programs for GMM and Empirical Likelihood at


http://www.ssc.wisc.edu/~bhansen/progs/progs_gmm.html

Finally, Happy easter day to all of you, while I will have to stay at home
preparing interview

Tags - gmm

Please read update at http:://www.mathfinance.cn 245


Nonparametric Density Estimation
A simple, straightforward way to estimate density nonparametrically is
kernel density estimator, for instance, in R a built-in function density() is
for this, with different kernel choices "gaussian", "epanechnikov",
"rectangular", "triangular", "biweight", "cosine", and "optcosine". Should
you are unhappy with this function and eager for an extention, take a
look at the following papers and associated codes:

"Exact Mean Integrated Squared Error of Higher-Order Kernels"


Econometric Theory (2005).
"Bandwidth Selection for Nonparametric Distribution Estimation"
unpublished working paper (2004).
"Nonparametric Estimation of Smooth Conditional Distributions"
unpublished working paper (2004).
"Interval Forecasts and Parameter Uncertainty" Journal of Econometrics
(2006).

http://www.ssc.wisc.edu/~bhansen/progs/progs_np.html

Tags - density

Please read update at http:://www.mathfinance.cn 246


Newey West estimator
This function returns the Newey-West estimator of the asymptotic
variance matrix. What is Newey West? it was proposed by the author
Whitney K. Newey and Kenneth D. West in their paper "A simple,
positive semi-definite, heteroskedasticity and autocorrelation consistent
covariance matrix" at 1987. It rests on considerations of the so-called
“frequency domain representation” of the Ft’s and also of a number of
notions associated with nonparametric estimation procedures.

One possible application of Newey West estimator is for long run


variance covariance calculation; another might be for the improvement
of OLS regression when the variables have heteroskedasticity and
autocorrelation.

Download at http://www.homepages.ucl.ac.uk/~uctprgi/
Matlabcode.htm
Tags - covariance

Please read update at http:://www.mathfinance.cn 247


Allan variance
Long term memory has frequently been observed in time series.
Statistical theory for long term memory stochastic processes is largely
different from the standard time series analysis, which assumes short
term memory. The Allen variance is a particular measure of variability
developed for long term memory processes.

Taken from Wikipedia, "The Allan variance, named after David W.


Allan, is a measurement of stability in clocks and oscillators. It is also
known as the two-sample variance. It is defined as one half of the time
average of the squares of the differences between successive readings of
the fractional frequency error sampled over the sampling period."

I am not quite convinced how to use Allan variance for stock returns,
that is, given stock return time series, can we better estimate its long
term variance by Allan variance? any idea?

Allan variance Matlab code is easy to write and can also be downloaded
at: http://www.alamath.com/
index.php?option=com_content&task=view&id=19&Itemid=31

Tags - variance

Please read update at http:://www.mathfinance.cn 248


Black Scholes on excel
Excel Add In (Visual Basic) for Black Scholes, Numerical Integration
and Probability Density Estimation

This is a MS Excel Add In (with Visual Basic Source Code) for several
separated issues:

1. Numerical Integration

2. Golden Section Search for Max/Min

3. Probability Density Estimation Using Kernels

4. Black Scholes Option Valuation, Implied Volatility and Option


Greeks
Many of these functions can also be used in standalone Visual Basic
applications.

Read Installation and Use Instructions. Download Excel Add-In and


Visual Basic source code as a zip file or as tar.gz file at
http://www.iimahd.ernet.in/~jrvarma/software.php
Tags - black scholes

Please read update at http:://www.mathfinance.cn 249


Financial Engineering Toolbox
A toolbox accompanying the book "Financial Engineering: Derivatives
Pricing, Computer Simulations, Market Statistics", (couldn't find the
book on Amazon, surprisingly), which provides a comprehensive
overview of financial markets and a cutting-edge discussion of
mathematical and numerical methods employed in financial
engineering. The primary topics covered include: in-depth reporting of
derivatives' pricing models, constructions and practical application of
exotic options, and market statistics with a comprehensive review of
time series models.

Selected chapters:
1. Introduction
2. Financial markets
3. Securities
4. Basic derivatives (forwards, futures, swaps and options)
5. Financial mathematics of discrete models
6. Financial mathematics of continuous models
7. Term structure models
8. Construction and pricing of exotic derivatives
9. Market statistics
10. Alternative models

Downloading at: http://www.im.pwr.wroc.pl/~hugo/stronaHSC/


Podstrony/ksiazki/if_gb.html
Tags - toolbox

Please read update at http:://www.mathfinance.cn 250


Apply student credit card
This is a review of week.

College shall be a time of studying, a time of risk taking, and a time of


tension. Most of those tensions stem from bills. From student loans to
schoolbooks, college life costs expensive. A lot of pupils apply for for
student credit cards at school.

Student credit card is given to any member of the academic


organizations disregarding whether he or she is part time or full time,
undergraduate or graduate student, international students who are
exchanging, working or learning in the United States, university staffs
either full time or part time faculty and executives who are 16 year old
age and above. For those students who are less than 18 years of age
accepted from the parents or the guardian is compulsory.

Applying for a student credit card is suggested because it can help


pupils in making their accredit history which might be useful in the
future particularly in finding loans like automobile, real estate or even
immediate payment loans. Most of international students and scholars
discover it actually hard to receive a credit card as they lack a credit card
history. For them to make a credit card history they ought to have a
credit card or at the least consume a history in paying back debts of
whatever case. It is indeed a frustrative position specially if you are
seriously in need of financial help.

Please read update at http:://www.mathfinance.cn 251


Shit happens everywhere
Today is the first day of G20 summit, is also the strongest protest in the
last fews days, which will last at least till tomorrow. Company suggests
us to have dress down to avoid unnecessary conflict with protestors, (for
those of you who have no idea what's happened or how seriou this
protest is in London recently, what I can tell you is the slogan of a
protestor group being "Burn a banker"), I do enjoy dress down, wearing
jeans, t-shirt and looking relaxed (although not).

Protest itself is fair enough and welcomed, everyone has the right to
speak out his or her own views, this is a kind of freedom we should
cherish, but freedom does not mean you can do anything you want. I
fully understand the feeling of losing job (I myself will be one of them
soon), however, this should never be an excuse of blaming other people,
nothing hurts us, as foreigners, worse than hearing "fucking foreigners"
in the broad street. Fortunately, those people are only a few, shit
happens everywhere.

there is still "hero"

more pics can be found http://www.flickr.com/search/


?q=london+protest&s=rec

Tags - protest

Please read update at http:://www.mathfinance.cn 252


MFE toolbox
Oxford MFE package was shared there, here is a new MFE Matlab
toolbox accompanying the book "Modeling and Forecasting Electricity
Loads and Prices: A Statistical Approach", which is grouped into the
following seven categories:

1. Time series,
2. Distributions,
3. Tests and goodness-of-fit functions,
4. Markov regime switching (MRS) models,
5. GUI functions,
6. Demos,
7. Data files.

Selected functions are:

armaacvf - Autocovariance function of an ARMA process.


average - Weighted average.
decompB - Moving average with rolling volatility daily data
decomposition.
rollingvol - Annual rolling volatility.
empcdf - Empirical cumulative distribution function (cdf).
hypest - Estimate parameters of the hyperbolic distribution.
nigcdf - NIG cumulative distribution function (cdf).
nigest - Estimate parameters of the NIG distribution.
nigloglik - NIG log-likelihood function.
nigpdf - NIG probability density function (pdf).
stabcdf - (Alpha-)stable cumulative distribution function (cdf).
stabcull - Quantile parameter estimates of a stable distribution.
stabreg - Regression parameter estimates of a stable distribution.
edftests - Empirical distribution function (edf) goodness-of-fit statistics
(Kolmogorov and Anderson-Darling).

Downloading the toolbox at: http://www.im.pwr.wroc.pl/~rweron/


MFE.html
More about the book at: http://www.riskey.cn/2009/04/modeling-and-
forecasting-electricity-loads-and-prices-a-statistical-approach-the-wiley-
finance-series-hardcover/
Tags - mfe , matlab , toolbox

Please read update at http:://www.mathfinance.cn 253


Financial data download
Financial data is the center of quantitative finance research,
undoubtedly. Here is a list of free financial data for downloading, for
more please check pages http://www.quantnet.org/forum/
showthread.php?t=2159 and http://www.wilmott.com/
messageview.cfm?catid=19&threadid=14748, enjoy.

For instance:
1. ADVFN offer FREE streaming stocks and shares data form around the
world. SEE MORE
2. Historical FX Rates: http://oanda.com/convert/fxhistory
3. Historical Stock Prices: http://finance.yahoo.com/q/hp?s=yhoo
4. Recent LIBOR rates: BBA - British Bankers' Association - BBA LIBOR
5. Some Implied Volatilities: http://www.ivolatility.com
6. Delayed Commodities: http://www.liffe-commodities.com.
7. US Fundamentals: http://www.sec.gov

Tags - data

Please read update at http:://www.mathfinance.cn 254


Independent Components Analysis
The FastICA package is a free (GPL) MATLAB program that implements
the fast independent component analysis.

Independent component analysis (ICA) or blind source separation is a


modern signal processing technique to multivariate financial time series
such as a portfolio of stocks to multivariate financial time series such as a
portfolio of stocks. The key idea of ICA is to linearly map the observed
multivariate time series into a new space of statistically independent
components (ICs). This can be viewed as a factorization of the portfolio
since joint probabilities become simple products in the coordinate system
of the ICs.

The major difference between Independent component analysis and


more familiar principal component analysis (PCA) is in the type of
components obtained. The goal of PCA is to obtain principal components
which are uncorrelated. Moreover, PCA gives projections of the data in
the direction of the maximum variance. The principal components (PCs)
are ordered in terms of their variances: the first PC defines the direction
that captures the maximum variance possible, the second PC defines (in
the remaining orthogonal subspace) the direction of maximum variance,
and so forth. In ICA however, the aim is to obtain statistically
independent components. What's more, PCA algorithms use only second
order statistical information (variance dominates). On the other hand,
ICA algorithms may use higher order2 statistical information for
separating the signals.

To download FastICA and more about the book Independent


Component Analysis check http://www.cis.hut.fi/projects/ica/
fastica/, the book can be bought at Amazon through: Independent
Component Analysis
Tags - multivariate

Please read update at http:://www.mathfinance.cn 255


Equity option calculator on Gphone
I bought a Gphone several months ago, its main attraction to me is Gmail
everywhere as long as there is signal since I can't use Gmail box with my
PC at company (my boss won't read my blog). Another shining point of
Gphone is its Android platform and Market, where people can publish
applications on entertainment, finance, news, weather, etc.

Yesterday I downloaded a free application named Equity option


calculator, a simple equity options pricer for European style no dividend
calls and puts using your own inputs under Black Scholes model
framework. Alternatively enter a ticker and let the market data calibrator
fill in pricing parameters. solve for the option value or implied volatility.
The pricer also calculates option sensitivities (Greeks).

Although the supported options are limited, it is fun to play a derivative


calculator wherever as you go, isn't it? the code is written in Java that I
am not familiar with, but have downloaded The Android SDK for
developers to see if I am able to build an application covering more
options like Matlab-GUI equity derivative calculator does.

if you happen to own a Gphone, this option pricer can be found by


typing "equity option calculator" in Market. Have fun.

Publisher's blog: http://jwdevg1.blogspot.com/


Tags - calculator , gphone , option

Please read update at http:://www.mathfinance.cn 256


Kernel principal component analysis
EasyPCA is a small educational program intended to help to understand
how the Principal Component Analysis (PCA) algorithm works. It has
been coded in a very modular way in order to make it easy to
understand the code.

PCA is a useful statistical technique that has found application in fields


such as face recognition and image compression, and is a common
technique for finding patterns in data of high dimension.

For more detail please check http://transp-or2.epfl.ch/pagesPerso/


javierFiles/software.php
Tags - pca

Please read update at http:://www.mathfinance.cn 257


Create your own websites
This is a review of the week.

You are perhaps a modest enterprise owner who already holds a


website, You might be a SOHO work-at-home self-employee who would
like to make additional revenue for yourself. You may be an cyberspace
seller who prefer to bring affiliate or marketing to the advanced level.
Disregarding what you wish to do on internet you're likely becoming to
need to understand how to make a website that operates.

While it refers to constructing websites there's many confusion about the


best method to do. Nevertheless, it is crucial to choose what your
purpose is prior to do it, even before you register a host name!

Should you just prefer to "set up a website" and do not concern whether
or not it gets any visitor or has any possibility to make you an income,
that's easy. There are a lot of free lunch services that will allow you
produce a personal website to share experiance or make friends online.

However, if you prefer to create website that looks appealing or more


professional, you will have to plan a little more carefully. BlueVoda is a
drag & drop Web site builder that enables a user with almost no
experience to build a fantastic Web site. No HTML, PHP or any other
coding knowledge is demanded. From a simple homepage to a fancy
WEB2.0, you can also own one with few simple steps.

Please read update at http:://www.mathfinance.cn 258


VIX calculation
CBOE Volatility Index, VIX, was originally designed to measure the
market’s expectation of 30-day volatility implied by at-the-money S&P
100 Index (OEX) option prices. Now VIX is used to reflect a new way to
measure expected volatility, one that continues to be widely used by
financial theorists, risk managers and volatility traders alike. The new
VIX is based on the S&P 500 Index (SPX), the core index for U.S. equities,
and estimates expected volatility by averaging the weighted prices of
SPX puts and calls over a wide range of strike prices. By supplying a
script for replicating volatility exposure with a portfolio of SPX options,
this new methodology transformed VIX from an abstract concept into a
practical standard for trading and hedging volatility.

Introduced by this paper http://www.cboe.com/micro/vix/


vixwhite.pdf, VIX calculation is done step-by step as:
1), Select the options to be used in the VIX calculation;
2), Calculate volatility for both near-term and next-term options;
3), Calculate the 30-day weighted average of variance, then take the
square root of that value and multiply by 100 to get VIX.

Matlab code: http://docs.google.com/Doc?id=ddb2j6dw_12fjk57bfx


Tags - volatility , vix

Please read update at http:://www.mathfinance.cn 259


Top Quant codes collection you shouldnt miss
To search and backup easier, I make a PDF file which includes so far
most of entries of the Quantitative finance collector blog. This
Quantitative finance codes list is partly what I have collected during my
financial engineering learning journey. Most of the entries were written
when I was at university, apparently many codes can not be used
directly for a certain purpose, we can, certainly, learn the way the coders
applied.

Although I try best to check each file before recommendation,


downloading and using are at your own risk. Should you are interested
and would like to track my latest collection, please visit my blog or
follow my twitter at http://www.twitter.com/a_biao.

You can distribute this list as you want, the only wish from me is please
’do not change the sentences’ and leave the original links when you want
to post somewhere, thank you.

Downloading the PDF file at: http://www.mathfinance.cn/attachment/


QuantitativeFinanceCollector.pdf (right click and save as)

Please read update at http:://www.mathfinance.cn 260


Option pricing with excel
A nice paper on step-by-step option pricing with excel, VBA codes are
included in the paper as well.

The authors first briefly review the principles of pricing by no arbitrage


in a binomial tree, and show how this can be implemented in Excel; then
move to continuous-time model - Black scholes pricing model; after a
short discussion on the parameter estimation issues, they turn to two
numerical methods for pricing, which are Monte Carlo simulation and
Finite difference for Partial differential equation (PDE); at last, option
hedging is introduced, advantages and disadvantages of spreadsheets in
general and Excel in particular are analyzed shortly.

Download paper "Option pricing with the Excel" at


http://www.math.ku.dk/~rolf/REV.excelpaper.pdf
Tags - option , excel

Please read update at http:://www.mathfinance.cn 261


Cheap web hosting solution
This is a short review of web hosting.

Many folks would like to own Web sites nowdays, however they concern
about the cost. Purchasing the real domain name is really cheap, around
10 US dolloars you can get a fancy dot com name, therefore it's not
actually a problem. What's crucial, although, is the hosting. it is
meaningless to have a domain name should you do not go forward and
make a site on it, begin appealing subscribers and customers, and do
something to earn revenue. Even if you are merely blogging, you may
not prefer to utilize the free services. If you are not blogging and you're
indeed marketing a product or service, you truly can not bear free
hosting. You'll have to own a Web site that allows more than what you
are able to do on free services, most probably. There are dozens of ways
to acquire that hosting, though, and the best way for most people is to
use the Web Hosting service that accompanies the host name. Numerous
corporations who sell domain names feature these hosting packages, and
they aren't really expensive. For instance, 4 Cheap Web Hosting is a
guide to the best rated affordable web hosting packages available online.
Take a look if you have plan to own a site in the near future.

Please read update at http:://www.mathfinance.cn 262


Oxford MFE UCSD GARCH toolbox
The Oxford MFE Toolbox is the follow on to the UCSD GARCH toolbox.
It has been widely used by students here at Oxford, and represents a
substantial improvement in robustness over the original UCSD GARCH
code, although in its current form it only contains univariate routines.

Contents include:
1 Stationary Time Series 5
1.1 ARMA Simulation
1.1.1 Simulation: armaxfilter_simulate . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 ARMA Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2.1 Estimation: armaxfilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2.2 Residual Plotting: tsresidualplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.2.3 Characteristic Roots: armaroots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.2.4 Information Criteria: aicsbic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.3 ARMA Forecasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.3.1 Forecasting: arma_forecaster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.4 Sample autocorrelation and partial autocorrelation . . . . . . . . . . . . . . . .
. . . . . . . 23
1.4.1 Sample Autocorrelations: sacf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.4.2 Sample Partial Autocorrelations: spacf . . . . . . . . . . . . . . . . . . . . . . . . . .
25
1.5 Theoretical autocorrelation and partial autocorrelation . . . . . . . . . . . . .
. . . . . . . . 27
1.5.1 ARMA Autocorrelations: acf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.5.2 ARMA Partial Autocorrelations: pacf . . . . . . . . . . . . . . . . . . . . . . . . . . .
29
1.6 Testing for serial correlation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
31
1.6.1 Ljung-BoxQ Statistic: ljungbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
1.6.2 LM Serial Correlation Test: lmtest1 . . . . . . . . . . . . . . . . . . . . . . . . . . . .
33
2 Nonstationary Time Series 37
2.1 Unit Root Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.1.1 Augmented Dickey-Fuller testing: augdf . . . . . . . . . . . . . . . . . . . . . . . .
. 37
2.1.2 Augmented Dickey-Fuller testing with automated lag selection:
augdfautolag . . . . 40
3 Vector Autoregressions 43

Please read update at http:://www.mathfinance.cn 263


3.1 Stationary Vector Autoregression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . 43
3.1.1 Vector Autoregression estimation: vectorar . . . . . . . . . . . . . . . . . . . . . .
. 43
3.1.2 Granger Causality Testing: grangercause . . . . . . . . . . . . . . . . . . . . . . . .
50
3.1.3 Impulse Response function calculation: impulseresponse . . . . . . . . . .
. . . . 53
4 Volatility Modeling 57
4.1 GARCH Model Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
57
4.1.1 ARCH/GARCH/GJR-GARCH/TARCH/AVGARCH/ZARCH
Estimation: tarch . . . . . . 57
4.1.2 Some behind the scenes choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
59
4.1.3 EGARCH Estimation: egarch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.1.4 APARCH Estimation: aparch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
66
5 Density Estimation 71
5.1 Kernel Density Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
71

Code and documention are available at:


http://www.kevinsheppard.com/wiki/MFE_Toolbox
Tags - garch

Please read update at http:://www.mathfinance.cn 264


Quant salary
Hutson has published its quant salary survey results in Asian market,
http://china.hudson.com/documents/Hudson-Asia-Banking-Financial-
Services-Salary-Information.pdf, focusing on Banking and Financial
services sector. The figure looks not bad at all, given the terrible market
of 2008. I have to say for many cases the quant salary does not mean the
exact number the quant get, especially in China, other income exceeding
salary is pretty possible.

I also had a survey for quant salary in mainland, China, results are
shown below (basic salary + bonus, about 1~3 years work experience in
Chinese Yuan):
number percentage of voters
50K ~ 80K 11.4%
80K ~ 100K 7.89%
100K ~ 120K 5.26%
120K ~ 150K 22.81%
150K ~ 200K 7.02%
200K ~ 300K 7.89%
>300K 37.72%

Considering the average annual salary for Chinese fresh master


graduates is about 60K, quant salary is exicting, isn't it?
Tags - salary

Please read update at http:://www.mathfinance.cn 265


Video lectures
Just share with you guys two free online video lecture sites I have
recently used, both time- and cost- saving, isn't it? enjoy.

http://videolectures.net/Top/Computer_Science/Machine_Learning/

http://videolectures.net/
Tags - video

Please read update at http:://www.mathfinance.cn 266


Asymmetric copula analysis
http://www.mathfinance.cn/Grouped-T-copula-simulation-estimation/
shared a sample code for grouped-t copula simulation, further, several
copula estimation and simulation package can be found. But, most of the
case we talk about an exchangeble copula due to its relatively easier to
explain, however, it has limited applications especially in the area of
credit risk, or derivative markets where asymmetric dependence plays a
crutial role. For example, a desire to maintain the competitiveness of
Japanese exports to the United States. with German exports to the United
States. would lead the Bank of Japan to intervene to ensure a matching
depreciation of the yen against the dollar whenever the Deutsche mark
(DM) depreciated against the U.S. dollar. Such rebalancing behavior
would also lead to greater dependence during depreciations of the DM
and yen against the dollar than during appreciations. It is certainly
natural to enquire whether there are extensions that are not rigidly
exchangeble.

A scatter plot of the return of S&P 500 index and that of its implied
volatility difference series is shown above, clearly the dependence is
stronger in left-up corner than right-down corner.

Interested reader shall refer to the following papers and Matlab codes for
detail:
Modelling Asymmetric Exchange Rate Dependence, 2006, International
Economic Review, 47(2), 527-556.
Paper (PDF), Abstract (HTML), Slides June01 (PDF), Code (MATLAB)

-- This paper was previously circulated as “Modelling Time-Varying


Exchange Rate Dependence Using the Conditional Copula”, University
of California, San Diego, Discussion Paper 01-09.
-- The Joe-Clayton and symmetrised Joe-Clayton copula density
functions can be found here (PDF). Matlab functions for these can be
found here.
http://econ.duke.edu/~ap172/research.html

Tags - copula , asymmetric

Please read update at http:://www.mathfinance.cn 267


c++ for finance
A c++ class list for finance, specifically, a derivative calculator source
code, is available, including:

american_option_approximation: uses the Black Scholes formulae for


European options, to approximate the values of American options.

american_option_fudge: approximates the value of American Options as


the value of the corresponding European option, plus the addition of a
fudge factor

binomial_option: typical binomial tree to price option value

Bisection_Secant< functor, real > : This class is a child class of Bisection.


The algorithm converges faster because it changes from the bisection to
the secant algorithm /// on every other iteration

european_option_pair : Black Scholes option pricing formulae for puts


and calls

...

Click for more and downloading http://acumenconsultinginc.net/


TechNotes/public_options/html/annotated.html
Tags - option , c++

Please read update at http:://www.mathfinance.cn 268


WolframAlpha computational knowledge engine
You might have no idea who is Wolfram, but you might know
Mathematica more or less, right, Wolfram is the computer scientist who
has developed Mathematica. A recent post of his blog shows his another
more ambitious project named Wolfram|Alpha will be available in May,
2009.

What is Wolfram|Alpha? its own logo says WolframAlpha is a


computational knowledge engine, It doesn't simply return results that
contain (match) the keywords you search, like Google, Yahoo, or MSN
live does, and it isn't only a giant database of knowledge, like the
Wikipedia; Instead, Wolfram Alpha indeed computes the answers to the
question you type in the "search" form. Simply put, it is a (computation +
search) engine.

Since the project will only be available for public after May, currently we
can't test its efficiency and how magic it is. Can it return the value of
"Black Scholes call option price with strike 10, asset price 10, time to
maturity 1 year, interest rate 3%, and 25% annual volatility"? LOL, I am
too demanding.

Anyway, should you be interested, please check it at:


http://www.wolframalpha.com/

Tags - mathematica , wolfram

Please read update at http:://www.mathfinance.cn 269


Maximum likelihood estimation of CIR interest rate
Quotation
The square root diffusion process is widely used for modeling interest
rates
behaviour. It is an underlying process of the well-known Cox-Ingersoll-
Ross
term structure model (1985). We investigate maximum likelihood
estimation
of the square root process (CIR process) for interest rate time series. The
MATLAB implementation of the estimation routine is provided and
tested on
the PRIBOR 3M time series.

PDF file with Matlab codes included: http://dsp.vscht.cz/


konference_matlab/MATLAB07/prispevky/kladivko_k/kladivko_k.pdf

For those intested: a small re-organization of the blog has been


undertaken, we moved all codes collection posts under category Quant
code, which makes browse easier and more convenient (hopefully). In
addition, we added Quant newssection where selected news and
resources, focusing on Asian Quant markets, will be published. Hope
this change won't bring trouble to you, thanks.
Tags - cox ingersoll ross

Please read update at http:://www.mathfinance.cn 270


Compound option pricing
A compound option is simply an option on an option. The exercise
payoff of a compound option involves the value of another option. A
compound option then has two expiration dates and two strike prices.
Take the example of a European style call on a call. On the first
expiration date T1, the holder has the right to buy a new call using the
strike price X1. The new call has expiration date T2 and strike price X2.

The pricing of many other derivative instruments can be modeled as


compound options. By visualizing the underlying stock as an option on
the firm value, an option on stock of a levered firm that expires earlier
than the maturity date of the debt issued by the
firm can be regarded as a compound option on the firm value (Geske,
1979). On the expiration of the option (the first expiration date of the
compound option), the holder chooses to acquire the stock or otherwise.
The decision depends on whether the stock as a call on the firm value is
more valuable than the strike price.

Attached is a sample matlab code computing the value of a compound


call option with the Black-Scholes pricing model using Geske's analytic
formulas.

Click to download
Tags - compound , option

Please read update at http:://www.mathfinance.cn 271


Credit card bailout
A review of credit card bailout.

It appears as if day-to-day at present that we hear about a government


bought at bailout of additional major company. Numerous smaller
commercial enterprise, as well as individual people, are left enquiring
where is their bailout from the dishonest loaning practices of the
depository financial institution and credit card corporations.

In recent years, consumers have been promoted to Apply Credit Card for
daily purchases, including groceries, fast food meals, and even the
morning cup of coffee en route to office. All of these purchases, in
addition the interest and fees appended, have only ramped up a huge
pile of debt for the ordinary cardholder.

This is not much unlike the debt built up by companies, who now bear
their hand out, calling for for help. And the government appears very
amenable to offer that help, at the long-run expense of the American
taxpayer.

There is nevertheless, a bailout of forms for personal credit card debt.


This isn't a government platform, no more taxpayer bucks are ill-used,
and you will not find out about it on the nightly news show. As a matter
of fact, there is really no money needed in this bailout. Through debt
elimination, a person can lawfully and entirely discharge 100% of their
debts from credit cards and consumer loan*. Totally without afresh loan,
subsidy, or government takeover.
Tags - credit , bailout

Please read update at http:://www.mathfinance.cn 272


CDS Standard Model
JP. Morgan has release its CDS pricing and analysis model code!

Quotation
The ISDA CDS Standard Model
The ISDA CDS Standard Model is a source code for CDS calculations
and can be downloaded freely through this website. The source code is
copyright of ISDA and available under an Open Source license.

Background
As the CDS market evolves to trade single name contracts with a fixed
coupon and upfront payment, it is critical for CDS investors to match the
upfront payment amounts and to be able to translate upfront quotations
to spread quotations and vice versa in a standardized manner.
Implementing the ISDA CDS Standard Model and using the agreed
standard input parameters will allow CDS market participants to tie out
calculations and thus improve consistency and reduce operational
differences downstream.

Besides the code for CDS, a Yield Curve Specifications PDF file about
how the yield curve is constructed and calculated is also available at the
webpage, enjoy!

http://www.cdsmodel.com/
Tags - cds , credit

Please read update at http:://www.mathfinance.cn 273


Modelling the implied volatility surface
The volatility surface implied by option prices presents a structure that
changes over
time. The aim of this paper is to present a framework to model the
implied volatility
of the FTSE options in real time, and to present a prototype application
that
implements this framework. The authors adapt the parametric models
presented in Dumas et
al (1998) to estimate the surfaces across moneyness instead of across
strikes, they
discuss how this framework can be used in applications of option pricing
and risk
management.

Paper and attached matlab/VB/mathematica codes:


http://www.amadeo.name/working_papers/
volatility_surface_may04.pdf
Tags - volatility , surface , smile

Please read update at http:://www.mathfinance.cn 274


Automatic Code Testing
Everyday you write your quantitative finance code, test the code, crash;
then modify it, test it, maybe crash again, and so on. Is there an
automatic testing tool doing these boring, repetitive procedures for you?
YES. Automatic Testing is a great tool to increase productivity and save
time. It helps you catch bugs early by allowing frequent retesting of your
code as you develop. This prevents code "regressing" in the sense of
reintroducing previously identified and fixed bugs in later updates to
your code.

Automatic Testing is made simple and quick through the use of unit
testing frameworks, the most popular amongst these is xUnit which has
implementations in most modern programming languages. For Matlab
we have a version of mlUnit available for your use. In python, pyUnit is
part of the standard library and is available as a standard package
unittest. For R there is RUnit.

Main Benefits:

much less time spent chasing bugs and debugging;


higher quality of code and software;
provides documentation of which functionality has been tested;
greater confidence to make changes to existing code since unit tests will
catch incompatibilities early.

Sounds nice? Downloading packages at:


http://mlunit.dohmke.de/Main_Page for Matlab
http://docs.python.org/library/unittest.html for Python
http://cran.r-project.org/web/packages/RUnit/index.html for R.

Tags - code , test

Please read update at http:://www.mathfinance.cn 275


Managing MATLAB Projects
Whenever I opened my m files with Matlab, I was tired of looking for
them one by one; the situation became worse for a big project with
dozens of small m files. You might argue what we can do is to save all
files of one project at a separated directory, well, that’s what I did, but
with the expanding of project, sub-projects are created and some files are
inter-correlated among those sub-projects. It therefore becomes
unrealistic to separate those files any more. Is there a project
management tool like Visual C++ does for cpp/hpp? mlProj is one good
application I recently found.

mlProj is a tool for managing MATLAB projects. It considers


• all opened m-files,
• all figure windows,
• the MATLAB path, and
• the MATLAB workspace,
which are saved when a project is closed, and loaded when the project is
opened. The projects are shown as a tree, which provides simple access
to directories and files of the active project. The features include
• add a new project,
• open, save and close projects,
• open files in the MATLAB editor,
• delete files, directories and projects,
• rename files and directories,
• reload the tree view, and
• add user-defined items to the mlProj menu.

downloading link and userguide are at:http://mlproj.dohmke.de/


Main_Page
Tags - matlab

Please read update at http:://www.mathfinance.cn 276


wavelet analysis
WaveLab is a collection of Matlab functions to implement a variety of
algorithms related to wavelet analysis. A partial list of the techniques
made available:

orthogonal and biorthogonal wavelet transforms,


translation-invariant wavelets,
interpolating wavelet transforms,
cosine packets,
wavelet packets,
matching pursuit,
......

downloading at http://www-stat.stanford.edu/~wavelab/
Wavelab_850/index_wavelab850.html
Tags - wavelet

Please read update at http:://www.mathfinance.cn 277


Historical Volatility Estimation
Dozens of ways to calculate historical volatility, let alone volatility (I
mean, implied volatility, stochastic volatility, for instance.). Here is the
MATLAB code that one could use to estimate historical volatility using
different methods

Historical Close-to-Close volatility


Historical High Low Parkinson Volatility
Historical Garman Klass Volatility
Historical Garman Klass Volatility modified by Yang and Zhang
Historical Roger and Satchell Volatility
Historical Yang and Zhang Volatility
Average of all the historical volatilities calculated above

Enjoy. http://tradingwithmatlab.blogspot.com/2008/06/estimate-
historical-volatility.html
Tags - volatility , stochastic

Please read update at http:://www.mathfinance.cn 278


Several matlab packages
Several matlab packages to download, including:

Complexity - for estimating various temporal and spatial signal


complexities
Denoising - for removing noise from signals
Kalman filter - for Kalman filter
Independent Components - for ICA based on `accelerated' covariant
algorithm (natural gradient)
Gaussian mixture models - for analysis of Gaussian mixture models for
data set clustering etc.
MinEnt clustering - for minimum-entropy (maximum certainty)
partitioning
Extreme Value Theory - for detecting novelty using extreme value theory

Publications also are at: http://www.robots.ox.ac.uk/~sjrob/Outgoing/


software.html

Tags - filter , extreme

Please read update at http:://www.mathfinance.cn 279


Generalized Linear Models in Matlab
glmlab is a free MATLAB toolbox for analysing generalized linear
models. glmlab can fit all types of generalized linear models, including
(among others):
multiple regression;
log-linear models;
logistic regression; and
weighted regression.

glmlab includes the following error distributions:


normal (Gaussian);
gamma;
inverse Gaussian;
Poisson; and
binomial.
You can also specify your own error distributions with just a little bit of
MATLAB programming.

http://www.sci.usq.edu.au/staff/dunn/glmlab/glmlab.html

Tags - regression

Please read update at http:://www.mathfinance.cn 280


Matlab implementation of cointegration tests
Matlab of the paper "Implementing Pesaran-Shin-Smith"

This first year paper is based on Pesaran et al. (2000) who generalise the
cointegration tests
introduced by Johansen to include exogenous I(1) variables in a VECM
model. It reiterates
the proofs for their central test statistics and presents them in a less
dense format: Following
Pesaran et al. (2000), this paper focuses on the derivation of the
corresponding cointegrating rank
tests, by first introducing a VAR model, subsequently deriving the
likelihood for the cointegration
parameters and, finally, the test statistics and their asymptotic
distributions. The final section
introduces tests on whether the required exogeneity restrictions hold. In
addition, this paper is
concerned with implementing the mentioned test statistics in a Matlab
routine.

Paper and Matlab code: http://www.zeugner.eu/arbeiten/tafel.php


Tags - cointegration

Please read update at http:://www.mathfinance.cn 281


Pattern Recognition Package
Pattern recognition is a sub-topic of machine learning. It is "the act of
taking in raw data and taking an action based on the category of the
data".Most research in pattern recognition is about methods for
supervised learning and unsupervised learning. another black-box as
neural network.

Pattern recognition aims to classify data (patterns) based either on a


priori knowledge or on statistical information extracted from the
patterns. The patterns to be classified are usually groups of
measurements or observations, defining points in an appropriate
multidimensional space. This is in contrast to pattern matching, where
the pattern is rigidly specified.

PRTools supplies about 200 user routines for traditional statistical


pattern recognition tasks. It includes procedures for data generation,
training classifiers, combining classifiers, features selection, linear and
non-linear feature extraction, density estimation, cluster analysis,
evaluation and visualisation. It is intended to aid students and
researchers in designing and evaluating new algorithms and in building
prototypes.

Matlab package and manual are available at http://www.prtools.org/


download.html
Tags - pattern

Please read update at http:://www.mathfinance.cn 282


Quant Trading Strategy Demo
A Quant Trading Strategy Demo, including:
CPPI (Constant Proportional Portfolio Insurance), OBPI (Option Based
Portfolio Insurance), DPE (Dynamic Protected Envelope) and DPAA
(Dynamic
Protected Asset Allocation)

Download at:

http://www.quantcode.com/modules/mydownloads/
visitwad.php?cid=9&lid=508
The underlying risky asset (can be equity or fixed income instruments)
are
simulated via general innovation processes with specification of
stochastic
volatility.

Note:

1. This is purely quant asset allocation strategy, it can be combined


with factor and fundamental analysis for more specific low-frequency
trading
strategies. Or it can be combined with statistical data mining techniques
for high-frequency trading strategies.

2. Explainations and some related VBA code will be published in:

http://www.weizhenstanford.com/blog
Tags - strategy

Please read update at http:://www.mathfinance.cn 283


Feedforward neural networks package
Some call it "probably the best feedforward neural networks package", I
can't gurantee it, however, as I know almost nothing about neural
network. Please help me write a review if you can, cheers.

The Netlab toolbox is designed to provide the central tools necessary for
the simulation of theoretically well founded neural network algorithms
and related models for use in teaching, research and applications
development.

It consists of a toolbox of Matlab® functions and scripts based on the


approach and techniques described in Neural Networks for Pattern
Recognition by Christopher M. Bishop, (Oxford University Press, 1995)

Download, overview and example are at http://www.ncrg.aston.ac.uk/


netlab/index.php.
Tags - neural-network

Please read update at http:://www.mathfinance.cn 284


Efficient maximum-likelihood estimation
% Fastfit Toolbox. Efficient maximum-likelihood estimation using
generalized
% Newton iterations.
% Version 1.2 19-May-04
% By Thomas P. Minka
%
% Dirichlet
% dirichlet_sample - Sample from Dirichlet distribution.
% dirichlet_logprob - Evaluate a Dirichlet distribution.
% dirichlet_fit - Maximum-likelihood Dirichlet distribution.
% dirichlet_fit_simple - Maximum-likelihood Dirichlet distribution.
% dirichlet_fit_newton - Maximum-likelihood Dirichlet distribution.
% dirichlet_fit_m - Maximum-likelihood Dirichlet mean.
% dirichlet_fit_s - Maximum-likelihood Dirichlet precision.
%
% Polya, a.k.a. Dirichlet-multinomial
% polya_sample - Sample from Dirichlet-multinomial (Polya)
distribution.
% polya_logprob - Evaluate a Dirichlet-multinomial (Polya)
distribution.
% polya_fit - Maximum-likelihood Polya distribution.
% polya_fit_ms - Maximum-likelihood Polya distribution.
% polya_fit_simple - Maximum-likelihood Polya distribution.
% polya_fit_s - Maximum-likelihood Polya precision.
% polya_fit_m - Maximum-likelihood Polya mean.
%
% Other
% gamma_fit - Maximum-likelihood Gamma distribution.
% negbin_fit - Maximum-likelihood Negative Binomial.
% inv_digamma - Inverse of the digamma function.
%
% test_dirichlet_fit,... Test scripts for above routines.

http://research.microsoft.com/en-us/um/people/minka/software/
fastfit/
Tags - mle

Please read update at http:://www.mathfinance.cn 285


Maximum likelihood estimation in R
Maximum likelihood estimation can be implemented like Quasi-
maximum likelihood in Matlab, You can also write an R function which
computes out the likelihood function. As always in R, this can be done in
several different ways.

One issue is that of restrictions upon parameters. When the search


algorithm is running, it may stumble upon nonsensical values - such as a
sigma below 0 - and you do need to think about this. One traditional
way to deal with this is to "transform the parameter space". As an
example, for all positive values of sigma, log(sigma) ranges from -
infinity to +infinity. So it's safe to do an unconstrained search using
log(sigma) as the free parameter.

For detail about methodology and sample codes see


http://www.mayin.org/ajayshah/KB/R/documents/mle/mle.html.
Tags - mle

Please read update at http:://www.mathfinance.cn 286


Merry Christmas
Merry Christmas to you all and happy 2009 new year.

Blog will take several days off.

Please read update at http:://www.mathfinance.cn 287


Newmat C++ matrix library
This C++ library is intended for scientists and engineers who need to
manipulate a variety of types of matrices using standard matrix
operations. Emphasis is on the kind of operations needed in statistical
calculations such as least squares, linear equation solve and eigenvalues.

It supports matrix types: Matrix (rectangular matrix);


UpperTriangularMatrix; LowerTriangularMatrix; DiagonalMatrix;
SymmetricMatrix; BandMatrix; UpperBandMatrix; LowerBandMatrix;
SymmetricBandMatrix; IdentityMatrix; RowVector; ColumnVector.

Only one element type (float or double) is supported.

The library includes the operations *, +, -, *=, +=, -=, Kronecker product,
Schur product, concatenation, inverse, transpose, conversion between
types, submatrix, determinant, Cholesky decomposition, QR
triangularisation, singular value decomposition, eigenvalues of a
symmetric matrix, sorting, fast Fourier and trig. transforms, printing and
an interface with Numerical Recipes in C.

Introduction and package downloading: http://www.robertnz.net/


nm_intro.htm
http://www.robertnz.net/download.html
Tags - matrix , library

Please read update at http:://www.mathfinance.cn 288


Free Mathematica Software for Stable Analysis
Stable densities in four different parameterizations:
S(α,β,γ,δ;0) parameterization (top left), the "standard" S(α,β,γ,δ;1)
parameterization (top right), S(α,β,γ,δ;2) parameterization (bottom left),
S(α,β,γ,δ;3) parameterization (bottom right). The values of α are
indicated on the plots, skewness is indicated by color: β=0 (black), β=0.25
(red), β=0.5 (green), β=0.75 (yellow), β=1 (blue). In all cases, scale γ=1
and location δ=0. Note the discontinuity in the standard
1-parameterization near alpha=1.

download stable distribution software at http://www.mathestate.com/


tools/Financial/sw/Software.html
Tags - stable , distribution

Please read update at http:://www.mathfinance.cn 289


Extra moments measure
The following functions are intended to replicate calculations for taking
higher moments of hedge fund returns into account in analyzing
particular investments. Most of the formulae are taken from various
EDHEC research papers.

# All returns are assumed to be on a monthly scale!

functions including:

# moment.third
# moment.fourth
# CoSkewness
# CoKurtosis
# BetaCoVariance
# BetaCoV (wrapper for BetaCoVariance)
# SystematicBeta (wrapper for BetaCoVariance)
# BetaCoSkewness
# BetaCoS (wrapper for BetaCoSkewness)
# SystematicSkewness (wrapper for BetaCoSkewness)
# BetaCoKurtosis
# BetaCoK (wrapper for BetaCoKurtosis)
# SystematicKurtosis (wrapper for BetaCoKurtosis)
# VaR
# VaR.Beyond
# VaR.column
# VaR.CornishFisher
# VaR.Marginal
# modifiedVaR (wrapper for VaR.CornishFisher)

http://braverock.com/brian/R/extra_moments.R
Tags - moment , portfolio

Please read update at http:://www.mathfinance.cn 290


Implementation of Skew Normal/Student t distributions
SKEW is a Gauss library for computing pdf, cdf and inverse of the cdf
and simulating random numbers for the SN, ST, MSN and MST
distribution functions described in Azzalini, A. and Capitanio A.[2003],
Distributions generated by perturbation of symmetry with emphasis on
a multivariate skew t distribution, JRSS B, 65, 367-389.

Check A Gauss implementation of Skew Normal/Student distributions


at http://www.thierry-roncalli.com/#gauss
Tags - distribution , skew

Please read update at http:://www.mathfinance.cn 291


Functions for portfolio analysis
Functions include:
1. efficient.portfolio compute minimum variance portfolio subject to
target return
2. globalMin.portfolio compute global minimum variance portfolio
3. tangency.portfolio compute tangency portfolio
4. efficient.frontier computer Markowitz bullet

http://faculty.washington.edu/ezivot/econ483/portfolio.ssc

Tags - markowitz , splus

Please read update at http:://www.mathfinance.cn 292


Convert Splus to R
Suppose you have got used to Splus and want to switch to R software
(why bother to change? R is free while Splus is not, fair enough?), what
can you do? since there are many functions in S-PLUS that are missing in
R, one way is to understand the functions and write your owns, working
N hours without sleep (N>?). however, you can avoid doing like that if
you are as headche as me whenever you think of this solution. There is a
package named Splus2R, which is to facilitate the conversion of S-PLUS
packages to R packages, this package provides some missing S-PLUS
functionality in R.

I have not tested the package, though, will update later. Here is
downloading link: http://cran.r-project.org/web/packages/splus2R/
index.html.
Tags - splus , r

Please read update at http:://www.mathfinance.cn 293


Extract Market Expectations from Financial Instruments
A Choosy review of recently techniques to extract information about
market expectations from asset values for monetary policy uses.
Traditionally, interest rates and forward exchange rates have been
applied to extract expected returns of future interest rates, exchange
rates and inflation. More lately, these ways have been polished to rely on
implied forward interest rates, and then to extract expected future time-
paths. Very recently, methods have been studied to extract not only the
mean returns but the whole (risk neutral) probability distribution from a
set of option prices.

Matlab files: http://home.datacomm.ch/paulsoderlind/Software/


Software.html#MatLabScripts
Tags - distribution

Please read update at http:://www.mathfinance.cn 294


Grouped T copula simulation and estimation
Copula is widely applied to model the dependence of multivariate
variable, two popula implicit copulas are Gaussian copula and T copula,
however, tail dependence under Gaussian copula is asymptotically equal
to zero, which is unrealistic and under-estimate the co-movement of
variables, especially in extreme market situation nowdays; T copula, on
the other hand, has a global degree of freedom to decide largely the
dependence structure, which is over-simple, for instance, risk manager
might want to define different degree of freedom for different markets
due to their special risk profile. Grouped-T copula was created to
overcome this problem, where seperated degree of freedom can be set
for each subgroup. sample code is here: http://economia.unipv.it/
pagp/pagine_personali/dean/programs/gruped_t_copula_simul_est
Tags - copula

Please read update at http:://www.mathfinance.cn 295


Mean-variance portfolio optimization
Quotation
We seek to try out ga and patternsearch functions of the Genetic
Algorithm and Direct Search Toolbox. We consider the unconstrained
mean-variance portfolio optimization problem, handled by portopt and
portalloc of the Financial Toolbox - note that in absence of constraints
other than sum(w) = 1, the problem admits a simple closed-form analytic
solution - and see whether ga and patternsearch succeed at locating the
optimal portfolio identified by portalloc.

http://www.mathworks.com/matlabcentral/fileexchange/16884

Tags - optimization , markowitz

Please read update at http:://www.mathfinance.cn 296


Asymmetric Power Distribution
Asymmetric Power Distribution (APD) family of densities extends the
Generalized Power Distribution to cases where the data exhibits
asymmetry.

It contains the asymmetric Gaussian and Laplace densities as special


cases.

In the paper entitled "Asymmetric Power Distribution: Theory and


Applications to Risk Measurement", the author provide a detailed
description of the properties of an APD random variable, such as its
quantiles and expected shortfalls.

http://econ.ucsd.edu/~ikomunje/code.htm to download "Asymmetric


Power Distribution: Theory and Applications to Risk Measurement" and
Matlab code files.
Tags - distribution , asymmetric

Please read update at http:://www.mathfinance.cn 297


Spatial Statistics Toolbox for Matlab
Historically, it has been difficult to apply spatial statistics to large
datasets (e.g., more than 10,000 observations). This site contains public
domain spatial software written in Matlab (Matlab Spatial Statistics
Toolbox 2.0) capable of estimating very large spatial autoregressions
(e.g., one example involves 1,000,000 observations). The spatial software
uses sparse matrix methods to compute the matrix determinants
employed in the maximum likelihood estimation of the spatial
autoregressions. Specifically, the software can estimate simultaneous
spatial autoregressions (SAR), conditional spatial autoregressions (CAR),
mixed regressive spatially autoregressive (MRSA) estimates as well as
other lattice models which are the mainstay of spatial econometrics.
Version 1.1 contained routines for specifying dependence via nearest
neighbors or contiguity, exact log-determinant computations, and closed
form maximum likelihood estimation of closest neighbor dependence.

Check http://www.spatial-statistics.com/ for downloading.


Tags - matlab , statistics

Please read update at http:://www.mathfinance.cn 298


Generate random numbers of stable distribution
A deluging section of the research in financial markets is established on
the presumption that financial markets are forced by a gaussian process.
This presumption has been largely debated, and it has often been
demonstrated than it's untrue for equity, forex, and commodities
markets. Stable distributions have been advised as a better model
instead.

Nevertheless, stable distributions are not applied much in the


industry due to a lack of proper interpreting and usable software
package. The lack of analytical formulas for the probability density and
cumulative distribution functions is also a reason.

For codes and research results of stable distribution click


http://dimacs.rutgers.edu/~graham/code.html
Tags - stable , distribution

Please read update at http:://www.mathfinance.cn 299


A Simple Trick to Avoid Oscillation in Binomial Trees
Derivative price can be calculated either by analytic formula like Black
Scholes model, or by numerical solution, for instance, solving paritial
difference equation, Monte carlo simulation, binomial tree, etc. A lot of
people are not aware of this simple trick to avoid oscillation in binomial
trees. Oscillation might become dangerous when calculating Greeks via
numerical differentiation. Here's the trick. E.g., for American options,
just replace the last step in the binomial tree with the closed-form Black-
Scholes formula.

http://leippold.googlepages.com/matlab for details.


Tags - tree , binomial

Please read update at http:://www.mathfinance.cn 300


Kernel density estimation
One of widely applied non-parametric density estimation methods. Fast
and accurate state-of-the-art bivariate kernel density estimator with
diagonal bandwidth matrix. The kernel is assumed to be Gaussian. The
two bandwidth parameters are chosen optimally without ever using/
assuming a parametric model for the data or any "rules of
thumb". Unlike many other procedures, this one is immune to accuracy
failures in the estimation of multimodal densities with widely separated
modes.

http://www.mathworks.com/matlabcentral/fileexchange/17204
Tags - kernel , density

Please read update at http:://www.mathfinance.cn 301


OptionCity Calculator
Key Benefits of the OptionCity Calculator

* Flexible models with stochastic volatility and stock price jumps


* Option prices with Greeks (sensitivity to parameters)
* Realistic Smile charts
* Fast evaluations
* Self-validating results. (You validate calculations by selecting a
different numerical method: Lattice, Series, or Monte Carlo)

The program is a downloadable executable for MS Windows systems:


http://www.optioncity.net/calculator.htm

Tags - calculator , option

Please read update at http:://www.mathfinance.cn 302


Simulation of Heston model
Generates Heston stochastic volatility process at various frequencies,
% ds = mu dt Vt^1/2 dW_1t
% dVt = b(a-Vt) dt sig Vt^1/2 dW_2t
% Corr( dW_1t, dW_2t )=rho
% S0 is starting value of price proces
% NbD corresponds to numbers of days

http://www.hec.unil.ch/matlabcodes/option_pricing.html

Tags - heston

Please read update at http:://www.mathfinance.cn 303


Uniform Random Number Generator
Uniform Random number is crucial for Monte Carlo simulation, some
famous uniform random number generators are Halton sequence and
Sobol sequence. Normal random number can be simulated then by
inverse normal cumulative function, for instance, Peter J Acklam inverse
normal cumulative distribution or Beasley-Springer-Moro inverse
normal.

UNIFORM is a Mathematica library which return a sequence of


uniformly distributed pseudorandom numbers.

The fundamental underlying random number generator in UNIFORM is


based on a simple, old, and limited linear congruential random number
generator originally used in the IBM System 360.

For detail and several language version pls click


http://people.scs.fsu.edu/~burkardt/math_src/uniform/uniform.html.
Tags - simulation , monte carlo

Please read update at http:://www.mathfinance.cn 304


Feedforward Neural Networks and Lyapunov Exponents
Estimation
This program, NETLE.EXE, estimates feedforward neural network
models and computes Lyapunov exponents (LE). Neural networks are
estimated by the method of nonlinear least squares (NLS) (Kuan and Liu
(1995)); Lyapunov exponents are calculated from the derivative matrices
of estimated network models (Gencay and Dechert (1992)). Note that a
positive Lyapunov exponent indicates that the underlying series is
chaotic.

REFERENCES:

Kuan, Chung-Ming and Tung Liu (1995). "Forecasting exchange rates


using feedforward and recurrent networks", Journal of Applied
Econometrics, forthcoming.

Gencay, Ramazan and W. D. Dechert (1992). "An algorithm for the n


Lyapunov exponents of an n-dimensional unknown dynamical system",
Physica D, 59, 142-157.

http://www.sfu.ca/~rgencay/lyap.html

Tags - neural-network

Please read update at http:://www.mathfinance.cn 305


Estimation of parameters and eigenmodes of multivariate
autoregressive models
ARfit is a collection of Matlab modules for

* estimating parameters of multivariate autoregressive (AR) models,


* diagnostic checking of fitted AR models, and
* analyzing eigenmodes of fitted AR models.

the package is based on the following two paper:


A. Neumaier and T. Schneider, 2001: Estimation of parameters and
eigenmodes of multivariate autoregressive models. ACM Trans. Math.
Softw., 27, 27–57.

T. Schneider and A. Neumaier, 2001: Algorithm 808: ARfit - A Matlab


package for the estimation of parameters and eigenmodes of
multivariate autoregressive models. ACM Trans. Math. Softw., 27, 58–65.

Paper and Package are at http://www.gps.caltech.edu/~tapio/arfit/


#files.
Tags - autoregressive

Please read update at http:://www.mathfinance.cn 306


Interest Rate Modeling in Excel
Interest Rate Modeling including:

Nelson Siegel Yield Curve Model


Nelson Siegel Yield Curve Model with Svensson 1994 Extension
One-Factor Interest Rate Models (Vasicek. Cox, Ingersoll & Ross)
Interest Rate Trinomial Tree - Hull & White Method

http://www.mngt.waikato.ac.nz/kurt/frontpage/modelmainpages/
InterestRateModels.htm
Tags - yield

Please read update at http:://www.mathfinance.cn 307


Multivariate dependence with copulas
Classes (S4) of commonly used copulas including elliptical (normal and
t), Archimedean (Clayton, Gumbel, Frank, and Ali-Mikhail-Haq),
extreme value (Husler-Reiss and Galambos), and other families (Plackett
and Farlie-Gumbel-Morgenstern). Methods for density, distribution,
random number generation, bivariate dependence measures, perspective
and contour plots. Functions for fitting copula models. Independence
tests among random variables and random vectors. Serial independence
tests for univariate and multivariate continuous time series. Goodness-
of-fit tests for copulas based on multipliers and on the parametric
bootstrap.

R package can be downloaded at http://cran.r-project.org/web/


packages/copula/index.html
Tags - copula

Please read update at http:://www.mathfinance.cn 308


Extreme Value Analysis in Matlab
EVIM: A Software Package for Extreme Value Analysis in MATLAB

Quotation
From the practitioners’ point of view, one of the most interesting
questions that tail studies can answer is what are the extreme
movements that can be expected in financial markets? Have we already
seen the largest ones or are we going to experience even larger
movements? Are there theoretical processes that can model the type of
fat tails which come out of our empirical analysis? Answers to such
questions are essential for sound risk management of financial
exposures. It turns out that we can answer these questions within the
framework of the extreme value theory. This paper provides a step-by-
step guideline for extreme value analysis in the MATLAB environment
with several examples.

paper and code can be downloaded at http://www.sfu.ca/~rgencay/


evim.html.
Tags - extreme

Please read update at http:://www.mathfinance.cn 309


Primitive polynomials for Sobol sequences
Quasi monte carlo method is popular for derivative pricing, Sobol
sequences is among the most widely-used low-discrepancy sequences,
and most efficient one I have ever used. The biggest challenge for
generating sobol sequences is to construct primitive polynomials, here is
a Mathematic file showing the algorithm to construct primitive
polynomials for multi-dimensional Sobol sequences , have fun.

http://leippold.googlepages.com/matlab
Tags - sobol , simulation

Please read update at http:://www.mathfinance.cn 310


Modeling Financial Time Series with S-PLUS
Although S-plus is the most terrible language I have ever used in terms
of debugging (I have to say that, no offense to S-plus fans, as my
colleagues said, it is hard to understand it is still existed in 21 centuary), I
found the S-plus scripts accompanying the book Modeling Financial
Time Series with S-PLUS, covering:

Time Series Manipulation, Time Series Concepts, Unit Root


Tests, Modeling Extreme Values, Time Series Regression, Univariate
GARCH, Long Memory, Rolling Analysis, Systems of Regression
Eqations, VAR Models, Cointegration, Factor Models, Term Structure,
Copulas, Generalized Method of Moments, etc.

For detail please download at http://faculty.washington.edu/ezivot/


MFTS2ndEditionScripts.htm
Tags - s-plus

Please read update at http:://www.mathfinance.cn 311


Yield Curve Modelling
Exponentials, Polynomials, and Fourier Series: More Yield Curve
Modelling at the Bank of Canada, where the authors used Cubic-spline,
B-spline and MLES spline curve to model interest rate curve, including a
penalty in the generalized least-squares objective function.

Interested ppl can refer to the PDF document and Matlab codes are at
appendix. http://www.bankofcanada.ca/en/res/wp/2002/
wp02-29.html
Tags - matlab , yield

Please read update at http:://www.mathfinance.cn 312


Online derivative calculator
An online derivative calculator covers:

Bond Price Volatility: duration(s), convexity, immunization;


Term Structure: yield curve, spot rate, forward rate, term structure
theories
Option Pricing: Black-Scholes, binomial, European, American
Numerical Greeks (& Some Latin): delta, gamma, vega, theta
Option Applications & Exotic Options: Corporate securities, barrier,
Asian, lookback, Parisian option,compound, exchange, etc.
futures, forward, futures option, swap
Monte Carlo & Quasi-random: variance reduction, Brownian bridge,
Halton-, Sobel-, Faure-sequences
GARCH option pricing model:multinomial tree, Monte Carlo
Interest Rate Models: lognormal, Vasicek, CIR, BDT, Hull-White, HJM
Mortgage-backed Securities: prepayment, PSA, CPR, SMM, pass-
through, CMO, stripped MBS, ARM, prepayment model, seq. CMO, PO/
IO, PAC, option-adjusted spread, cash flow, duration
convertible bond, callable & put bond, option-adjusted spread
...

http://www.csie.ntu.edu.tw/~lyuu/Capitals/capitals.htm
Tags - calculator , derivative

Please read update at http:://www.mathfinance.cn 313


VaR and Expected shortfall under Generalized Student t
Value at risk (VaR) is the expected maximum loss an asset or a portfolio
can incur over a target horizon within a given confidence level; Expected
Shortfall (ES), also called Conditional tail expectation (CTE), is the
expectation of the losses bigger (that is, worse) than VaR over a target
horizon within a given confidence level. There are several methods in
calculating VaR, including Historical simulation, Monte Carlo
simulation, and parametric method, dozens of underlying distributions
are ready for choice when using Monte Carlo simulation and Parametric
method, among which Gaussian distribution is, undoubtedly the most
popular one, t-distribution is also widely used due to its ability to
capture fat-tail.

A sample Matlab code to construct the Generalized Student t over a


given support then compute quantiles and numerical expected shortfall
is http://www.hec.unil.ch/matlabcodes/Econometrics/TestGTdens.m.

Tags - var , es , t

Please read update at http:://www.mathfinance.cn 314


Quantitative Risk Management R package
I shared an Econometric tools for performance and risk analysis package
in R, today I introduce another Quantitative Risk Management R
package, which is accompanying the book Quantitative Risk
Management: Concepts, Techniques and Tools by Alexander J. McNeil,
Rudiger Frey and Paul Embrechts, a nice book written by one of my
professors. In this book special care is given to Copula analysis, Extreme
value thoey, credit risk analysis, etc. Given the fact it was ranked by one
of the top 10 most technical books of the year 2007, i bet you will learn a
lot from it.

R-language version can be downloaded at http://cran.r-project.org/


web/packages/QRMlib/index.html and S-PLUS library to accompany
book is at http://www.ma.hw.ac.uk/~mcneil/book/index.html.
Tags - risk

Please read update at http:://www.mathfinance.cn 315


Levenberg-Marquardt nonlinear least squares algorithms
In mathematics and computing, the Levenberg–Marquardt algorithm (or
LMA) provides a numerical solution to the problem of minimizing a
function, generally nonlinear, over a space of parameters of the function.
These minimization problems arise especially in least squares curve
fitting and nonlinear programming.

The Levenberg-Marquardt algorithm has proved to be an effective and


popular way to solve nonlinear least squares problems. MINPACK-1
contains Levenberg-Marquardt codes in which the Jacobian matrix may
be either supplied by the user or calculated by using finite differences.
IMSL , MATLAB , ODRPACK , and PROC NLP also contain Levenberg-
Marquardt routines.

The algorithms in ODRPACK solve unconstrained nonlinear least


squares problems and orthogonal distance regression problems,
including those with implicit models and multiresponse data.

For detail about Levenberg-Marquardt nonlinear least squares


algorithms introduction and code pls click http://www.ics.forth.gr/
~lourakis/levmar/
Tags - levenberg-marquardt , optimization

Please read update at http:://www.mathfinance.cn 316


Newey and West Covariance Matrix Estimator
Covariance matrix is vital for pricing and risk analysis, before I shares a
Matlab code on weighted covariance matrix computation, here is another
method named Newey & West covariance matrix, which calculates the
covariance matrix with a non-parametrical method. Choices of kernels
include Bartlett, Truncated and Quadratic Spectral. An example program
also demonstrates how to use of these procedures. For detail please refer
to http://kafuwong.econ.hku.hk/research/gausscode/cov1.htm.
Tags - covariance

Please read update at http:://www.mathfinance.cn 317


Calibrating the Ornstein-Uhlenbeck model
Ornstein-Uhlenbeck model is widely used to model interest rate, two
popular types are Vasicek and CIR, here the author describes two
methods for calibrating the model parameters of an Ornstein-Uhlenbeck
process to a given dataset.

* The least squares regression method


* maximum likelihood method

methdology applied and sample matlab code are at


http://www.sitmo.com/doc/Calibrating_the_Ornstein-
Uhlenbeck_model.
Tags - yield , calibration

Please read update at http:://www.mathfinance.cn 318


Econometrics Software
Dozens of Matlab code for Econometrics study, including:

Brock, Dechert& Scheinkman (1986) test for independence based on the


correlation dimension

Significance level of the BDS statistic in small samples

Geweke &Porter-Hudak (1983) estimation of fractional differencing


parameter

Heteroskedasticity-consistent variance-ratio evaluationfor any q spacing

Engle's(1982) test for ARCH

Box-Pierce(1970) Q test using Ljung & Box's (1978) finite-sample


correction

Phillips-Perron test of the unit-root hypothesis in a Dickey-Fuller


regression

Durbin h statistic and significance of the hypothesis of no serial


correlation

Durbin-Watson d-statistic and significance level for the null hypothesis:


DW = 2

http://ww61.tiki.ne.jp/~kanzler/
index.htm#L.%20Kanzler:%20Software
Tags - econometrics

Please read update at http:://www.mathfinance.cn 319


Black Litterman Portfolio Allocation
Quotation
The Black Litterman model was first published by Fischer Black and
Robert Litterman of Goldman Sachs in an internal Goldman Sachs Fixed
Income document in 1990. This paper was then published in the Journal
of Fixed Income in 1991. A longer and richer paper was published in
1992 in the Financial Analysts Journal (FAJ). The latter article was then
republished by FAJ in the mid 1990's. Copies of the FAJ article are
widely available on the Internet. It provides the rationale for the
methodology, and some information on the derivation, but does not
show all the formulas or a full derivation. It also includes a rather
complex worked example, which is difficult to reproduce due to the
number of assets and use of currency hedging.

The Black Litterman model makes two significant contributions to the


problem of asset allocation. First, it provides an intuitive prior, the
CAPM equilibrium market portfolio, as a starting point for estimation of
asset returns. Previous similar work started either with the
uninformative uniform prior distribution or with the global minimum
variance portfolio. The latter method, described by Frost and Savarino
(1986) and Jorion (1986), took a shrinkage approach to improve the final
asset allocation. Neither of these methods has an intuitive connection
back to the market,. The idea that one could use 'reverse optimization' to
generate a stable distribution of returns from the CAPM market portfolio
as a starting point is a significant improvement to the process of return
estimation.

Second, the BlackLitterman model provides a clear way to specify


investors views and to blend the investors views with prior information.
The investor's views are allowed to be partial or complete, and the views
can span arbitrary and overlapping sets of assets. The model estimates
expected excessreturns and covariances which can be used as input to an
optimizer. Prior to their paper, nothing similar had been published. The
mixing process had been studied, but nobody had applied it to the
problem of estimating returns. No research linked the process of
specifying views to the blending of the prior and the investors views.
The BlackLitterman model provides a quantitative framework for
specifying the investor's views, and a clear way to combine those

Please read update at http:://www.mathfinance.cn 320


investor's views with an intuitive prior to arrive at a new combined
distribution.

For a collection of reference paper and an online application please see


http://www.blacklitterman.org/blapplet.html
Tags - allocation , black-litterman

Please read update at http:://www.mathfinance.cn 321


Hull-White Term Structure Model
Accompanying Excel of "Implementation of Hull White's No-Arbitrage
Term Structure Model" by Eugen Puschkarski, including:

HEDGE.XLS: Calculation of hedge parameters


CALIBRAT.XLS: Calibration of the model to market data, calculation of
optimal volatility parameters
AMERICAN.XLS: Valuation of American style option
CALLABLE.XLS: Valuation of callable, putable bonds
CAP.XLS: Valuation of Caps and Floors, comparison of analytical and
numerical solution
COUPON.XLS: Pricing of an option on a coupon bond
BINARY.XLS: Valuation of binary options of an accrual swap
CONVERG2.XLS: Analysis of convergence behaviour of the numerical
solution
CONVERG3.XLS: Analysis of convergence behaviour if cash flows
between nodes do occur
FLOATER1.XLS: Valuation of standard and non-standard floater
NUM.XLS: Numerical valuation of zero coupon bond options
SWAP.XLS: Calculation of swaptions

Paper and Excel file can be found at http://www.angelfire.com/ny/


financeinfo/research.html
wiki(Hull-White model)
Tags - hull-white , yield

Please read update at http:://www.mathfinance.cn 322


Fourier Space Time-stepping (FST) option calculator
Online Fourier Space Time-stepping (FST) option calculator where
options class includes European, American, Barrier, Shout and Spread
option; underlying stock process follows Black Scholes Merton, Merton
Jump Diffusion, Kou Jump Diffusion, Variance Gamma, Normal Inverse
Gaussian and CGMY.

For more information on the Fourier Space Time-stepping (FST) method,


stock price models and options refer to the papers below at the site
http://128.100.73.155/fst/.

Papers:

* Option Pricing with Regime Switching Levy Processes Using Fourier


Space Time-stepping
* Fourier Space Time-stepping for Option Pricing with Levy Models.

Related Matlab codes can also be downloaded at


http://www.cs.toronto.edu/~vsurkov/fst_matlab.html
Tags - calculator , derivative , option

Please read update at http:://www.mathfinance.cn 323


Nearest correlation matrix
Correlation matrix exists almost everywhere for derivative pricing and
risk management, especially when Monte Carlo simulation is applied,
for instance, to simulate correlated random numbers via Cholesky
decomposition of correlation matrix. However, one strong requirement
of Cholseky decomposition on correlation matrix is positive semi-
definite, in other words, eigenvalues must be positive. Another example
of positive semi-definite correlation matrix requirement is for risk
management measurement, otherwise the volatility calculated might be
negative, which is non-acceptable.

In practice, sometimes we need to change correlation matrix to our


forecasting values, even minor change might lead to invalid matrix, for
this problem, http://www.maths.manchester.ac.uk/~nareports/
narep369.pdf details the way to overcome it, accompanying Matlab code
can also be found at http://www.maths.manchester.ac.uk/~clucas/
near_cor.m and http://www.maths.manchester.ac.uk/~clucas/
eig_mex.c.
Tags - correlation , cholesky

Please read update at http:://www.mathfinance.cn 324


MySQL and Matlab
The MySQL database server is very popular for its openness, robustness,
and speed. Matlab is a wonderful commercial product for scientific and
technical computing. Using them together is a great tool for quantitative
data analysis. You can do this using the Matlab Database Toolbox, but it
is more efficient to connect directly using the APIs for both products.
This code implements that connection, with a fairly rich framework for
handling data conversion, especially dates and times.

http://cims.nyu.edu/~almgren/mysql/
Tags - matlab , sql

Please read update at http:://www.mathfinance.cn 325


Rmetrics - Basics of Option Valuation
Open Source Software for Financial Engineering and Computational
Finance

Rmetrics is the premier open source solution for teaching financial


market analysis and valuation of financial instruments. With hundreds
of functions build on modern methods Rmetrics combines explorative
data analysis, statistical modeling and rapid model prototyping. The
Rmetrics Packages are embedded in R building an environment which
creates for students a first class system for applications in statistics and
finance.

Download at http://cran.cnr.berkeley.edu/web/packages/fOptions/
index.html
Tags - r , option

Please read update at http:://www.mathfinance.cn 326


Singular Value Decomposition
In linear algebra, the singular value decomposition (SVD) is an
important factorization of a rectangular real or complex matrix, with
several applications in signal processing and statistics. Applications
which employ the SVD include computing the pseudoinverse, least
squares fitting of data, matrix approximation, and determining the rank,
range and null space of a matrix.

Singular Value Decomposition to solve ill conditioned square matrices.

Excel, C++ Add-in and Demo Spreadsheet with application manual and
on-line help are at http://www.financial-risk-manager.com/risks/
analytics/multivar/an_mv_t.html#svd

wiki(Singular value decomposition)


Tags - svd , matrix

Please read update at http:://www.mathfinance.cn 327


Heston model pricing and calibration
Quotation

The Heston Model is one of the most widely used stochastic volatility
(SV) models today. Its attractiveness lies in the powerful duality of its
tractability and robustness relative to other SV models.

This project initially begun as one that addressed the calibration problem
of this model. Attempting to solve such a problem was an impossible
task due to the lack of exposure to such ‘advanced’ models.

I, therefore, decided to take a slight digression into the world of Heston


and stochastic volatility. Enroute I realised that fundamental information
that one would require to gain an intuitive understanding of such a
model was very disjoint and hence incomplete. This project, therefore,
evolved into something that could fill this gap.

A practical approach has been adopted since the focus of calibration is


quite practical itself. All the relevant tools are provided to facilitate this
calibration process, including MATLAB code. This code has been
confined to the appendix to keep the main body clutter free and ‘quick-
to-read’.

paper and code can be downloaded at http://web.wits.ac.za/NR/


rdonlyres/98E22C37-FA41-4C5B-8F11-F44BED5FF4C7/0/
nimalinmoodley.zip
Tags - heston

Please read update at http:://www.mathfinance.cn 328


MATLABroutines for risk and portfolio management
These routines support the book "Risk and Asset Allocation" Springer
Finance, by A. Meucci.

The routines include many new features:


- more uni-, multi- and matrix-variate distributions
- more copulas
- more graphical representations
- more analyses in terms of the location-dispersion ellipsoid.
- best replication / best factor selection
- FFT-based projection of a distribution to the investment horizon
- caveats about delta/gamma pricing
- step-by-step evaluation of a generic estimator
- non-parametric estimators
- multivariate elliptical maximum-likelihood estimators
- shrinkage estimators: Stein and Ledoit-Wolf, Bayesian classical
equivalent
- robust estimators: Hubert M, high-breakdown minimum volume
ellipsoid
- missing-data techniques: EM algorithm, uneven-series conditional
estimation
- stochastic dominance
- extreme value theory for VaR
- Cornish-Fisher approximation for VaR
- kernel-based contribution to VaR and expected shortfall from different
risk-factors
- mean-variance analysis and pitfalls (different horizons, compounded
vs. linear returns, etc...)
- Bayesian estimation (multivariate analytical, Monte Carlo Markov
Chains, priors for correlation matrices)
- estimation risk evaluation: opportunity cost of estimation-based
allocations
- Black Litterman allocation
- robust optimization (calls SeDuMi to perform cone programming)
- robust Bayesian allocation
- more...

sample chapter and codes can be downloaded at


http://www.symmys.com/AttilioMeucci/Book/Downloads/

Please read update at http:://www.mathfinance.cn 329


Downloads
Tags - allocation

Please read update at http:://www.mathfinance.cn 330


Code search portal
Share two code search portal today, one is search Quant code, where
people can search code relative to quantitative finance, for instance,
Code Search example: Black Scholes matlab; the other one is R-project
search engine, specifically for R language programming users. Enjoy.

http://www.finmath.cn/

http://www.rseek.org/

Please read update at http:://www.mathfinance.cn 331


Bayesian Copula Selection
Matlab implementation of a method to select the 'best' copula among a
subset of copula families.

Based on theory published in : Huard, D., G. Évin, A.-C. Favre (2006),


Bayesian Copula Selection, Computational Statistics and Data Analysis,
COMSTA3137, vol. 51 (2), 809-822.

http://code.google.com/p/copula/
Tags - copula

Please read update at http:://www.mathfinance.cn 332


Multidimensional numerical integration
Most derivative pricing problems have finally come to solve integration
numerically, by Simpson, Monte Carlo simulation, etc., however, multi-
dimensional integration is time-consuming and prone to error, here I
share a Cuba library which offers a choice of four independent routines
for multidimensional numerical integration: Vegas, Suave, Divonne, and
Cuhre.
Quotation
Vegas is the simplest of the four. It uses importance sampling for
variance reduction, but is only in some cases competitive in terms of the
number of samples needed to reach a prescribed accuracy. Nevertheless,
it has a few improvements over the original algorithm and comes in
handy for cross-checking the results of other methods.

Suave is a new algorithm which combines the advantages of two popular


methods: importance sampling as done by Vegas and subregion
sampling in a manner similar to Miser. By dividing into subregions,
Suave manages to a certain extent to get around Vegas' difficulty to
adapt its weight function to structures not aligned with the coordinate
axes.

Divonne is a further development of the CERNLIB routine D151.


Divonne works by stratified sampling, where the partitioning of the
integration region is aided by methods from numerical optimization. A
number of improvements have been added to this algorithm, the most
significant being the possibility to supply knowledge about the
integrand. Narrow peaks in particular are difficult to find without
sampling very many points, especially in high dimensions. Often the
exact or approximate location of such peaks is known from analytic
considerations, however, and with such hints the desired accuracy can
be reached with far fewer points.

Cuhre employs a cubature rule for subregion estimation in a globally


adaptive subdivision scheme. It is hence a deterministic, not a Monte
Carlo method. In each iteration, the subregion with the largest error is
halved along the axis where the integrand has the largest fourth
difference. Cuhre is quite powerful in moderate dimensions, and is
usually the only viable method to obtain high precision, say relative
accuracies much below 1e-3.

Please read update at http:://www.mathfinance.cn 333


http://www.feynarts.de/cuba/

Tags - integration

Please read update at http:://www.mathfinance.cn 334


Econometric tools for performance and risk analysis
Quotation
Library of econometric functions for performance and risk analysis of
financial portfolios. This library aims to aid practitioners and researchers
in using the latest research in analysis of both normal and non-normal
return streams.

We created this library to include functionality that has been appearing


in the academic literature on performance analysis and risk over the past
several years, but had no functional equivalent in R. In doing so, we also
found it valuable to have wrapper functions for functionality easily
replicated in R, so that we could access that functionality using a
function with defaults and naming consistent with common usage in the
finance literature. The following sections cover Performance Analysis,
Risk Analysis (with a separate treatment of VaR), Summary Tables of
related statistics, Charts and Graphs, a variety of Wrappers and Utility
functions, and some thoughts on work yet to be done.

http://braverock.com/brian/R/PerformanceAnalytics/html/
PerformanceAnalytics-package.html
Tags - econometrics , performance , r

Please read update at http:://www.mathfinance.cn 335


Decomposing rating transition matrices
Spreadsheet for the calculation of:
- the diagonal decomposition MDM^-1
- the generating matrix A of the ratings process
- the time-dependent transition matrix P(t)

http://www.schonbucher.de/risk/index.html
spreadsheet http://www.schonbucher.de/risk/rating_case.xls
Tags - rating

Please read update at http:://www.mathfinance.cn 336


Collection of R codes
R-Cookbook.com is a collection of "recipes"--problems, solutions, and
working examples--contributed by the R community in order to share
code, promote the use of R, and make the learning process more efficient
for new users.

http://www.r-cookbook.com/

Please read update at http:://www.mathfinance.cn 337


OLS Regression with missing values
Excel provides a handy function called LINEST that allows the user to
make OLS regressions in an very quick and simple fashion.
Unfortunately, the function fails if some values are missing in the data.

Here is a small program that addresss this shortcoming. After installing


this add-in, you can simply say LINESTNA(...) instead of LINEST(...) and
the problem with the missing values is gone.

The program first extracts the rows that do not contain any missing
values, and then calls Excel's LINEST to perform the estimation with the
cleaned data. The data have to be organized column-wise.

http://www.wwz.unibas.ch/ds/abt/wirtschaftstheorie/personen/
yvan/software/#c6714
Tags - regression

Please read update at http:://www.mathfinance.cn 338


Crank-Nicholson finite difference solution of American
option
Crank-Nicolson for a European put was introduced before, to better
master this technique, i share another sample code using Crank-
Nicholson finite difference for American option.

BLSPRICEFDAM Black-Scholes put and call pricing for American


Options using the Crank-Nicholson finite difference solution of Black-
Scholes Partial differential equation. Note that this function returns an
approximate solution unlike the analytical solution (BLSPRICE)
SO is the current asset price, X is the exercise price, R is the risk-free
interest rate, T is the time to maturity of the option in years, SIG is the
standard deviation of the annualized continuously compounded rate of
return of the asset (also known as volatility), and Q is the dividend rate
of the asset. The default Q is 0. N denotes the number of discretization
points in the stock price domain, and M denotes the number of
discretization points in time domain used for the PDE solution.Try
increasing either of M or N to achieve greater efficiency.

lecture notes can be downloaded at http://www.cs.cornell.edu/Info/


Courses/Spring-98/CS522/home.html and matlab file
http://www.cs.cornell.edu/Info/Courses/Spring-98/CS522/content/
blspricefdam.m.
Tags - american , pde , option

Please read update at http:://www.mathfinance.cn 339


Career change
Arrived in London today, new job will start from tomorrow, the first few
weeks will be busy as i need to get used to the new life here.

I will try to update new code link as possible as i can. thx for your
support.

Please read update at http:://www.mathfinance.cn 340


Up-and-out call option by Monte Carlo
Another sample code of the book An Introduction to Financial Option
Valuation: Mathematics, Stochastics and Computation, read Crank-
Nicolson for put. This sample calculates a up-and-out call barrier option
via Monte Carlo simulation with antithetic variates.

An up and out call is a regular call option that ceases to exist if the asset
price reaches a barrier level, H, that is higher than the current asset price,
when H is less than or equal to K, the value of the up and out call is zero.

Code can be accessed here http://www.maths.strath.ac.uk/~aas96106/


ch21.m.
Tags - barrier , option

Please read update at http:://www.mathfinance.cn 341


Trinomial tree class for short rate model
This page comprises the code and items of a C++ class that could be
applied to construct a trinomial tree for the short rate. The tree matches
to the yield curve but not to the volatility. curve.

The programming code is grounded on the book "Implementing


Derivatives Models", page 260, Clewlow and Strickland, the code
specifies a C++ implementation of a tree object. By input a set of
parameters the class will form an array of nodes, each one corresponding
to a node on the tree. Currently the tree is matched to the underlying
interest rate curve, but not a vol. curve.

http://www.phineas.pwp.blueyonder.co.uk/TreeClass.htm
Tags - yield

Please read update at http:://www.mathfinance.cn 342


Variance swap hedging under Heston volatility
Calculate variance swap hedging portfolio under Heston vol model
using MC simulation. The strategy is discussed in Gatheral p.136 and
http://www.ederman.com/new/docs/gs-volatility_swaps.pdf.

The strategy works by exploiting the difference between percentage


differences and log differences. A percentage difference is expressed as
(S’ – S)/S or S’/S - 1. A log difference is log(S’) – log(S) or log(S’/S). Fore
more detail refer to http://math.nyu.edu/~atm262/files/fall06/
casestudies/a7/hestonvarswap.m and the above mentioned paper.
Tags - heston

Please read update at http:://www.mathfinance.cn 343


Vasicek Model calibration and simulation
Entries Vasicek estimation and Vasicek model in binomial tree
introduced how to estimate Vasicek model parameters, how to
implement Vasicek interest rate model in binomial tree, which can be
further used to price option on bonds, for instance. Here i share another
two excel files demonstrating how to calibrate a Vasicek model to a
given term structure and simulate Vasicek zero bond prices and the path
of the short rate.

Download at http://www.mathematik.uni-kl.de/~korn/korn2b.htm,
besides Vasicek short rate model, CIR, Dothan and Exponential Vasicek
are also included in one file.
Tags - vasicek

Please read update at http:://www.mathfinance.cn 344


Solving PDE implicit / explicit methods
Basically there are two types of finite difference methods: explicit finite
difference method and implicit finite difference method. Other types are
just the derivation of these two types, for example, Crank-Nicolson
method is an average of the explicit method and implicit method.

Two sample Matlab files to compare the performance of solving PDE via
implicit and explicit method. http://frontera.bu.edu/MathFn.html

wiki(Finite difference method)


Tags - pde

Please read update at http:://www.mathfinance.cn 345


Unified Asian Option Pricing
Asian options are securities with payoff which depends on the average
of the underlying stock price over certain time interval. Since no general
analytical solution for the price of the Asian option is known, a variety of
techniques have been developed to analyze arithmetic average Asian
options.

A simple and numerically stable 2-term partial differential equation


characterizing the price of any type of arithmetically averaged Asian
option is given. The approach includes both continuously and discretely
sampled options and it is easily extended to handle continuous or
discrete dividend yields.

The paper "Unified Asian Pricing", Risk, Vol. 15, No. 6, 113-116 and its
Mathematica nb file can be downloaded at
http://www.stat.columbia.edu/~vecer/.
Tags - asian , option

Please read update at http:://www.mathfinance.cn 346


Nearest Neighbour Algorithm to forecast Stock Prices
This is the algorithm involved on the use of the non-linear forecast of
asset's prices based on the nearest neighbour method.

The basic idea of the NN algorithm is that the time series copies it's own
past behavior, and such fact can be used for forecasting purposes. On the
zip file there are two functions: one is the univariate version of NN
(nn.m) and the other is the multivariate approach, also called
simultaneous NN (snn.m).

Quotation
The nearest neighbor method is defined as a non-parametric class of
regression. Its main idea is that the series copies its own behavior along
the time. In other words, past pieces of information on the series have
symmetry with the last information available before the observation on
t+1. Such way of capturing the pattern on the times series behavior is the
main argument for the similarity between NN algorithm and the
graphical part of technical analysis, charting.

The way the NN works is very different than the popular ARIMA model.
The ARIMA modeling philosophy is to capture a statistical pattern
between the locations of the observations in time. For the NN, such
location is not important, since the objective of the
algorithm is to locate similar pieces of information, independently of
their location in time. Behind all the mathematical formality, the main
idea of the NN approach is to capture a nonlinear dynamic of self-
similarity on the series, which is similar to the fractal dynamic of a
chaotic time series.

http://www.mathworks.com/matlabcentral/fileexchange/
loadFile.do?objectId=9396&objectType=file
Tags - forecast

Please read update at http:://www.mathfinance.cn 347


FFT computation of option prices
The Black-Scholes formula, one of the major breakthroughs of modern
finance, allows for an easy and fast computation of option prices. But
some of its assumptions, like constant volatility or log-normal
distribution of asset prices, do not find justification in the markets. More
complex models, which take into account the empirical facts, often lead
to more computations and this time burden can become a severe
problem when computation of many option prices is required, e.g. in
calibration of the implied volatility surface. To overcome this problem
Carr and Madan (1999) developed a fast method to compute option
prices for a whole range of strikes.

Fast Fourier transform (FFT) is applied for this purpose, the use of the
FFT is motivated by two reasons. On the one hand, the algorithm offers a
speed advantage. This effect is even boosted by the possibility of the
pricing algorithm to calculate prices for a whole range of strikes. On the
other hand, the cf of the log price is known and has a simple form for
many models considered in literature, while the density is often not
known in closed form.

Here is an sample Matlab file for FFT computation of option prices,


http://www.theponytail.net/CCFEA/lect01/lect01fftoptionnormal.m.
wiki(Fast Fourier transform)
Tags - fft , option

Please read update at http:://www.mathfinance.cn 348


Rank reduction of correlation matrices by majorization
Rank reduction is useful for multi-factor derivative pricing and risk
analysis, for instance, for a Bermudan swaption, Major, MajorW and
MajorPower are MATLAB templates that may be used to find a low-rank
correlation matrix locally nearest to a given correlation matrix, by means
of majorization. Major implements equal weights on the entries of the
correlation matrix. MajorW implements non-constant weights.

For an introductory of Rank reduction of correlation matrices by


majorization paper can be downloaded at http://www.pietersz.org/
majorization.pdf, with Matlab codes
http://www.pietersz.org/major.htm
Tags - correlation

Please read update at http:://www.mathfinance.cn 349


Option greeks analysis
A useful tool built to help the user gain an intuitive feel for option
pricing and the greeks.

Allows the user to create a portfolio of options (and thus straddles,


strangles, butterflies and anything else you fancy can be easily created
using the GUI).

Once this is done, the user can plot the option price, delta, gamma, vega
and variance vega in 3D and examine how they vary with time to
maturity, volatility, interest rates and carry.

It also allows you to perturb a 4th dimension also allowing you to create
an animation.

Type PlotMeTheGreeks() on the matlab command line to start the GUI.

http://www.mathworks.com/matlabcentral/fileexchange/
loadFile.do?objectId=10428&objectType=FILE
Tags - greeks , option

Please read update at http:://www.mathfinance.cn 350


Real option case study
Nth much to say, for those of you interested into applying real option
valuation model in real situation.

Doc file and Excel sheet can be downloaded here


http://faculty.fuqua.duke.edu/~charvey/Teaching/BA456_2002/
LogiTech/.
Tags - real-option , option

Please read update at http:://www.mathfinance.cn 351


Peter J Acklam inverse normal cumulative distribution
Random number generation is essential for Monte Carlo simulation,
among random numbers, normal distributed numbers are undoubtedly
the most widely used ones, here comes the problem, for a given uniform
random numbers series, how do you compute the inverse normal
cumulative distribution function?

I once introduced Moro inverse normal function for this purpose, here is
another power function named Peter J Acklam inverse normal
cumulative distribution, for my study and work i have tried both but
couldnot decide which one is better, here i quote the sentence from the
book "Monte carlo methos in finance" by Peter Jackel: Equally, for the
inverse cumulative normal function z = N'(p), there are several
numerical implementations providing different degrees of accuracy and
efficiency. A very fast and accurate approximation is the one given by
Boris Moro in [Mor95]. The most accurate whilst still highly efficient
implementation currently freely available, however, is probably the
algorithm by Peter Acklam. when allowing for an additional evaluation
of a machine-accurate cumulative normal distribution function,
Acklam’s procedure is able to produce the inverse cumulative normal
function to full machine accuracy by applying a second stage refinement
using Halley’s method.

Good, here is the page for Peter J Acklam inverse normal cumulative
distribution codes in several languages, http://home.online.no/
~pjacklam/notes/invnorm/index.html#The_algorithm, enjoy.
Tags - random , normal

Please read update at http:://www.mathfinance.cn 352


Numerical valuation of convertible bonds
A Convertible Bond (CB) is a hybrid derivative with complex embedded
features, it allows the holder to convert the bond to a certain shares
(conversion ratio) of stock issued by the same company at a prescribed
stock price (conversion price), besides this feature, CB normally has
embedded American call (put) option which allows the bond issuer
(holder) to call (sell) back the CB from holder (to issuer) at a pre-decided
call (put) price once the underlying stock price is above (below) strike
price for a certain prescribed, consecutive time, hereafter called Parisian
option; in Asian markets, CB also has a refix clause which allows the
bond issuer to reset the conversion price, under several stock price
scenarios; as a hybrid product with equity and fixed income
characteristics, CB is under default risk, both stochastic interest rate and
stochastic volatility play a role for its valuation; etc,.

The convertible bond calculator uses a binomial lattice with the stock
price as the only state variable to analyse convertible bonds with call and
put features. The software does not use the warrant valuation approach
which requires the volatility of equity (stocks plus warrants). Instead, it
ignores the dilution effect and uses stock price volatility which is more
readily available.
download at http://www.iimahd.ernet.in/~jrvarma/software/ecb.zip
online convertible bonds calculator http://www.iimahd.ernet.in/
~jrvarma/software/convertible.php, more are at
http://www.iimahd.ernet.in/~jrvarma/software.php.

Tags - convertible bond

Please read update at http:://www.mathfinance.cn 353


Spread option valuation
Spread option derives its value from the difference between the prices of
two or more assets, it can be considered as a type of rainbow option in
that it's payoff depends on 2 or 3 underlying assets. for instance, for a 2
underlying assets call spread option, the payoff is like max(S1 - S2 - K, 0),
where K is the strike price betting on the spread (or difference) of these
two stock prices. Spread option is widely used in energy industry,
especially in oil industry.

In previous entry how to price spread option with Monte Carlo


simulation was introduced, here is another valuation method of spread
options follwing the article Low-Fat Spreads by K. Ravindran, RISK, Oct
1993.

for detail check http://www.mathfinance.org/FF/cpplib.php。


Tags - spread , option

Please read update at http:://www.mathfinance.cn 354


Cliquet option with Jump-Diffusion Bates Model
Cliquet option, also called ratchet option, is an extended roll-down
option, with strikes set at the barriers, which never knock out
completely. It is a series of at the money options, with periodic
settlement, resetting the strike value at the then current price level, at
which time, the option locks in the difference between the old and new
strike and pays that out as the profit. The profit can be accumulated until
final maturity, or paid out at each reset date.

The Bates Model is a type of Jump-Difussion model that is able to


improve calibration results for short term options. The Bates Model
consists of Jumps processes built on top a Heston model.

http://www.javaquant.net/finalgo/BatesModel.html lists the C++ code


to price Cliquet options using the Log-Jump variant of the Bates model
with stochastic volatility.

wiki(Cliquet option)
Tags - cliquet , heston , option

Please read update at http:://www.mathfinance.cn 355


Arithmetic Game
One of my friends sent me an interesting site: Arithmetic game, (please
help us develop by submitting a site in your favorites), The Arithmetic
Game is a speed drill where you are given two minutes to solve as many
arithmetic problems as you can, problems including addition,
subtraction, multiplication, and division, for each problem answered
correctly you will get score, test how many scores you can achieve. The
highest score so far is 137, amazing...

http://zetamac.com/arithmetic/

This game helps me recall the exam I took for a quantitative trader
position several months ago, i failed
Tags - game

Please read update at http:://www.mathfinance.cn 356


Monte Carlo arithmetic average price Asian option
Today is the Chinese traditional Mid-Autumn Festival, also known as
the Moon Festival, which is used to celebrate the end of the summer
harvesting season, first of all, wish you happy everyday and achieve
what you want. A pic of Mooncake

Asian options are options where the payoff depends on the average price
of the underlying asset during at least some part of the life of the option.
The payoff from an average price call is max(Save - K, 0) where Save is
the average value of the underlying asset calculated over a
predetermined averaging period. Average price options are less
expensive than regular options.

Besides anti-thetic sampling method, control variate is another popular


way for variance reduction, given the condition we can find a good
proxy product, whose pricing formula is easy to get, in our case,
geometric average asian option is used as control variate for arithemetic
average asian option, here is a M file demonstrating Monte Carlo
simulation on an arithmetic average price Asian option using a
geometric average price Asian as control variate.

http://personal.strath.ac.uk/d.j.higham/ch22.m.
Tags - asian , option

Please read update at http:://www.mathfinance.cn 357


Constant Maturity Swap (CMS) option pricing
Constant maturity swap is a type of interest rate swap where the rate of
interest of any single leg is readjusted in a periodic manner in case of
market swap rate but not with the LIBOR (London Interbank Offered
Rate) or any other floating reference index rate. In other words, it may
also be said that the constant maturity swap actually allows the
purchasers to fix the duration of the received flows on a swap. Constant
maturity swap is also known as CMS. The Constant Maturity Swaps may
be of two types - Single Currency Swaps or Cross Currency Swaps.

Pricing of cms option and a cms floor using the generalized Black-
Scholes formula with a convexity adjustment Excel sample file:
http://www.finmath.net/spreadsheets/CMS%20Option.zip, at the
same page http://www.finmath.net/spreadsheets/ you can also find
pricing of swaption using the generalized Black-Scholes formula.

wiki(Constant maturity swap)

Tags - cms , option

Please read update at http:://www.mathfinance.cn 358


Normal Inverse Gaussian option pricer
Quotation
To price and hedge derivative securities, it is crucial to have a good
model of the probability distribution of the underlying product. The
most famous continuous-time model is the celebrated Black Scholes
model, which uses the Normal distribution to fit the log returns of the
underlying.

As we know from empirical research, one of the main problems with the
Black–Scholes model is that the data suggest that the log returns of
stocks/indices are not Normally distributed as in the Black–Scholes
model. The log returns of most financial assets do not follow a Normal
law. They are skewed and have an actual kurtosis higher than that of the
Normal distribution. Other more flexible distributions are needed.

Moreover, not only do we need a more flexible static distribution, but in


order to model the behaviour through time we need more flexible
stochastic processes (which generalize Brownian motion). Looking at the
definition of Brownian motion, we would like to have a similar,i.e. with
independent and stationary increments, process, based on a more
general distribution than the normal. However, in order to define such a
stochastic process with independent and stationary increments, the
distribution has to be infinitely divisible, such processes are called Lévy
processes, one example of such process is normal inverse gaussian
(NIG).

Normal Inverse Gauss option pricer (with Esscher transform correction),


Excel + DLL, and a Maple worksheet with short explanations can be
downloaded at http://www.axelvogt.de/axalom/
NIG_tiny_withDLL.zip, more are at the main page of author
http://www.axelvogt.de/axalom/index.html.

Tags - nig , option

Please read update at http:://www.mathfinance.cn 359


Mixed Integer Linear Programming (MILP) solver
Are you fed up with "linprog" or "fmincon" command in Matlab? do you
sometimes find the results violate your providing constraints while
Matlab says "condition satisfied", or sometimes you get a weird solution
while Matlab tells you "convergence successful", etc. (I am not saying
bad words about Matlab, I AM a fan of it, but if there is a better solution
for the given problem, why not at least try it?)

Optimization packages are widelyspread, here is a site i introduced,


optimization package. Several days ago a friend of mine sent me a link
about lp-solver, which is a Mixed Integer Linear Programming (MILP)
solver, convenient to use and highly efficient, cannot help sharing with
you all. (please submit your favorite code site if you happen to find one
and help others, thanx.)

The name itself tells you this package is for linear programming
problem, What is Linear Programming then? A Linear Program (LP) is a
problem that can be expressed as follows:

minimize cx
subject to Ax = b
x >= 0

where x is the vector of variables to be solved for, A is a matrix of known


coefficients, and c and b are vectors of known coefficients. The
expression "cx" is called the objective function, and the equations "Ax=b"
are called the constraints. LP is widely used for portfolio optimization,
for instance, to mimic the performance of an index, to minimize tracking
error of your portfolio, etc. Don't hesitate to try it yourself.

PS: lp-solver can be called as a library from different languages like C,


VB, .NET, Delphi, Excel, Java, ...It can also be called from AMPL,
MATLAB, O-Matrix, Scilab, Octave, R via a driver program. you will
find a way.

Download at http://lpsolve.sourceforge.net/5.5/.
Tags - optimization

Please read update at http:://www.mathfinance.cn 360


Pricing American Options
American options can be computed by several ways, to name a few:
binomial tree, Least square Monte Carlo simulation, numerically solving
PDE. Previously I share a PSOR code to calculate Linear
Complementarity Formulation problem when applying finite difference
or finite element for american option, here is a file including:
* GUI for pricing through CRR binormial tree
* Script for pricing with Finitie differences
* GUI for pricing via the Monte Carlo method of Longstaff and Schwartz
* Functions to implement all three methods

you'll have a clear picture in mind how to deal with American-type


options, enjoy.
http://www.mathworks.com/matlabcentral/fileexchange/
loadFile.do?objectId=16476&objectType=file.
Tags - american , lsm , option

Please read update at http:://www.mathfinance.cn 361


Bootstrapping interest rate curve
Bootstrapping is a technique for building a zero-coupon yield curve from
the prices of a set of coupon bonds through forward replacement.

Using these zero-coupon bonds we can deduce forward and spot rates
for all time to maturities by making a couple of assumptions (including
linear interpolation). The term structure of spot rates is recovered from
the bond yields by solving for them recursively, this iterative process is
called the BootStrap Method.

http://janroman.dhis.org/stud/Bootstrap_2006.xls shows how to


implement Boostrapping method in Excel, more can be found at his
website http://janroman.dhis.org/index_eng2.html.

Tags - bootstrapping , yield

Please read update at http:://www.mathfinance.cn 362


Variance reduction by antithetic variable
Had a small party with friends yesterday and drank until 5 o'clock in the
morning, hangover is still here after 6 hours sleep. All feasts must come
to an end, we have to accept this fact, going to leave soon the country i
have stayed over one year, leave friends accompanying me when i was
sad and joyful, specially a girl i favor.

Back to code, Whenever we price a derivative via Monte Carlo


simulation, for instance use Gaussian variates to simulate Brownian
motion by constructing sample paths of standard Wiener processes, we
can make use of the fact that for any one drawn path its mirror image
has equal probability. In other words, if a single evaluation driven by a
Gaussian variate vector draw zi is given by vi = v(zi), we also use vvi =
v(−zi), which is called antithetic sampling and widely used for variance
reduction because of its simplicity to add to your code.

Run the sample code to check the variance reduction effect if you wish
http://www.ma.ic.ac.uk/~becherer/Course07MS15/
antitheticexample.m.
Tags - variance-reduction

Please read update at http:://www.mathfinance.cn 363


Term Structure Lattice to Price Bermudan swaption
The modelling philosophy for term-structure models is somewhat
different to the modelling philosophy for equity models. In the latter
case, stock price dynamics are usually specified under the physical
probability measure, P, before their dynamics under an EMM, Q, are
determined. For example, in the binomial Black-Scholes framework a
unique Q is easily determined after the P-dynamics of the stock-price are
given. Moreover, it is easy to check that the model does not allow any
arbitrage: we just need d < R < u.

In contrast, with term-structure models we often assume that zero-


coupon bonds of every maturity exists and it is not always easy to
directly specify their P-dynamics in an arbitrage-free manner that it is
economically satisfactory. For example, in a T-period binomial model
there are O(T) zero-coupon bond prices that we need to specify at each
node. Checking that the model is arbitrage-free and that bond price
processes have suitable properties (e.g. implied interest rates are always
non-negative) can be a cumbersome task. As a result, we usually work
with term structure models where we directly specify an EMM, Q, and
price all securities using this EMM. By construction, such a model is
arbitrage free. Moreover, by leaving some parameters initially
unspecified (e.g. short-rate values at nodes or Q-probabilities along
branches in a lattice model) we can then calibrate them so that security
prices in the model coincide with security prices observed in the market.

In the lecture notes of Term Structure Models-Spring 2005 professor


Martin Haugh introduces how to price a Bermudan swaption with term
structure lattice, precisely speaking, binomial tree, there he cailibrates
both Ho-Lee and Black Derman Toy Model and use the calibrated
interested rate model to price a Bermudan swaption as an example.

lecture notes about this topic is http://www.columbia.edu/~mh2078/


TS05/lattice_models.pdf and
sample spreedsheet is http://www.columbia.edu/~mh2078/TS05/
Term_Structure_Lattices.xls
wiki(Bermudan swaption)
Tags - swaption , bermudan

Please read update at http:://www.mathfinance.cn 364


Crank-Nicolson for a European put
A PDE can be solved by Finite Difference or Finite Element method, both
methods require space discretization, therefore, explicit or implicit finite
difference is applied for this problem. The advantage of explicit finite
difference is it does not require matrix inversion, however, to satisfy CFL
condition, dt (time interval) can not be too small to prevent from non-
convergece result, Crank-Nicolson is supposed to balance between
explicit and implicit finite difference by choosing theta=1/2, which
means taking average of explicit and implicit method.

A sample code to show the performance of Crank Nicolson for a


Europen put can be downloaded at http://www.maths.strath.ac.uk/
~aas96106/ch24.m, it is from chapter 24 of the book An Introduction to
Financial Option Valuation: Mathematics, Stochastics and
Computation, more codes are at the homepage
http://www.maths.strath.ac.uk/~aas96106/option_book.html
wiki(Crank Nicolson)
Tags - pde

Please read update at http:://www.mathfinance.cn 365


evolutionary algorithm optimization
In the post Optimization packages dozens of optimization routines can
be downloaded, here I am going to share a special optimization method:
evolutionary algorithm.

Evolutionary algorithms (EAs) are search methods that take their


inspiration from natural selection and survival of the fittest in the
biological world. EAs differ from more traditional optimization
techniques in that they involve a search from a "population" of solutions,
not from a single point. Each iteration of an EA involves a competitive
selection that weeds out poor solutions. The solutions with high "fitness"
are "recombined" with other solutions by swaping parts of a solution
with another. Solutions are also "mutated" by making a small change to a
single element of the solution. Recombination and mutation are used to
generate new solutions that are biased towards regions of the space for
which good solutions have already been seen.

This R package provides the DEoptim function which performs


Differential Evolution Optimization (evolutionary algorithm), for detail
check http://cran.r-project.org/web/packages/DEoptim/index.html.
wiki(Evolutionary algorithm)
Tags - optimization

Please read update at http:://www.mathfinance.cn 366


Finite Element package
Recently I have been working on pricing a high dimensional (4
dimension, actually) derivative via partial differencial equation (PDE),
which can be solved numerically by Finite Element or Finite Difference
method. Indeed Matlab has a PDE toolbox to use, however, as I know,
this PDE toolbox can only calculate two dimensional problem, for
instance, stock and time dimension as Black Scholes model does.

For your attention, I found an excellent Finite Element package named


Getfem++ written in C++, as its webpage says, "The Getfem++ project
focuses on the development of a generic and efficient C++ library for
finite element methods. The goal is to provide a library allowing the
computation of any elementary matrix (even for mixed finite element
methods) on the largest class of methods and elements, and for arbitrary
dimension (i.e. not only 2D and 3D problems). " what's more interesting
is this library can be linked easily to Matlab.

We know Finite Element method is an alternative to Finite Difference


discretization of the BS and other equations in the price resp. the log-
price space variable. The advantage of FE is that it gives convergent
deterministic approximations of the option price under realistic, low
smoothness assumptions on the payoff function, as e.g. for binary
contracts and in particular allow a higher rate of convergence that that
achievable with Monte Carlo simulations.

To get a deeper insight on and download open source Getfem++ please


be at http://home.gna.org/getfem/
wiki(Finite element)
Tags - finite-element , pde

Please read update at http:://www.mathfinance.cn 367


Vasicek model in binomial tree
At previous post I shared a site using R language for Vasicek estimation,
as we know, Vasicek model is a term structure model describing the
stochastic process of interest rates. It is a type of "one-factor model" with
negative interest rate possible, despite this shortcoming, it is still applied
for fixed income research and application due to its mean-reversion
characteristics.

Here is another Vasicek application implemented with binomial tree in


C++, the tree construction procedure is outlined in Tuckman famous
book Fixed Income Securities. By providing input parameters like the
initial short rate, speed of mean reversion, long-run average rate and
volatility, interest rate following Vasicek evolution is constructed.

For detail check this page http://math.nyu.edu/~atm262/spring06/


ircm/vasicek/.

Tags - vasicek , binomial

Please read update at http:://www.mathfinance.cn 368


Code for Quantitative Macroeconomics
I am not a fan of Quantitative Macroeconomics, which uses standard
neoclassical theory to explain business cycle fluctuations and tries to
answer the following questions, to name a few,
What are the empirical characteristics of business cycles?
What brings business cycles about?
What propagates them?
Who is most affected and how large would be the welfare gains of
eliminating them?
What can economic policy, both fiscal and monetary policy do in order
to soften or eliminate business cycles?
Should the government try to do so?
......

Sounds boring? I found this site when I searched "Kalman filter", click
the following link for codes in Quant economics of different
programming languages.
http://ideas.repec.org/s/dge/qmrbcd.html
Tags - economics

Please read update at http:://www.mathfinance.cn 369


Libor Market Model: Theory and Implementation source code
Libor Market Model is a term structure model applied to value and
hedge exotic interest rate derivatives. The model is recognized and
employed largely because of its consistency with the popular market
model, Black's formula. This consistency makes the calibration process
easy as the Black's market prices for vanilla interest rate Options can be
instantly used as an input.

The purpose of this book -Libor Market Model: Theory and


Implementation is to analyze the Libor Market Model in theory and
implement it practically to the evaluation of normal caps, barriers,
European swaptions and ratchets, etc. The dynamic of the Libor Market
Model will be derived and the whole steps of its implementation
applying Monte Carlo simulation will be introduced. Implementation is
accomplished via several volatility and correlation formulation. Special
attention should be given when it comes to calibrate the Libor Market
Model and model the forward rate volatilities and correlations since they
could impact prices of interest rate derivatives substantially.

you can download the free c course code by leaving your email at
http://www.irina-goetsch.com/libor-market-model/app#order
wiki(LIBOR Market Model)

Tags - libor

Please read update at http:://www.mathfinance.cn 370


European Exchage Options
Options to exchange one asset for another arise in various contexts. An
option to buy yen with Australian dollars is, from the point of view of a
US investor, an option to exchange one foreign currency asset for
another foreign currency asset. A stock lender offer is an option to
exchange shares in one stock for shares in another stock.

Consider a European option to give up an asset worth ST at time T and


receive in return an asset worth VT, the payoff from the option is
max(VT-ST,0)
A formula for valuing this option was first produced by Margrabe at his
paper “The value of an option to exchange one asset for another”,
Journal of Finance, a sample Matlab file can be downloaded here

http://www.global-derivatives.com/code/matlab/
EuropeanExchange.m
http://www.global-derivatives.com/
index.php?option=com_content&task=view&id=184
wiki(Foreign exchange option)
Tags - exchange , derivative , option

Please read update at http:://www.mathfinance.cn 371


brownian bridge simulation
Quotation
Similar to the spectral path construction method, the Brownian bridge is
a way to construct a discretised Wiener process path by using the first
Gaussian variates in a vector draw z to shape the overall features of the
path, and then add more and more of the fine structure. The very first
variate z1 is used to determine the realisation of theWiener path at the
final time tn of our n-point discretisation of the path by setting Wtn =
sqrt(tn)z1. The next variate is then used to determine the value of the
Wiener process as it was realised at an intermediate timestep tj
conditional on the realisation at tn (and at t0 = 0 which is, of course,
zero). The procedure is then repeated to gradually fill in all of the
realisations of the Wiener process at all intermediate points, in an ever
refining algorithm.

here is a simulation of Brownian paths, brownian-bridge type


simulation.

Click to download
Tags - brownian-bridge

Please read update at http:://www.mathfinance.cn 372


Swaption valuation
A swaption is an over-the-counter derivative on a swap. Normally, the
underlying swap is a vanilla interest rate swap. Nevertheless, "swaption"
could be applied to relate to a derivative about whatever kind of swap.

Swaptions could be European, American, or even Bermudan type. They


can be physically settled, in which case a derivative is really participated
into at exercise date. They can be cash settled as well, in which example
the market price of the underlying swap is cleared at maturity.

it is frequently more handy to address in terms of two common kinds of


swaption:

A payer swaption is a call option on a pay-fixed swap, the swaption


holder has the right to pay fixed rate on a swap.

A receiver swaption is a call option on a receive fixed swap, the swaption


holder has the right to receive fixed rate on a swap.

a spreedsheet showing how to price a swaption in a tree can be


downloaded at:
http://www.anassabri.info/ValuingSwaptions.xls
wiki(Swaption)
Tags - swaption

Please read update at http:://www.mathfinance.cn 373


principal component analysis
Principal component analysis (PCA) is widely used for data research, for
instance, interest rate analysis, VaR calculation of porfolio, etc. What is
PCA? It is a method of discovering patterns in data, and conveying the
data in such a manner to spotlight their similarities and divergences.
Because patterns in data can be difficult to detect in data of high
dimension, where the luxury of graphical representation is not available,
PCA is a potent tool for analysing data.

The additional major benefit of PCA is that after you have obtained these
patterns in the data, and you compact the data, ie. by reducing the
number of dimensions, without much loss of information.

http://www.theponytail.net/CCFEA/
http://www.theponytail.net/CCFEA/lect04/lect04pc.m
wiki(principal component analysis)

Tags - pca

Please read update at http:://www.mathfinance.cn 374


Nelson Siegel interest rate model calibration
Often we need to model the yield curve for bond pricing and risk
analysis purpose, for instance,

The valuation of products requires the modelling of the entire covariance


structure. Historical estimation of such large covariance matrices is
statistically not tractable anymore.
Need strong structure to be imposed on the co-movements of financial
quantities of interest.
Specify the dynamics of a small number of variables (e.g. PCA).
Correlation structure among observable quantities can now be obtained
analytically or numerically.
Simultaneous pricing of dierent options and hedging instruments in a
consistent framework.

There are dozens of interest rate models used by practioners, Nelson-


Siegel term structure model is one of them gained popularity. here is a
spreedsheet showing how to fit Extended Nelson Siegel Spot Rate with
Solver.

http://janroman.dhis.org/
http://janroman.dhis.org/finance/Excel/
NelsonSiegelYieldCurveModel.xls
wiki(Nelson-Siegel)
Tags - yield , nelson-siegel

Please read update at http:://www.mathfinance.cn 375


Combinatorica mathematica package
Oops, first post on Mathematica, simply because I dont use it for
research, I simply love Matlab and C++, due to their popularity and
easy-to-use. However, good news for Mathematica fans, here I found an
excellent Mathematica package named "The Combinatorica Project",
which is a package written in 1989 by Steve Skiena for exercising
computational discrete mathematics.

here is the introductory page and downloading link, have fun and enjoy
new week.
http://www.cs.uiowa.edu/~sriram/Combinatorica/
Tags - mathematica

Please read update at http:://www.mathfinance.cn 376


PSOR for American option
We often have to price the American Option with Linear
Complementarity Formulation when using finite difference method. One
of methods for solving linear complementarity problem is Projected
Successive Over Relaxation (PSOR), which is iterative and tries to solve
the following formulation:
x'(Ax - b) = 0
x >= 0
Ax - b >= 0
using the projected SOR algorithm. Here is a sample Matlab code
showing the basic algorithem of PSOR,
function [x] = psor(A,b,x0)
omega = 1.5;
tol = 1e-9;
jmax = 1e+3;

n = length(b); x = x0; j = 1;
for i = 1:n
x(i) = max(0,x(i)+omega*(b(i)-A(i,:)*x)/A(i,i));
end

while (norm(x-x0) > tol) && (j < jmax)


j = j + 1; x0 = x;
for i = 1:n
x(i) = max(0,x(i)+omega*(b(i)-A(i,:)*x)/A(i,i));
end
end
return

A problem with this sample code is slow computation speed, Should you
are happy with C++, the following C++ code which can be called directly
in Matlab.

Click to download
wiki(Linear complementarity problem)
Tags - psor , american , option

Please read update at http:://www.mathfinance.cn 377


Finance IQ test
Weekend Time! interested into doing a short test on your finance IQ?
Finance IQ is designed to test your knowledge in finance. The questions
database includes various categories to choose, for instance, you can
choose to test your Risk IQ or Options IQ, level could be from as easy as
the definition of European option, black scholes to FRM test or even
more advanced.

Take a rest & have fun.


Kind reminding: today is the last day of Beijing Olimpic and closing
ceremony will be staging.
http://www.fintools.com/docs/FinanceIQ.xls
Tags - iq

Please read update at http:://www.mathfinance.cn 378


Floating Strike Lookback Option
The payoffs from lookback options depend on the maximum or
minimum asset price reached during the life of the option. The payoff
from a European-style lookback call is the amount that the final asset
price exceeds the minimum asset price achieved during the life of the
option. The payoff from a European-style lookback put is the amount by
which the maximumasset price achieved during the life of the option
exceeds the final asset price.

Floating Strike Lookback Options means the strike is given as the


optimal(maximum or minimum) value of the underlying asset. Matlab
code for pricing it is here:

http://www.global-derivatives.com/code/matlab/Lookback-
FloatingStrike.m
Tags - lookback , exotic , option

Please read update at http:://www.mathfinance.cn 379


Markowitz Efficient Frontier stock portfolio
The efficient frontier was initiative specified by Markowitz in his
innovative report . The theory deals an amounts of risky products and
searches an optimal portfolio based on those possible investments.

Given a time interval, we could impute expected returns and volatilities.


We could also specify a correlation of returns. The "optimal" portfolio
can be formed in two methods:

first: for a certain level of volatility, count all portfolios that equal this
volatility. amongst them all, choose the one with highest expected
return.
second: for a given expected return, count all portfolios having this
expected return. Choose the one which has the lowest volatility.

often numerical calculation is applied for optimization as we have


additional constraints on the optimal portfolio, for instance, weight
limits, etc. below is an Excel file demonstrating many assets Efficient
Portfolio can be generated by solver.

http://www.essex.ac.uk/ccfea/Teaching/Archive/200304/Quant/
3%20Portfolio%20Analysis/Efficient%20Portfolio.xls
wiki(Capital asset pricing model)
Tags - markowitz , optimization

Please read update at http:://www.mathfinance.cn 380


Visualize Copulas
In those Copula codes you can get a rough idea what copula is, how to
estimate and simulate it, how to test its performance, etc., to help you
visualize what on earth the copula should look like, below R code draws
plots of some widely used copulas.

PS: I just finished my Copuls exam one hour ago, performance...um....


Fighting...

http://www.fam.tuwien.ac.at/~mkeller/R-progs/copula.R
Tags - copula

Please read update at http:://www.mathfinance.cn 381


Java Quantlib
Many people know QuantLib, which is a free/open-source library for
quantitative finance for modeling, trading, and risk management in real-
life written in C++, for those people prefer Java language, they have to
read & understand C++ codes and transfer them to Java code. JQuantLib
is aiming at these Java-fans group,

Quotation
JQuantLib is a free, open-source, comprehensive framework for
quantitative finance, written in Java. It provides "quants" and Java
application developers several mathematical and statistical tools needed
for the valuation of financial instruments, among other features.

Is there MQuantLib for Matlab fans?


Tags - quantlib , java

Please read update at http:://www.mathfinance.cn 382


SABR stochastic volatility model
A suitable characteristic of any local and stochastic volatility model is
that the model can yield the same prices of the vanilla options that were
applied as inputs to the calibration of the model. failure to do so will
clearly cause the model not arbitrage free and generate it nearly useless.

A substantial point of the SABR model is that the prices of vanilla


options can be computed in almost closed form (Subject to the precise
of a series expansion). Basically it has been shown that the price of a
vanilla option under the SABR model is yielded by the suitable Black
model, given that the correct implied volatility is employed.

SABR code in VBA and C is available together with a PDF:


http://www.axelvogt.de/axalom/SABR.pdf
http://www.axelvogt.de/axalom/SABR_Code_VB_and_C.txt

wiki(SABR Volatility Model)


Tags - stochastic , volatility

Please read update at http:://www.mathfinance.cn 383


Copula simulation and estimation
Copula is widely used for multi-variate modeling, especially when the
underlying marginal distributions are not the same, generally speaking,
Copula has at least the following application:

• Copulas provide us with a deeper understanding of dependence as


such.
• Many dependence concepts, orderings and measures of association
depend on H only through C and are in other words margin-free.
• Copulas allow us to easily construct (and simulate from) multivariate
distributions with given univariate margins. This fact is particularly
useful for stress testing.
• Multivariate data can be modeled in two separate stages: The
univariate marginals can be handled first and their dependence structure
thereafter. This comes in especially handy when we either already have
some information about the margins (e.g. in the bottom-up approach in
risk management) or if finding appropriate marginal distributions is
difficult. In the latter case, we can model the margins nonparametricaly
and use a parametric copula model to describe their dependence.
......

Below is the matlab file for Copula simulation and estimation, enjoy.
http://www.mathworks.com/matlabcentral/fileexchange/
loadFile.do?objectId=15449
wiki(Copula)
Tags - copula

Please read update at http:://www.mathfinance.cn 384


Perl Option Pricing Project
Derivatives can be valued applying a mixture of statistical models. A
former version of the Perl module was utilized to produce market
analysis software package. The code comprises of a Perl module
incorporating routines to do option pricing and related computations.

Software documentation
For a fantabulous reference on derivative pricing, confer with Espen
Gaarder Haug (1998) Option Pricing Formulas, McGraw-Hill. The
routines were all deduced from the pseudocode there.

http://www.kmri.com/software/popp.html
Tags - perl , option

Please read update at http:://www.mathfinance.cn 385


GEV distribution and density function
The role of the generalized extreme value (GEV) distribution in the
theory of extremes is analogous to that of the normal distribution (and
more generally the stable laws) in the central limit thoory for sums of
random varibles. The df of the GEV distribution is given by a three-
parameter family: shapre, location and scale, where shape parameter
decides the distribution is Frechet, Weibull or Gumbel.

A matlab code for plot the GEV distribution and density function

http://www.essex.ac.uk/ccfea/Teaching/Archive/200405/CF901/
weeks3and4/plot_GEV_densities.txt
wiki(Generalized extreme value distribution)
Tags - gev , extreme

Please read update at http:://www.mathfinance.cn 386


Multivariate normal CDF
As a generalization of the normal or Gauss distribution to many
dimensions we define the multinormal distribution. In statistics, the
multivariate normal (mvn) is a widely-used distribution, for instance,
basket option pricing, portfolio VaR analysis. Unluckily, its cumulative
distribution function (cdf) doesn't take a closed form. There are,
nevertheless, amounts of techniques that numerically approximate the
value of the cdf.

Here is one of such methods in M file.

http://alex.strashny.org/a/Multivariate-normal-cumulative-
distribution-function-(cdf)-in-MATLAB.html
wiki(Multivariate normal distribution)
Tags - cdf

Please read update at http:://www.mathfinance.cn 387


Equity linked notes
An Equity-Linked Note (ELN) is a debt tool that differs from a normal
fixed-income security due to the coupon is depend on the return of a
single stock, basket of stocks or equity index. An ELN is a principal
secured instrument Commonly configured to generate 100% of the
original investment at due date, but differs from a standard fixed-
coupon bond because its coupon is decided by the performance of the
underlying equity.

This spreadsheet calculates the price and embedded option value of


equity linked notes, together with other option, Robeco-Reverse
convertible, for example.

http://www.ulb.ac.be/cours/solvay/farber/exceltips.htm
http://www.ulb.ac.be/cours/solvay/farber/VUB/
08%20Lecture%202.xls
wiki(Equity linked note)
Tags - eln

Please read update at http:://www.mathfinance.cn 388


Process Simulation in R
Simple demonstration codes for process simulation in R, including
Brownian motion simulation, Poisson process simulatio, Euler scheme
simulation for Geometric Brownian motion, the mean-reverting process,
and the process with two 'attractors', etc.

http://www.math.ku.dk/~rolf/teaching/mfe04/MiscInfo.html#Code
Tags - simulation

Please read update at http:://www.mathfinance.cn 389


Optimization packages
Optimization models play an increasingly important role in financial
decisions. Many computational nance problems ranging from asset
allocation to risk management, from option pricing to model calibration
can be solved efficiently using modern optimization techniques. Several
classes of optimization problems including linear, quadratic, integer,
dynamic, stochastic, conic, and robust programming are often
encountered in financial models. This site collects dozens of optimization
packages in different programming languages, you will find one for you.

http://www.rpi.edu/~mitchj/pack.html#abacus
wiki(Optimization)
Tags - optimization

Please read update at http:://www.mathfinance.cn 390


Real Option Models in Valuation
Real Option good example in Corporate Finance

This example approximates the economic value of the option to


extend in an investing project. it can also be used to appraise the value of
strategic options.
This example calculates the value of the option to postpone an
investment project.
This example estimates the value of fiscal tractability, i.e, the
sustenance of extra debt capability or back-up funding.
This example estimates the value of the option to give up a project or
investment.

Real Option Models in Valuation

A example that applies option pricing to measure the equity in a


company; most well suitable for largely levered firms in trouble.
A model that applies option pricing to evaluate a natural resource
firm; useful for measuring oil or mining companies.
A model that applies option pricing to appraise a product patent or
option; useful for valuing the patents that a company may declare.

http://pages.stern.nyu.edu/~adamodar/New_Home_Page/
spreadsh.htm#optincf
wiki(Real option)
Tags - real-option , option

Please read update at http:://www.mathfinance.cn 391


Brinson performance attribution
Performance attribution is used as a way to check the relative
performance of portfolio against selected Benchmark, the difference of
which is called active return. Brinson method decomposes active return
to asset selection effect and industry selection effect, helping investor
realize where the active return is from, which asset or industry has a
biggest contribution to the active return of portfolio, ect.

http://www.barra.com/products/spreadsheets/stockselection.xls
wiki(Performance attribution)
Tags - performance

Please read update at http:://www.mathfinance.cn 392


R-code for Vasicek estimation
A short-rate model is usually calibrated to some initial structures in the
market, typically the initial yield curve, the caps volatility surface, the
swaptions volatility surface, and possibly other products, thus
determining the model parameters. Vasicek, Cox Ingersoll Ross (CIR),
Dothan, for instance, are among the frequently-used short-rate models.
The strength of Vasicek model is analytical bond prices and analytical
option prices can be obtained and easily calculatied, however, negative
short rates are also possible with positive probability.

R code can be downloaded at http://www.math.ku.dk/~rolf/teaching/


mfe04/MiscInfo.html#Code

wiki(Vasicek model)
Tags - vasicek , cox ingersoll ross

Please read update at http:://www.mathfinance.cn 393


Valuing Warrants under dilution
Usually, when a call option on a stock is exercised, the party with the
short position acquires shares that have already been issued and sells
them to the counterparty, however, warrants, executive stock options as
well, are options that work slightly differently, they are written by a
company on its own stock, when they are exercised, the company issues
more of its own stock and sells them to the option holder for the strike
price. the exercise of a warrant therefore leads to an increase in the
number of shares of the company's stock that are outstanding, which has
the dilution effect on the price of warrant as a result.

often we ignore this dilution effect as it might be small, here is a


spreedsheet model for valuing options that result in dilution of the
underlying stock if you do want to consider it.

http://pages.stern.nyu.edu/~adamodar/New_Home_Page/
spreadsh.htm#basicoption

Tags - warrant

Please read update at http:://www.mathfinance.cn 394


halton and sobol sequences
I couldnot stop using Quasi Monte Carlo simulation for derivative
pricing, especially when the problem to solve is a low dimensional one.
Among low discrepancy random numbers, Halton sequences and sobol
sequences are two of my favorites, although sometimes I compare other
sequences like Faure, Haselgrove, and Niederreiter as well. Unlike
pseudo-random numbers, low-discrepancy numbers aim not to be
serially uncorrelated, but instead to take into account which points in the
domain to be sampled have already been probed. Low-discrepancy
numbers have become a popular tool for financial Monte Carlo
calculations since the early 1990s.

http://www.math.uic.edu/~hanson/mcs507/cp4f04.html
wiki(Low-discrepancy sequence)

Tags - halton , sobol

Please read update at http:://www.mathfinance.cn 395


Beasley-Springer-Moro inverse normal
Once you get uniform random numbers, how to inverse that to normal
random numbers require numerical technique, Moro is one of such
techniques,
Quotation
my favourite method for constructing standard normal variates is the
highly sophisticated interpolation formula by Peter Acklam for the
inverse cumulative normal distribution. A very crude way to quickly
construct (approximately) normally distributed variates is to add up 12
uniform variates, and subtract 6. For any reasonable application, I would
always use either Peter Acklam’s method, or Boris Moro’s interpolation
formula.

http://www.mathworks.com/matlabcentral/fileexchange/
loadFile.do?objectId=14234&objectType=file
Tags - normal , monte carlo

Please read update at http:://www.mathfinance.cn 396


Barrier Option Calculator
tran(This program can calculate values and greeks for plain vanilla
options as well as single and double barrier options with or without
rebate. Calculations are performed within the standard Black-Scholes
model. For plain vanilla and single barrier options, the calculation is
purely analytical. Double barrier options are approximated using a
Fourier series approximation, unless volatility is low. For low volatility
an alternative series expansion is used.)

http://www.neumann.nl/~dimitri/pricing.html
wiki(barrier option)
Tags - barrier , calculator , option

Please read update at http:://www.mathfinance.cn 397


Monte Carlo Chooser Option
Chooser option gives the holder the right to choose it is a call or put
option at a prescriped strike price and date. here is a sample spreedsheet
pricing chooser option with Monte Carlo simulation.

http://fisher.utstat.toronto.edu/sjaimung/courses/2008-2009/sta2502/
main.htm

Tags - monte carlo , chooser , option

Please read update at http:://www.mathfinance.cn 398


State space model toolbox
Another MATLAB toolbox for time series analysis using state space
models. Supports fully interactive model construction with MATLAB
objects and efficient Kalman filter backend implemented in c.

http://sourceforge.net/projects/ssmodels/
wiki(kalman filter)
Tags - filter

Please read update at http:://www.mathfinance.cn 399


Sobol and Generalised Faure sequences
Low discrepancy sequences are highly recommended for low-
dimensional Monte Carlo simulation, they have been proved to be able
to improve convergence speed, accuracy, etc. take a trial.

http://web.wits.ac.za/NR/rdonlyres/96ECC07E-
AE3C-4706-94F8-C1A53011AF38/0/searlecode.zip
wiki(Low-discrepancy sequence)
Tags - sobol , faure

Please read update at http:://www.mathfinance.cn 400


Entire Equity and Monetary Option Formulas
lots of equity and monetary option model available in VBA, for instance,
Black Scholes 1973, you can download them or calculate the formula
online.

http://www.montegodata.co.uk/Consult/Derivative/Derivatives.html

Tags - derivative , calculator , option

Please read update at http:://www.mathfinance.cn 401


Code for Financial Modeling Under Non-Gaussian
Distributions
This site stores matlab codes accompanying the book Financial Modeling
Under Non-Gaussian Distributions, a wonderful and easy to read book,
which was used by my professor last semester, you can imagine how
much this site has helped me, Cheers.

http://www.hec.unil.ch/MatlabCodes/
Tags - matlab

Please read update at http:://www.mathfinance.cn 402


Black Scholes in Multiple Languages
Black Scholes formula is widely used for vanilla option pricing, which is
also easy to code, but how many language can you use? I can do it in
Matlab, C++, GAUSS, VBA, PHP. Guess what, this site collects more
than 30 languages, have fun!

http://www.espenhaug.com/black_scholes.html

wiki(black scholes)
Tags - black scholes

Please read update at http:://www.mathfinance.cn 403


Calibration of a binomial tree to the volatility surface
How to calibrate a binomial tree to the volatility surface implied from
market option prices. Code in Matlab.

http://theponytail.net/CCFEA/

wiki(Volatility smile)
Tags - volatility , smile , binomial

Please read update at http:://www.mathfinance.cn 404


Monte Carlo Pricer Black Derman Toy Model
Financial Quantitative Algorithms

below you will find the some sources of the sources in C++ and Java.T

Table with C++ sources

Closed expressions and Approximate Models for various Financial


Option on Equity
Binary Tree method to Price Options on Equity
Monte Carlo pricer of Exotics
Monte Carlo Pricer of American Calls and Puts
Monte Carlo Pricer of European Barrier, Knock in and out Options
Monte Carlo Pricer European Spread Options
Monte Carlo Pricer of Interest Rate Derivatives (One factor)
Monte Carlo Pricer Ho Lee Model
Monte Carlo Pricer Hull White Model
Monte Carlo Pricer Black Derman Toy Model
Monte Carlo Pricer Brace Gatarek Musiela / Jamishidian Model
Monte Carlo pricer of exotics with constant Jump-Diffussion
Monte Carlo Pricer of Barrier, Knock in and out Options with Jump-
Diffusion
Monte Carlo Pricer European Spread Options with Jump-Diffusion

Table with Java sources

Closed expressions and Approximate Models for various Financial


Option on Equity
Binary Tree method to Price Options on Equity
Monte Carlo pricer of Exotics
Monte Carlo Pricer of American Calls and Puts
Monte Carlo Pricer of European Barrier, Knock in and out Options
Monte Carlo Pricer European Spread Options
Monte Carlo Pricer of Interest Rate Derivatives (One factor)
Monte Carlo Pricer Ho Lee Model

Please read update at http:://www.mathfinance.cn 405


Monte Carlo Pricer Hull White Model
Monte Carlo Pricer Black Derman Toy Model
Monte Carlo Pricer Brace Gatarek Musiela / Jamishidian Model
Monte Carlo pricer of exotics with constant Jump-Diffussion
Monte Carlo Pricer of Barrier, Knock in and out Options with Jump-
Diffusion
Monte Carlo Pricer European Spread Options with Jump-Diffusion

http://www.javaquant.net/downloads.html
wiki(Black Derman Toy)
Tags - bdt , monte carlo

Please read update at http:://www.mathfinance.cn 406


download option price data from Yahoo
This R program can be used to download option price data from Yahoo
to a data frame and to plot the corresponding implied-volatility smiles.

http://www.fam.tuwien.ac.at/~mkeller/
Tags - download , data , option

Please read update at http:://www.mathfinance.cn 407


Famas Return Decomposition
A sample spreedsheet demonstrating how to decompose Fama's return
into several sources.

http://clem.mscd.edu/~mayest/FIN4600/Files/famadcmp.xls

Tags - fama

Please read update at http:://www.mathfinance.cn 408


Receiver Swaption Price
Calcualtes the price of a receiver swaption (bp).

http://www.vbnumericalmethods.com/finance/

wiki(Swaption)
Tags - swaption

Please read update at http:://www.mathfinance.cn 409


Quantile Regression
Quantile regression is a statistical technique intended to estimate, and
conduct inference about, conditional quantile functions. Just as classical
linear regression methods based on minimizing sums of squared
residuals enable one to estimate models for conditional mean functions,
quantile regression methods offer a mechanism for estimating models
for the conditional median function, and the full range of other
conditional quantile functions. By supplementing the estimation of
conditional mean functions with techniques for estimating an entire
family of conditional quantile functions, quantile regression is capable of
providing a more complete statistical analysis of the stochastic
relationships among random variables.

http://www.econ.uiuc.edu/~roger/research/rq/rq.html
wiki(Quantile regression)
Tags - regression

Please read update at http:://www.mathfinance.cn 410


calibration of the Heston SV model
http://www.theponytail.net/CCFEA

wiki(heston model)

Tags - hestonvolatility , calibration

Please read update at http:://www.mathfinance.cn 411


CDO Pricing in Gaussian Copula
CDO prices with Monte Carlo simulation includes the creation of roads
in the sample correlation preset times. This defect is sometimes used to
calculate payments to fixed and floating legs and worth of each leg.

more at http://math.nyu.edu/~atm262/spring06/ircm/cdo/index.html

wiki(Collateralized debt obligations)


Tags - cdo , copula

Please read update at http:://www.mathfinance.cn 412


simulating a two-dimensional variance gamma process with
Clayton dependence structure
Simulates two dependent variance gamma processes without drift,
dependence is given by Clayton Levy copula with parameters theta and
rho.

http://people.math.jussieu.fr/~tankov/florence/

wiki(Variance-gamma distribution)
Tags - copula , levy

Please read update at http:://www.mathfinance.cn 413


EWMA Volatility
VB function to calculate 'exponentially weighted moving average'
volatilites (=RiskMetrics volatility forecasting) with or without assuming
a zero mean return.

http://www.andreassteiner.net/performanceanalysis/
?Downloads:VBA

wiki(EWMA)
Tags - volatility

Please read update at http:://www.mathfinance.cn 414


Black Scholes Implied Volatility
Calculates the implied volatility of an european option using bi-section
method. This function uses the super black scholes function.

http://www.vbnumericalmethods.com/finance/

wiki(Implied volatility)
Tags - black scholes , volatility

Please read update at http:://www.mathfinance.cn 415


Monte Carlo Pricer Brace Gatarek Musiela / Jamishidian
Model
Table with Java sources

Closed expressions and Approximate Models for various Financial


Option on Equity
Binary Tree method to Price Options on Equity
Monte Carlo pricer of Exotics
Monte Carlo Pricer of American Calls and Puts
Monte Carlo Pricer of European Barrier, Knock in and out Options
Monte Carlo Pricer European Spread Options
Monte Carlo Pricer of Interest Rate Derivatives (One factor)
Monte Carlo Pricer Ho Lee Model
Monte Carlo Pricer Hull White Model
Monte Carlo Pricer Black Derman Toy Model
Monte Carlo Pricer Brace Gatarek Musiela / Jamishidian Model
Monte Carlo pricer of exotics with constant Jump-Diffussion
Monte Carlo Pricer of Barrier, Knock in and out Options with Jump-
Diffusion
Monte Carlo Pricer European Spread Options with Jump-Diffusion

http://www.javaquant.net/downloads.html
wiki(LIBOR Market Model)
Tags - libor , bgm

Please read update at http:://www.mathfinance.cn 416


Monte Carlo Pricer of Barrier, Knock in and out Options with
Jump-Diffusion
how to price barrier options with jump-diffusion by monte carlo
simulations, codes are in Java language.

http://www.javaquant.net/downloads.html

wiki(Barrier option)
Tags - barrier , option

Please read update at http:://www.mathfinance.cn 417


Outperformance Options Price
Computes the price of an outperformance option.

http://www.vbnumericalmethods.com/finance/

wiki(Exotic option)
Tags - outperformance , option

Please read update at http:://www.mathfinance.cn 418


Rainbow Option Price
Calculates the price of a (two-coloured rainbow) option delivering the
best of two risky assets or cash.

http://www.vbnumericalmethods.com/finance/

wiki(Rainbow option)
Tags - rainbow , option

Please read update at http:://www.mathfinance.cn 419


Kalman filter toolbox for Matlab
This toolbox supports filtering, smoothing and parameter estimation
(using EM) for Linear Dynamical Systems.

* Download toolbox
* What is a Kalman filter?
* Example of Kalman filtering and smoothing for tracking
* What about non-linear and non-Gaussian systems?
* Other software for Kalman filtering, etc.
* Recommended reading

more at http://www.cs.ubc.ca/~murphyk/Software/Kalman/
kalman.html
wiki(Kalman filter)
Tags - filter

Please read update at http:://www.mathfinance.cn 420


Stochastic simulation using MATLAB
This tutorial contains Matlab code and documentation for a seminar on
stochastic simulation. The program package demonstrates basic
techniques for effective simulation and visualization of various
stochastic processes and random mechanisms. We try to emphasize
methods that are natural given the matrix and vector oriented nature of
Matlab. The goal is that users of this material find inspiration and ideas
to prepare their own code for a particular application involving random
dynamics.

http://www.math.uu.se/research/telecom/software/
Tags - simulation

Please read update at http:://www.mathfinance.cn 421


CONVERTIBLE BOND PRICING MODEL
A simple spreadsheet to price convertible bond based on Espen Gaarder
Haage's binomial tree model which was originally developed by
Goldman-Sachs.

http://www.yieldcurve.com/Mktsoftware/excelCB.htm

wiki(Convertible bond)
Tags - convertible bond

Please read update at http:://www.mathfinance.cn 422


matlab tips and tricks
Great site for anyone who wants to optimize his matlab file, speed up
computer, have fun.

http://www.ee.columbia.edu/~marios/matlab/matlab_tricks.html

wiki(matlab)
Tags - matlab

Please read update at http:://www.mathfinance.cn 423


American Options via Monte Carlo Simulations
Sample code to price american put option with least square Monte Carlo
simulation.

http://www.quantcode.com/modules/mydownloads/
visit.php?cid=11&lid=54
Tags - monte carlo , option

Please read update at http:://www.mathfinance.cn 424


Risk Neutral Default Probability
A spreadsheet that demonstrates risk-neutral default probabilities when
pricing bonds with embedded options. We illustrate the Martingale
pricing process under certain assumptions.
The user inputs the bond parameters and an assumed recovery rate for
each bond.
The spreadsheet computes the default probability.
The accompanying spreadsheet illustrates in simple terms how the risk-
neutral probabilities
are obtained.

http://www.yieldcurve.com/Mktsoftware/excelRN.htm
wiki(risk neutral)
Tags - default

Please read update at http:://www.mathfinance.cn 425


UK Gilt zero-coupon yield curve
This spreadsheet demonstrates constructing a zero-coupon yield curve
from market gilt yields, using the basis spline methodology and
approach.
A technical description of the methodology appeared in the book
"Capital Market Instruments" by Moorad Choudhry et al (FT Prentice
Hall 2001).

http://www.yieldcurve.com/Mktsoftware/excelYC.htm
wiki(yield curve)
Tags - yield

Please read update at http:://www.mathfinance.cn 426


Asian Option Pricing
Here is the MATLAB implementation of the pricing of Asian options
from the paper Unified Asian Pricing by Jan Vecer (2002), Risk, Vol. 15,
No. 6, 113-116.

http://en.literateprograms.org/Asian_Option_Pricing_(Matlab)
wiki(asian option)
Tags - asian , option

Please read update at http:://www.mathfinance.cn 427


Matlab-GUI equity derivative calculator
This is simple Matlab-GUI files i wrote learning to code an equity
derivative calculator, options include:

European option
American option
Asian option
Index future
Cash-or-nothing option
Asset-or-nothing option
Lookback option
Chooser option
Compound option
Exchange option
Power option

Unzip the EquityDerivGUI file to a directory of your local computer,


change the directory to be the current directory of your matlab, run main
file DerivativeGui.m. tested under Matlab7.0.1.

Click to download
Tags - derivative , matlab , gui

Please read update at http:://www.mathfinance.cn 428


Mersenne Twister random number generator
SFMT is a new variant of Mersenne Twister (MT) introduced by Mutsuo
Saito and Makoto Matsumoto in 2006. The algorithm was reported at
MCQMC 2006. The article will apper in the proceedings of
MCQMC2006. (see Prof. Matsumoto's Papers on random number
generation.) SFMT is a Linear Feedbacked Shift Register (LFSR)
generator that generates a 128-bit pseudorandom integer at one step.
SFMT is designed with recent parallelism of modern CPUs, such as
multi-stage pipelining and SIMD (e.g. 128-bit integer) instructions. It
supports 32-bit and 64-bit integers, as well as double precision floating
point as output.

http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/
index.html
wiki(Mersenne Twister)
Tags - random

Please read update at http:://www.mathfinance.cn 429


Singular value decomposition
The singular value decomposition of MxN matrix A is its representation
as A = U W V T, where U is an orthogonal MxM matrix, V - orthogonal
NxN matrix. The diagonal elements of matrix W are non-negative
numbers in descending order, all off-diagonal elements are zeros.

The matrix W consists mainly of zeros, so we only need the first


min(M,N) columns (three, in the example above) of matrix U to obtain
matrix A. Similarly, only the first min(M,N) rows of matrix V T affect the
product. These columns and rows are called left and right singular
vectors.

http://www.alglib.net/matrixops/general/svd.php

wiki(Singular value decomposition)


Tags - matrix

Please read update at http:://www.mathfinance.cn 430


Normal Inverse Gaussian(NIG) and other stochastical vol
model
stochastic volatility / other models

NIG_tiny_withDLL.zip
Normal Inverse Gauss option pricer (with Esscher transform
correction), Excel + DLL, and
a Maple worksheet with short explanations, cf Schoutens book "Levy
Proccess in Finance"

VG_Pricer_short(Maple).pdf
A 'brute' option pricer for the Variance Gamma model (Madan, Carr,
Chang 1998) in Maple

VG_small.zip
Variance Gamma model in Excel + DLL; it uses a gamma distribution
pdfGamma(a,x)
which accepts large numerical arguments

http://www.axelvogt.de/axalom/

wiki(Normal-inverse Gaussian distribution)


Tags - nig , volatility

Please read update at http:://www.mathfinance.cn 431


Online Option Calculator
Calculators

* Asian, fixed strike


* Asian, floating strike
* Barrier
* Barrier, double
* Binary, asset-or-nothing
* Binary, cash-or-nothing
* Binary, gap
* Double Binary
* Chooser, simple
* Chooser, complex
* Compound
* Correlation
* Exchange
* Extendible, holder
* Extendible, writer

* Forward start
* Lookback, fixed strike
* Lookback, floating strike
* Power
* Product
* Quanto
* Quotient
* Rainbow
* Range
* Spread
* StrikeReset
* TimeSwitch
* Vanilla

http://www.sitmo.com/live/OptionVanilla.html
Tags - calculator , option

Please read update at http:://www.mathfinance.cn 432


Monte Carlo Simulation Spread Options
an example of code used to price a spread option using Monte Carlo
simulations (Haug).

http://www.mathworks.com/matlabcentral/fileexchange/82

wiki(Spread option)
Tags - spread , monte carlo , option

Please read update at http:://www.mathfinance.cn 433


Matlab code for 2-factor CIR in simulations
Jackknifing Bond Option Prices. Programs and data used in the
paper: Swap and LIBOR Rates; Matlab code for 1-factor CIR in
simulations; Matlab code for 1-factor CIR in applications; Matlab code
for 2-factor CIR in simulations; Matlab code for 2-factor CIR in
applications

http://www.mysmu.edu/faculty/yujun/research.html
http://www.mysmu.edu/faculty/yujun/Research/
jackknifecir1foption_sim.m

Tags - cox ingersoll ross , cir

Please read update at http:://www.mathfinance.cn 434


CompEcon Toolbox for Matlab
CompEcon is a set of MATLAB functions for solving a variety of
problems in economics and finance. The library functions include
rootfinding and optimization solvers, a integrated set of routines for
function approximation using polynomial, splines and other functional
families, a set of numerical integration routines for general functions and
for common probability distributions, general solvers for Ordinary
Differential Equations (both initial and boundary value problems),
routines for solving discrete and continuous time dynamic programming
problems, and a general solver for financial derivatives (bonds, futures,
options).

http://www4.ncsu.edu/~pfackler/compecon/toolbox.html
Tags - matlab

Please read update at http:://www.mathfinance.cn 435


Quasi-maximum likelihood
Quasi-maximum likelihood toolbox in matlab.

http://www.mathtools.net/files/net/qmle.zip

wiki(maximum likelihood)
Tags - mle

Please read update at http:://www.mathfinance.cn 436


A Matlab Toolbox for Univariate GARCH estimation
The primary feature that differentiates GARCHKIT from other GARCH
implementations in Matlab is its ability to incorporate covariates into the
second moment. The current version of GARCHKIT, 1.0b3, allows
univariate ARMA(P,Q)-GARCH(R,S) estimation and simulation using
maximum likelihood. The conditional distribution may be normal,
student's t or a mixture of two normals.

Version 1.1 now estimates and simulates FIGARCH and GARCH-in-


Mean models.

Code can be downloaded at http://www-agecon.ag.ohio-state.edu/


people/roberts.628/papers/research/garchkit/garchkit.html

Tags - garch

Please read update at http:://www.mathfinance.cn 437


weighted covariance matrix
Computes a weighted covariance matrix and associated values

http://www.stanford.edu/~wfsharpe/mat/mlfn.htm

wiki(Covariance)
Tags - covariance

Please read update at http:://www.mathfinance.cn 438


On-Line Options Pricing Probability Calculators
Black-Scholes pricing analysis -- Ignoring dividends: Lets you examine
graphically how changes in stock price, volatility, time to expiration and
interest rate affect the option price, time value, the derived "Greeks"
(delta, gamma, theta, vega, rho) and the probability of the option closing
in the money. For simplicity, dividends are ignored so you just specify
the time to expiration in days rather than entering specific dates.

more at http://www.hoadley.net/options/calculators.htm

Tags - black scholes , calculator , option

Please read update at http:://www.mathfinance.cn 439


Copula toolbox for Matlab
An aggregation of Matlab routines that for research on copulas for
financial time series . A few elementary illustration code is given in
"copula_example_code.m". A table of contents is given in "contents.xls".
Shortly, the toolbox comprises CDFs, PDFs, log-likelihoods and random
number generators for numerous basic bivariate copulas, including the
Clayton, Gumbel, Normal, Student's t, Frank, Plackett and symmetrised
Joe-Clayton (SJC) copulas. Simple codes for time-varying Normal,
Gumbel and SJC copulas are included as well.

http://econ.duke.edu/~ap172/code.html

Tags - copula

Please read update at http:://www.mathfinance.cn 440


A lightweight C++ library for quantitative finance
applications
What is Terreneuve? Simply: "A lightweight C++ library for quantitative
finance applications."

In more detail, Terreneuve is our team name for the project in the Fall
2005 Computing in Finance course at NYU's Courant Institute Masters in
Math Finance. Working from this specification we hope to design a
useable C++ library for some important quantitative finance
applications.

Our target audience (aside from our prof ;-)) is students in quantitative
finance and those seeking a gentle introduction to financial computing.
Obviously, we also intend to use the project as a learning opportunity.
We refer those looking for a more comprehensive (and complex) library
to the quantlib project.

http://terreneuve.sourceforge.net/

Please read update at http:://www.mathfinance.cn 441


C++ Financial Algoritms (Financial Numerical Recipes)
Quotation
In finance, there are areas where formulas tend to get involved.
Sometimes it may be easier to follow an exact computer routine. I have
made some C++ subroutines that implements common algoritms in
finance. Typical examples are option/derivatives pricing, term structure
calculations, mean variance analysis. These routines are presented
together with a good deal of explanations and examples of use, but it is
by no means a complete "book" with all the answers and explanations.
I'm hoping to turn it into a book, but even in its incomplete state is
should provide a good deal of useful algorithms for people working
within the field of finance.

Book and Code are at http://finance-old.bi.no/~bernt/gcc_prog/


index.html
Tags - finance

Please read update at http:://www.mathfinance.cn 442


Global Derivatives Option Pricing Matlab Code
a list of various derivatives related Matlab files grouped into categories.
We have attempted to provide the simple models, as well as those which
rely on simulation techniques or advanced modeling, more at
http://www.global-derivatives.com/
index.php?option=com_content&task=view&id=184
Tags - derivative , option

Please read update at http:://www.mathfinance.cn 443


Archive of Finance Econometrics GAUSS Matlab Code
Procedures and necessary declaration files to calculate fitted option
prices using Fourier Inversion methods as in Bates (RFS 1996). This
allows for a variety of possible risk neutral diffusions which can
accommodate stochastic volatility, jumps, as well as correlation between
the volatility process and underlying asset.

more at http://www.cameronrookley.com/gtoml/archive.html

Tags - gauss

Please read update at http:://www.mathfinance.cn 444


Fast Greeks by Simulation in Forward Libor Models
Fast Greeks by Simulation in Forward Libor Models by Prof.
Glasserman, paper and code can be downloaded at:

http://www.gsb.columbia.edu/faculty/pglasserman/Other/
grklibor.pdf

http://www.gsb.columbia.edu/faculty/pglasserman/Other/
greeks_code.zip

wiki(libor)
Tags - greeks , libor

Please read update at http:://www.mathfinance.cn 445


Design Patterns and Derivatives Pricing
Design patterns are the cutting-edge paradigm for programming in
object-oriented languages. Here they are discussed, for the first time in a
book, in the context of implementing financial models in C++. Assuming
only a basic knowledge of C++ and mathematical finance, the reader is
taught how to produce well-designed, structured, re-usable code via
concrete examples. Each example is treated in depth, with the whys and
wherefores of the chosen method of solution critically examined. Part of
the book is devoted to designing re-usable components that are then put
together to build a Monte Carlo pricer for path-dependent exotic options.
Advanced topics treated include the factory pattern, the singleton
pattern and the decorator pattern. Complete ANSI/ISO-compatible C++
source code is included on a CD for the reader to study and re-use and
so develop the skills needed to implement financial models with object-
oriented programs and become a working financial engineer.

a copy of the c++ code is available to download at


http://www.markjoshi.com/design/
Tags - derivative

Please read update at http:://www.mathfinance.cn 446


Heston Stochastic Volatility
Online Closed form and Monte Carlo simulation for option under
Heston Stochastic Volatility.

http://www.math.nyu.edu/ms_students/lw429/calculator.htm

wiki(Heston model)
Tags - heston , volatility

Please read update at http:://www.mathfinance.cn 447


A Course in Derivative Securities: Introduction to Theory and
Computation
A textbook for a second course in derivatives at the undergraduate or
MBA level or for a first course in a financial engineering program. The
option pricing functions in the book (including worksheet examples and
the VBA source code) are available in this Excel workbook.

http://www.kerryback.net/
Tags - derivative

Please read update at http:://www.mathfinance.cn 448


Spreadsheet Programs
To help you in finding the spreadsheet that you might want, I have
categorized the spreadsheets into the following groups:
1. Corporate finance spreadsheets: These spreadsheets are most useful if
you are interested in conventional corporate financial analysis. It
includes spreadsheets to analyze a project's cashflows and viability, a
company's risk profile, its optimal capital structure and debt type,
andwhether it is paying out what it can afford to in dividends.
2. Valuation Inputs Spreadsheets: In this section, you will find
spreadsheets that allow you to
a. Estimate the right discount rate to use for your firm, starting with the
risk premium in your cost of equity and concluding with the cost of
capital for your firm.
b. Convert R&D and operating leases into capitalized assets
c. estimate the right capital expenditures and diagnose the terminal
value assumptions to see if they are reasonable.
3. Valuation Model Reconciliation: In this section, you will find
spreadsheets that reconcile different DCF approaches - FCFE versus
Dividend Discount Model, FCFE versus FCFF model, EVA versus Cost
of capital and Net Debt versus Gross Debt Approaches.
4 . Big-picture valuation spreadsheets: If you are looking for one
spreadsheet to help you in valuing a company, I would recommend one
of these 'ginzu' spreadsheets. While they require a large number of
inputs, they are flexible enough to allow you to value just about any
company. You do have to decide whether you want to use a dividend,
FCFE or FCFF model spreadsheet. If you have no idea which one will
work for you, I would suggest that you try the "right model" spreadsheet
first.
5 . Focused valuation spreadsheets: If you have a clear choice in terms of
models - stable growth dividend discount, 2-stage FCFE etc. - you can
download a spreadsheet for the specific model in this section.
......

http://pages.stern.nyu.edu/~adamodar/New_Home_Page/
spreadsh.htm
Tags - excel

Please read update at http:://www.mathfinance.cn 449


SAS for Financial Engineers
SAS for Financial Engineers:
1 – Introduction
2 – Data Management
3 – Financial Modeling(Important PROCs and Advanced PROCs: IML,
SQL)
4 – Advanced Techniques (SAS Macro and other programming
techniques)

http://faculty.haas.berkeley.edu/peliu/computing/

Tags - sas , finance

Please read update at http:://www.mathfinance.cn 450


MatLab for Financial Engineers
MatLab for Financial Engineers:
1-Basics
2–Statistical Analysis
3–Application to Finance I (Monte Carlo Simulations – Statistics Toolbox)
4–Application to Finance II(Portfolio Choice, Risk Management –
Optimum Toolbox)
5--Application to Finance III (Binomial and Trinomial Tree Valuation)

http://faculty.haas.berkeley.edu/peliu/computing/
Tags - matlab

Please read update at http:://www.mathfinance.cn 451


Pricing Derivatives Securities using MATLAB
A Zip file containing the examples that were used in the MathWorks
webinar: "Pricing Derivatives Securities using MATLAB".

Highlights:
* Pricing a portfolio of vanilla options using Black-Scholes, a Binomial
Tree and Monte Carlo simulation.
* Pricing exotic options using the implied trinomial tree (ITT) method
* Hedging using derivatives
* Pricing interest rate derivatives using the BDT model

http://www.mathworks.com/matlabcentral/fileexchange/
loadFile.do?objectId=14508
Tags - derivative , matlab

Please read update at http:://www.mathfinance.cn 452


Parameters estimation of GARCH model
Parameters estimation of GARCH model.

http://w3.uniroma1.it/passalac/buffer/GARCH.xls

wiki(GARCH)
Tags - garch

Please read update at http:://www.mathfinance.cn 453


Financial Model Library by Thomas Ho
Introduction:

* "Financial Model Library" is a library of financial models in an Excel


spreadsheet. The purpose of the library is to promote usage and better
understanding of financial models.
* All financial models in this section can be used free of charge and can
be distributed.
* We hope that you can also contribute to the library of financial
models by submitting your Excel model spreadsheet in the format
consistent with our models. The rules for submission are similar to that
of a Journal. That is:
o We maintain the right to reject your submission or suggest
o revisions of the models
o We reserve the copyright of the Excel spreadsheet model.
* The site is not responsible for any errors in the models and copyright
violation of any models submitted.

http://www.thomasho.com/mainpages/analysoln.asp
Tags - library

Please read update at http:://www.mathfinance.cn 454


Contact us
abiao: PhD candidate in finance, UK (2009 ~ present)
MSc in quantitative finance, Switzerland (2007 ~ 2008)
Quant researcher, UK, (2008~2009)
Quant analyst, China, (2004~2007)
Skills: Matlab, VBA, S+/R, C++

bo: MSc in computational finance, China


Researcher, China
Skills: VBA, Eview

Please leave message here, follow my twitter or write to abiao @


mathfinance.cn (remove space) for any issue regarding suggestion,
cooperation, ad on this blog, complaint, sharing quant code related site,
project outsourcing, internship, part-time job, freelance, etc., thank you.

Should you are interested into posting your articles on mathfinance.cn,


please read our paid contributor and guest post policies.

About MathFinance.cn: Blog on Quantitative finance code, methods in


math finance focusing on derivative pricing, quantitative trading and
quantitative risk management. Several features:
1, one of the few mainly quant oriented blogs;
2, received on average 500~600 unique visitors and 1200+ pageviews per
day;
3, visitors are mostly from US, UK, Canada, France, and Germany.

As of 24/04/2010, MathFinance.cn is:


#5 site in 'Quantitative Finance' *
#7 site in 'Quant' *
#5 site in "Math Finance" **
#9 site in "Quant Jobs" **
*by xmarks.com, **by Google.com
Quantitative Finance Collector is a Top Site in Quantitative Finance
Review This Site
Quantitative Finance Collector is a Top Site in Quant

Please read update at http:://www.mathfinance.cn 455


Review This Site

Tags - blog

Please read update at http:://www.mathfinance.cn 456


www.feedbooks.com
Food for the mind

Please read update at http:://www.mathfinance.cn 457

You might also like