Quantitative Finance Collector

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" 1 Please read update at http:://www.mathfinance.cn

description

Quantitative Finance Collector is simply a record of my financial engineering learning journey as a master in quantitative finance, a PhD candidate in finance and a Quantitative researcher. It is mainly about Quantitative finance codes, methods in mathematical finance focusing on derivative pricing, quantitative trading and quantitative risk management, with most of the entries written at university. Please read update at http://www.mathfinance.cn

Transcript of Quantitative Finance Collector

Page 1: Quantitative Finance Collector

Quantitative Finance Collectorabiao

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

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

Page 2: Quantitative Finance Collector

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.

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

Page 3: Quantitative Finance Collector

www.feedbooks.comFood for the mind

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

Page 4: Quantitative Finance Collector

Quantitative Finance Collector

Updated: 8-10Update this newspaper

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

Page 5: Quantitative Finance Collector

Quantitative Finance Collector

Handling Large CSV Files in R

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

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 formats3) use cast --> to group data in the most "square" format as possible, thisstep involves the Reshape package, a very good one.

2, use the bigmemory package to load the data, so in my case, usingread.big.matrix() instead of read.table(). There are several otherinteresting functions in this package, such as mwhich() replacing which()for memory consideration, foreach() instead of for(), etc. How large canthis package handle? I don't know, the authors successfully load a CSVwith size as large as 11GB.

3, switch to a 64 bit version of R with enough memory and preferably onlinux. I can't test this solution at my office due to administrationconstraint, although it is doable, as mentioned in R help document,Quotation64-bit versions of Windows run 32-bit executables under the WOW(Windows on Windows) subsystem: they run in almost exactly the sameway as on a 32-bit version of Windows, except that the address limit forthe R process is 4GB (rather than 2GB or perhaps 3GB)....The

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

Page 6: Quantitative Finance Collector

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

Search & trial.

Tags - r , csv

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

Page 7: Quantitative Finance Collector

Excellent Free CSV Splitter

Share an excellent free CSV splitter I found recently, as my csv file is toolarge to be openned in Matlab & R, I have to split the csv into severalsmaller 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 bevaried across computers), while my tick-by-tick corporate bond data hasnearly 30,000,000 number of rows.

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

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

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

Page 8: Quantitative Finance Collector

Isin Cusip Conversion

Long time no blog. Just to let you know I am still alive, busy with myown PhD research, collecting & cleaning data, programming, making myhands dirty...

Data massaging is not fun, what makes us more upset is different dataproviders have their own data format, name, code, etc., matching thedata from several sources is not so easy, for example, WRDS includesCUSIP code while Datastream provides ISIN. I didn't understand whythey do business like that but now I get it, similar as those cell phonemanufacturers have distinct chargers and plug-in, not because it's hardto standardize, but a way to impose customers to use always their ownproducts.

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

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

As always, I have been looking for guest writers.Tags - isin , cusip

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

Page 9: Quantitative Finance Collector

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 dataminers to take on the big investment banks in predicting the outcome ofthe World Cup. Now that the final has been decided, we can take a lookat how Kagglers stacked up against the quants at JP Morgan, GoldmanSachs, UBS and Danske Bank in forecasting the World Cup.

In total, 65 teams participated in the Take on the Quants challenge. JPMorgan finished 28th, Goldman Sachs 33rd, UBS 55th and Danske Bank64th. The betting markets fared better, finishing 16th.

The winner of the competition was Thomas Mahony, an Australianeconomist. His approach relied on Elo ratings with an adjustment forhome country/continent advantage. His strategy correctly tipped Spainto win, the Netherlands to finish second and Germany to finish in the topfour. The investment banks all had their top picks bow out early (UBS,Goldman Sachs and Danske Bank picked Brazil and JP Morgan pickedEngland), hurting their overall performance.

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

Tags - quant , world-cup

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

Page 10: Quantitative Finance Collector

Send SMS in Matlab

Ros is a colleague of mine in the same office, his main research isempirical analysis of different option pricing models, and as a result, heoften 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 tocome back office frequently to check which computer has finished thetask. It sounds boring, why not write a small script to send SMSmessage 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 Matlabfrom your gmail box to your cell phone carrier, and then your cell phonecarrier forwards the email to you as a text message.

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

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

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

So what you need to do is to put the function send_text_message at theend of your file, it will then send you a message automatically, forexamplesend_text_message('079-123-456','UK', 'Desk 12 Calculation Done','Nowyou can shut down the computer')

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

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

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

Page 11: Quantitative Finance Collector

following errors:1, ??? Error using ==> sendmail530 5.7.0 Must issue a STARTTLS command firstThis could happen for MATLAB 7.1 (R14SP3) and before, you may haveto upgrade your version.

2, Could not connect to SMTP host: smtp.gmail.com, port: 25;Connection timed out: connectThis is due to your firewall or anti-virus software setting. you are notallowed to send email from port 25. What you shall do is too add anexception and let your computer know this action is safe. For instance, Ihave McAfee, to add an exception, open its control console -> doubleclick access protection -> anti-virus standard protection -> prevent massmailing 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 andpassword at the beginning of the file.Tags - matlab , sms

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

Page 12: Quantitative Finance Collector

Excellent R Code Format Package

I have been looking for this type of package for several days, and luckilyfound it today. Unquestionable R is powerful, however, R programmingis unfriendly as far as I concern, mainly due to the lack of formatshortcut, which makes the R codes rather ugly. (It is an absoluteadvantage of Matlab, for example, ctrl+R for comment, ctrl+T foruncomment, ctrl+I for smart indent, etc.)

FormatR is the package for tidying R source code, although it is lessconvenient to use than the straightforward shortcuts in Matlab, thispackage is good enough for me, what is it for? as the title suggest:QuotationformatR: 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.htmlTags - r

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

Page 13: Quantitative Finance Collector

Simple Dummy R GUI Generator

Imagine you finish a dirty coding project and want to present to yourboss who is not in a good mood (may not be occasionally), how are yougoing 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 waysince you are supposed to introduce in a few short sentences. Generatinga GUI is probably the quickest / easiest way of understanding what thiscode 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 whencreating the Matlab-GUI equity derivative calculator. It becomes evenworse in R language, to be honest, I hate the graph plotting in R, terriblyunflexible compared with in Matlab. Luckily I came across a good R GUIpackage named "fgui", it does as its description: Rapidly create a GUIinterface for a function you created by automatically creating widgets forarguments 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 toothers a rough idea. One line code is enough.

For a simple example, I create a European option pricer with BlackScholes 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 thefollowing coderes <- gui(EuropeanOption,argOption=list(CallOption=c("TRUE","FALSE")))

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

Page 14: Quantitative Finance Collector

It returns a GUI looks like

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

Interested readers shall download the package "fgui" at http://cran.r-project.org/web/packages/fgui/index.htmlTags - r , gui

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

Page 15: Quantitative Finance Collector

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 fortechniques to better predict stock price movements. The 2010 INFORMSData Mining Contest takes aim at this goal, requiring participants tobuild models that predict the movement of stock prices over the next 60minutes.

Knowing whether a stock will increase or decrease allows traders tomake better investment decisions. Moreover, good predictive modelsallow traders to better understand what drives stock prices, supportingbetter risk management. The results of this contest could have a bigimpact on the finance industry.

QuotationCompetitors will be provided with intraday trading data showing stockprice movements at five minute intervals, sectoral data, economic data,experts' predictions and indices. We have provided a training databaseto allow participants to build their predictive models. Participants willsubmit their predictions for the test database (which doesn't include thevariable being predicted). The public leaderboard will be calculatedbased on 10 per cent of the test dataset.

The submission deadline is October 10th 2010. Final results will beannounced on October 12th. The winners of this contest will behonoured at a session of the INFORMS Annual Meeting in Austin-Texas(November 7-10).

Check the detail of this competition at http://kaggle.com/informs2010Tags - prediction , competition

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

Page 16: Quantitative Finance Collector

Debugging Your Thinking

QuotationWriting program code is a good way of debugging your thinking - BillVenables

Believe it or not, on average programmers spend 70% of their workingtime in debugging (I don't know where this number is from but I dobelieve so). A good debug tool, command or even habit will definitelyimprove your work efficiency, shorten working hour, and enjoy morethe world cup. When it comes to Matlab and R, I have to say thedebugging in Matlab is straightforward but is more comprehensive in R.Here is an introductory video demonstrating how to debug andunderstand Matlab codes:

Also a very good PDF document for debugging in R with detailedexamples at http://www.biostat.jhsph.edu/~rpeng/docs/R-debug-tools.pdf. Enjoy.Tags - debug

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

Page 17: Quantitative Finance Collector

Forex Market Strategy Guide: Scalping 101

There are multiple ways of profiting in forex, including swing trading ortrend following. However, scalping is the method with the shortesttrading periods. With this method, traders usually open a trade for 1-2minutes, or 5 minutes at the very most. The idea is to benefit from shortfluctuations in the market.

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

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

Of course, this limited exposure leads to a second major characteristic ofscalping—a large number of trades. Some scalpers may open and closeas many as several hundred trades within a single trading day.

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

A third characteristic is the fact that scalpers rely on some type ofleverage. The profit from each trade is generally quite small, and evenwith a huge number of orders, the results would hardly be worthy of theeffort. Depending on the amount of leverage you use, this can eliminateany real security. In spite of their arguments to the contrary, scalpers canlose a day’s work in a few bad transactions.

A fourth characteristic of scalping is that it is generally a full-timeendeavor. This is a significant limitation, since the majority of forextraders only do it in order to supplement their income. Scalping requiresconstant 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

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

Page 18: Quantitative Finance Collector

any other distractions. This is unworkable for many traders, thoughwhen 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 kitshave become available for scalpers. Unfortunately, most of these areunproven, and many make wild claims that stretch far beyondplausibility. Still, there is a real benefit in automating certain parts of theprocess. For instance, you might use software to execute redundant taskslike stop-loss, take profit and other orders, while doing the analyticaltasks yourself. In this limited role, the automation can be a significanthelp by allowing you to execute more trades with less drudgery.

Scalping is a workable strategy if you know what you are doing and arewilling to dedicate your full time energy to forex trading. Unfortunately,too many beginners try scalping based on the assumption that they canavoid risk. As any experienced investor knows, risk accompanies anygenuine financial opportunity. After several months of practice, and withplenty 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 whengetting started.

The first step in any guide on scalping is understanding how scalpersactually make money. What does a scalping strategy look like in dailypractice?

We already mentioned that scalping involves entering and exiting themarket 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 takesadvantage of volatility rather than trending, ranging, or fundamentalanalysis. 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 inliquidity, or other temporary abnormalities. For instance, a news shockor some other factor might suddenly increase demand for the yen.During that time, there will be a need for liquidity as too many peopledemand the yen with insufficient supply. The spread between bid andasking price will temporarily widen. A scalper might recognize that the

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

Page 19: Quantitative Finance Collector

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

This means that scalpers actually benefit from volatility by trading onthe assumption that prices will stabilize again. It’s not hard to see thatafter a major event, prices routinely zigzag for several minutes beforesettling again. Since this is an emotional over-reaction, a scalpermaintains 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 themicro-volatility of the market. They actually profit by dragging irrationalprice-spikes back to meaningful levels. One other implication is that themost important time for a scalper is just after a market shock. Scalperspay careful attention to announcements of economic data or news shocksand the disruption that follows.

But these observations lead to the other major topic of thisarticle—leverage. The inherent limitation of trading on micro-volatility isthat it will never be very significant. Therefore, scalpers use surprisingamounts of leverage to make their trading more potent. Their leveragemight range from 5:1, all the way up to 50:1. These kinds of leveragewould be simply intolerable for other traders, but the important thing toremember is the short duration that scalpers use. During this time, thereis little opportunity for wide swings in the market that would riskmassive losses. It is also crucial to always use a good stop-lossmechanism and not adjust it for individual trades. If these measures aremaintained and a trade turns out badly, it will be closed in a matter ofminutes or even less when the stop-loss level is reached.

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

Scalping is an interesting strategy because it takes advantage of

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

Page 20: Quantitative Finance Collector

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

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

One of the most important foundational issues is choosing the rightbroker. In some cases, a brokerage may even have a stated policy againstscalping. Without the right platform and broker, you simply have nochance of success. But what should you be looking for?

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

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

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

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

Page 21: Quantitative Finance Collector

There are several other things that can make scalping impossible. If thetrades take too long to process (slippage), the price difference willquickly make trading unprofitable. Therefore, you should always lookfor efficient execution of your orders. Similarly, price quotes mustalways 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. Forthe most part, this should include the same financial tools that trader’swant with other strategies. Of course, you should look for an interfacewith a full range of execution tools. But in particular, the interface needsto be fast and easy to use. This is important because of the number ofrapid orders that must be made. Customization is also a big advantage,as well as automation. You should also pay attention to the visualappearance of the interface. Scalping requires intense focus, and manytraders report eye-strain after a long day of staring intensely at a screen.

In short, you should consider every angle before committing yourself toa particular brokerage or a trading platform. Be upfront from thebeginning with your broker. If you try to use this strategy through asystem that can’t handle it, the brokerage will intentionally make tradingimpossible. Of course, you should also be confident that your brokerisn’t fraudulent. Most of all, you should never try to use scalpingthrough a broker with wide spreads or other excess costs. The net resultwill 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 shouldknow about scalping.

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

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

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

Page 22: Quantitative Finance Collector

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

Another group can be called carry pairs. These currencies are liquid, butmuch more volatile than the majors. A good example here is theJapanese Yen. Interest rates are very high on the Yen, and manyinvestors also use the currency for risky assets. One of the results is thatmarket shocks will have extreme results that might result in very widespreads. Within a scalping strategy, this might result in extreme lossesthat a stop-loss order cannot protect from. Furthermore, excessivevolatility can be quite unpredictable. Therefore, it is generally best forbeginners to stay away from pairs that involve the Yen (JPY) or othercarry pairs.

Finally, exotic pairs involve small or developing nations with a lowvolume of trade. Examples might include the Norwegian Krone (NOK),the Turkish Lira (TRY), the Brazilian Real (BRL), or any of thedeveloping currencies. These pairs are quite unpredictable, and oftenrun into significant liquidity problems. Trading with one of these is asignificant risk.

Any experience trader also realizes that the markets change during thecourse 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 theopening of the New York market. Late morning brings higher volatility,but also great liquidity. Many announcements also direct the marketduring this time. Early afternoon tends to be quite choppy, with higherrisks but potentially greater profits. Late afternoon sees the closing ofmost large banks in developed countries, and the market becomes itsquietest.

Really, your preference for each of these times depends on your style. Inchoppy conditions, scalpers should look for shorter trades withoutconcern for directionality. Of course, during the time that the marketsare open, there should be more attention to larger trends, and the

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

Page 23: Quantitative Finance Collector

possibility of more extended trades.

All of these factors are significantly influenced by your particular styleand your experience. Risk may be just the thing if you know how tohandle it, and experienced traders often had straight for more volatiletimes and currency pairs. If you’re only beginning, the key is to stay withmajor pairs and avoid times of wild fluctuations. Learn how to predictthe market with low leverage and minimal risk. Once you’ve seen andhandled various market conditions, you can consider taking bigger risks,and pursuing larger profits.

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

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

The more important point to recognize is that scalping varies drasticallyaccording to conditions. At times the distinction between scalping andother strategies is quite unclear. For instance, if a scalper opens aposition and then observes a longer profitable trend, it only makes senseto take full advantage of it. Depending on what is happening, a tradermight switch back and forth between all of the strategies, or form hisown hybrid.

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

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

Page 24: Quantitative Finance Collector

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

A second, related point is cool-headed thinking. When markets becomechaotic, it is easy to be controlled by the volatility and make foolishmistakes. At those times, remember your strategy and follow itassiduously.

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

Finally, it is imperative to know yourself. Know what style works wellfor you. Observe what market conditions tend to reap the best profits foryour trading. At certain times, it may be best not to trade at all. Whenyou recognize that conditions mirror what has worked well for yourstrategy in the past, you should jump into the market fully.

Beginning traders sometimes assume that scalping is the easiest way toearn a quick profit. However, scalping is actually one of the mostchallenging strategies. Some scalpers suffer losses at the beginning, butwith a lot of practice, discipline, education, and the right tools, thismethod can be one of the most profitable forex strategies.

Tags - forex , trading , strategy

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

Page 25: Quantitative Finance Collector

Excellent Yahoo Finance Data Downloader

Although I have shared several ways to download data from YahooFinance, for instance, Yahoo chinese historical stock data, downloadoption price data from Yahoo, I have to admit the one I recommendtoday is the best and most comprehensive ever. It supports dozens oftags to download, besides what we normally need for closing price,volumn, daily high, and daily low, including (click the graph to see aclearer picture):

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

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

Page 26: Quantitative Finance Collector

R Sapply Problem

Any expert in R please educates me. I have got a problem about thesapply (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, andto 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 usez <- sapply(1:10, function(i, x) {mean(x[1:i])}, x)

It went well, but what if besides computing z, I need to update anothervariable, for example, with loop, it istemp <- 3for (i in 1:10) {x[i] <- x[i]-tempz[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 functionof z[i]). How to vectorize that and use sapply then? since sapply can'treturn two variables z and temp.

I tried to define a matrix and store z in the first column and temp in thesecond 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'sgood.

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

Page 27: Quantitative Finance Collector

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 <- 3for (i in 1:nsim) {x[i] <- x[i]-tempz.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] <- 3z.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.tempz.sapply[i] <- tempz.sapply[i+1] <- z.tempz.sapply[i:(i+1)]

}, x, z.sapply, simplify =TRUE)y$z.sapply <- z.sapply[seq(2,2*nsim, by=2)]y

}

Tags - r

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

Page 28: Quantitative Finance Collector

R for Matlab Users

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

One bothering issue is each software has its own coding rules, forexample, in Matlab we use a(1,1) but in R we use a[1,1]; in Matlab wehave 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 similarway). It does bring me trouble sometimes, luckily I came across a webpage similar as cheat-sheets, it lists those widely used commands in Rand 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 of47 pages, fantastic! http://www.math.umaine.edu/~hiebeler/comp/matlabR.pdfTags - r , matlab

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

Page 29: Quantitative Finance Collector

South African World Cup

Today is the first day of South African world cup. Disappointing Frenchteam, although JP Morgan's Quant group members use their model topredict England will win this world cup Championship, I still go forNetherlands. GO GO GO, Holland.

A funny graph showing the characteristic of each team, enjoy footballeveryone.

Tags - football

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

Page 30: Quantitative Finance Collector

Exclusive Offer: Download $79-value Vertical Spreadsoptions trading ebook for free

A guest post from our Elliott.

Dear reader,

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

The new ebook, How to Use the Elliott Wave Principle to Improve YourOptions Trading Strategies -- Vertical Spreads, which sells in EWI'sonline store for $79, is available for free, exclusively to you, for a limitedtime.

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

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

Page 31: Quantitative Finance Collector

An Interest Rate R Package Plan

I recently have done some empirical studies on zero-coupon bondmodelling and pricing, and plan to create an interest rate R package inorder 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

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

Page 32: Quantitative Finance Collector

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 nothard, it IS in Windows, as R is designed in a Unix environment whichincludes a set of compilers, programming utilities, and text-formattingroutines while Windows lacks those. I used to build an R library in Unixand thought it was relatively as the same convenient as in Windows, butit turned out I had to spend several hours on it. Silly me.

Below are the selected steps to create an R package in Windows Isummarize: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, availableat http://www.miktex.org, http://msdn.microsoft.com/en-us/library/ms669985.aspx, and http://www.jrsoftware.org/, respectively. Forexample, Microsoft HTML Help Workshop is for making HTML Helpdocuments, LaTex is for a nicer outlook, especially when yourdocuments have math equations.

3, double click Rtools.exe to install it and its accompanying tools:minGW, perl. Rtools automatically recognizes the paths of those relevantsoftwares and add them to the environment variables of your computer.

4, check and change your PATH “environment variables” of yourcomputer 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 andselect 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 ofoptions, otherwise re-install or check the path if you see “… is not a

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

Page 33: Quantitative Finance Collector

recognized as an internal or external command …”

6, start R and run the command package.skeleton( ) with suitablearguments, read the help http://stat.ethz.ch/R-manual/R-patched/library/utils/html/package.skeleton.html for detail. For instance, I writea 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 toadd to the package MonteCarloPi. This function creates the directory treefor the package containing:DESCRIPTION <<man <<< for documentationR <<< for R function definitionssrc <<< for low-level source code (this is optional for other programmingfiles, 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 theabove directory with notepad or other tool, for instance, to add theauthor information and Help explanation.

8, open a “command prompt” window, change the directory to whereyour package is, type the command “R CMD build MonteCarloPi” tobuild the package, this will generate a file calledMonteCarloPi_1.0.tar.gz. You must run the command in a “commandprompt” 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 INSTALLMonteCarloPi_1.0.tar.gz”. Congratulations if you see “…done…” andyou will notice there is one more sub-folder “MonteCarloPi” in your Rlibrary folder.

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

MonteCarloPi <- function(nsim){

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

Page 34: Quantitative Finance Collector

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

}

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

Tags - r , package

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

Page 35: Quantitative Finance Collector

15 Incredibly Stupid Ways People Made Their Millions

A selection of stories outlining the stupid ways people madetheir millions.

Inventions are important. They're the reason life has become so easy forus, and technology so accommodating. The market for inventions isenormous, and hundreds of new ones are patented every day. Since noteveryone is a genius, many of them fall into obscurity immediately asinefficient or unimportant ideas. However, sometimes the silly ones wemight be quick to dismiss are unexpectedly more profitable than theconventional 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 aboutanything. It's literally a rock with googly eyes glued to it, but theinanimate companion grossed a couple million dollars in 1975. The fadonly 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, provedirresistible 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 searchfor the bathroom. But what if you’re out in public and don’t know whereto find one? Poppin’ a squat it picking a dark corner isn’t always anoption, and many establishments have bathrooms restricted foremployee or customer use only. Conveniently, anyone with a cell phonecan now find the nearest public restroom just by texting a short numberfor a small fee.

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

Page 36: Quantitative Finance Collector

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 amillion dollars off the idea. Giving dogs goggles is about as useful asgiving a goldfish a monocle and cane, but that didn’t stop the companyDoggles from doing their very best. At $80 a pair, Doggles is a multimillion dollar company.

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

4. Million Dollar Homepage

How much is a solitary pixel floating around in cyberspace worth? AlexTew thought $1 per pixel was a reasonable price. Tew was just about tobegin studying business at the University of Nottingham, but the idea hecame up with to fund his education proved that he already possessed thesensibility of a successful businessman. Tew bought a web domain, laidout an area of 1,000,000 pixels, and sold them in 100-dollar blocks. Adsranged from online casinos, to Target and everything in between. Thiswas The Million Dollar Homepage.Tew came up with the idea inAugust of 2005, and by New Year’s Eve, every pixel bar but one hadbeen sold. Not only did Tew make a whopping $ 1,037,100 gross from hisrelatively simple idea, but he also managed to attract some big nameclients, like Tenacious D.

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

Page 37: Quantitative Finance Collector

5. Mungo & Maud’s Petite Amande Dog Fragrance

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

Another case against Petite Armande is that dogs have an exponentiallystronger sense of smell than humans do. The animal most likely finds itunpleasant to be sprayed with irritating odor concentrates. If the smell isstrong to us, it must be a billion times stronger for the dog. Suityourselves, perfumed-pup-lovers, just don’t complain when Timmy’sstuck in a well an you bloodhound Biff can’t find him because his senseof 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 definitelysaying a lot, considering the cavalcade of weird stuff that’s preceded it.Wishbones are traditionally considered lucky, and are taken from ananimal (which is typically being consumed) to break in half between twopeople. Holding each end of the tiny bone, the two parties pull until itsnaps, and decide which player is the ‘lucky’ one according to who hasthe larger portion. However, Lucky Wishbone Co. doesn’t sell realwishbones. 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

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

Page 38: Quantitative Finance Collector

Get a postal address in the North Pole, pretend you are Santa Claus andcharge 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 businessin 2001, meaning he's made a multi-millionaire dollar fortune.

One of the best ways to make money out of people has always beentaking advantage of their naïveté and dreams, and who's more naïvethan kids? Byron Reese, sprung for a postal address in the North Pole, aplace he'd never been, so he could pretend to be Santa. Even worse thanthe mall Santa who lets kids sit on his lap and drinks malt liquor in theparking lot, in some intangible way.Reese writes back to the letters himself, but never reveals his trueidentity. At first, this sounds quite sweet, but consider this: What if littleSusie (they are always called Susie) wants a little doll which Mommyand 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 hoho!’ but then Jessica’s parents buy her a really awesome pony with aBose sound system and five LCD monitors? Then Santa all of a suddenseems nonexistent. Another million-dollar idea, this time one thatdepersonalizes one of the most beautiful mysteries of childhood bymaking 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 towaste your creativity on coming up with your own excuse? The ExcusedAbsence Network is a service which caters to all the lying employee’sneeds; from a missed math test all the way to skipping out on your ownwedding. The notes aren’t just those ‘little Johnny had a sore throattoday’ notes from mom – these are excuse notes that look as though theycome from a hospital or doctors office for just $25 per note.

9. Fetal Greetings

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

Page 39: Quantitative Finance Collector

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

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

10. www.MannequinMadness.com

Mannequin Madness is a website that sells second-hand mannequins atthird-hand mannequin prices. They boast that that have ‘the perfectbody for you to buy or rent’ and the second-hand mannequin business isbooming. The website stresses that the mannequins aren’t only good fortraditional uses, like showing off clothes and making you feel bad aboutyour body type. The website also suggests they be used for practicaljokes and Halloween displays (read: causing heart attacks).

11. Big Mouth Billy Bass

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

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

Page 40: Quantitative Finance Collector

12. www.ICanHasCheezburger.com

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

13. One Red Paperclip

Kyle McDonald may not be a household name, but he’s definitelyinternet-famous, and he definite has a household -- one that he tradedhis way to from a solitary red paperclip (which, to be honest, looksused). It only took Kyle exactly one year and fourteen trades to make hisway from a twisted piece of metal to a home for his family. Along theway, he travelled to the far reaches of Canada, all across the US, metAlice Cooper and Corbin Bernsen, and basically had one hell of a goodtime.Finally, Kyle settled with a home at 503 Main Street, Kipling,Saskatchewan, Canada, and he still lives there to this day. His storystands as an example of how you can start with absolutely nothing, andthen one day live in Canada.

14. Murder Clean Up

What is an ambitious real estate flipper to do with the abandoned housewhose floors have been ravaged by the waste and habitation of a feral catcommunity? What about the family whose estranged hoarder aunt dies

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

Page 41: Quantitative Finance Collector

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

15. Eternal Reef

Another death-related business is Eternal Reefs, a service which providesunderwater urns for individuals cremated after death. The cement globecontains holes to encourage plant growth and allow fish to swim in andout of your loved one’s ecologically friendly grave. Those purchasing theEternal Reef are allowed to press their hands into the soft concrete, orattach a flag or sorts as a means of marking their reef. Eternal Reefs havea profit of about half a million per year.

Tags - money

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

Page 42: Quantitative Finance Collector

Matlab File Style

Programming style, a set of rules or guidelines used when writing thesource code for a computer program, is important for a programmer, itnot only allows the reviewers to know the date and author of the file, butalso helps the programmer himself to track the file version and improvework efficiency. Nevertheless, repetitive comments, especially for theheader part are boring. Uncomment is even more boring, read Matlabcomment 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 specificstructure which helps for creating the main function structure. The actualworking MATLAB Version will be also captured. For example, runningnewfcn('testnewfcn') generates a file named testnewfcn.m at a pre-defined style, the new file looks likefunction 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.mto the appearance you like? just that simple!

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

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

Page 43: Quantitative Finance Collector

Mathematica Home Edition

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

That's why I only got to know the existence of Mathematica HomeEdition today despite the fact it has been in the market for over one year!What is Mathematica Home Edition? as the webpage shows:QuotationMathematica Home Edition gives home users Mathematica's powerfultechnology, developed over 20 years and used by Nobel-winningscientists and leading corporations. It provides access to curated data,makes it easy to create and share interactive applications, and a wholelot more.

It can be used for:Calculate mortgage, credit card, car, and student loan paymentsEvaluate currency exchange ratesMonitor stock market returns and predict trendsAnd much more...

In short words, Mathematica Home Edition contains the same functionsthat can be found in Wolfram's Mathematica 7. it is the full version ofMathematica but at reduced price for recreational or personal use.

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

PS: this post is by abiao, not by bo.Tags - mathematica

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

Page 44: Quantitative Finance Collector

FinMetrics

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

QuotationFinMetrics is MATLAB based, open source quantitative portfoliomanagement environment. Built on concepts of bottom-up approach toapplication design, it allows users to define most basic, low levelbuilding blocks, e.g. assets and transactions, to be further pieced togetherin a higher level objects, e.g. positions or portfolios. Data analysis andstatistics function, implemented within the environment and native toMATLAB, enable users to conduct scenario analysis, stress testing,performance measurement and attribution, risk measurement andattribution, design hedge strategies, etc. Open architecture of theenvironment allows users to work with objects of any level, dependingon their requirements and expertise. The object structure and data typesare specifically designed to make integration with MATLAB and nativeFinMetrics functions as easy as possible. FinMetrics user interfaceapplication and MATLAB scripting may be utilized to facilitate orautomate complex and repetitive tasks, as well as extend functionality ofthe environment.

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

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

Page 45: Quantitative Finance Collector

Flash Order

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

Some regard this as an unfair advantage as professional traders wouldgain advance knowledge on trends before individual buyers. Others saythat it adds ‘liquidity’ to the stock market. This opinion comes, of course,from the big businesses who are using the flash order service to theiradvantage to gain a profit. The problem is in the shifts that this bringsabout. For example, the big business might buy all of a certain stock, andthen sell it for a bit more than they bought it, but a penny less than whatthe next guy is offering it for. This advantage causes motion in a violentmanner in ways that would not be present in normal conditions. Whilethis 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 messpeople over. Those with a leg up can make an investment risk-free, andit is only risk-free for them because all of the risk falls on to the lowertier. So far, it has upset enough people to be at risk for banning. Thestock market has become a beast to be weary of these days. If this unfairadvantage doesn’t go, what’s to ensure equality in the future?Fortunately the flash order business will very likely be taken away asmore 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

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

Page 46: Quantitative Finance Collector

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, mathsequations, 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 extremelysimple with the cell mode in Matlab, it generates report automatically forus, any change you make regarding description, codes and results willbe 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 aname for each section, similar with the title for chapters in Word;Fourth, depending on your reports, inserting Text Markup, where youare able to insert description text, bold text, etc. most importantly, itsupports TeX equations;Finally, clicking "Publish to HTML", a nice-looking report is generated,and if necessary, changing the codes and re-running to update thereport.

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–Scholesparameters% 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)$$

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

Page 47: Quantitative Finance Collector

%% $$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 onlyplot(5 (1:10), call1)

The final report is shown at http://www.mathfinance.cn/attachment/CellPublishDemo.html, looks fantastic.Tags - matlab

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

Page 48: Quantitative Finance Collector

Matlab Comment Stripping

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

Needless to say, comment is crucial for programming, it helps ourselvesto debug our thoughts and other colleagues to understand the codesefficiently, which is especially indispensable as each programmer has hisown coding style. However, under certain circumstances we may haveto 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 fora small file, but generally we may end up with a file with dozens, if nothundreds, lines of comments, what's worse is those comments intersectand we have to be carefully to find them out.

Here is a clever way, MATLAB Comment Stripping Toolbox (it indeedhas only 3 short files if you are afraid by "Toolbox" ). Basically it is asmall collection of utilities for stripping MATLAB comments fromMATLAB 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 strippingcomments from multi-line strings, that is strings with embeddednewlines, 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 thecomments and rename it as test-client.m:% test the comment strip command using mlstripcommentsfile(infile,outfile)% by abiao @ mathfinance.cna = rnorm(10,1); % check if you can remove me% one more lineb = 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

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

Page 49: Quantitative Finance Collector

a = rnorm(10,1);

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

rnorm(3,3);

Nice, isn't it? you can download the toolbox athttp://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 defaultbehavior." You may choose to modify the codes by deleting 'tokenize'.Tags - matlab

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

Page 50: Quantitative Finance Collector

Financial Scams

A guest post of Bo.

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

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

It is these relics or mock-ups of them that are sold to you by theconartists. Normally with very official looking documentation and afteryou’ve been hopped from bank to bank, you find out that it is in factworth nothing except maybe some sentimental collector’s value. If yourlucky, it may actually be an actual Bond, in which case you could get asmall amount of money from a museum that hosts them. This is truly agreat demonstration of one of the historical financial scams.

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

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

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

Page 51: Quantitative Finance Collector

Tags - scam

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

Page 52: Quantitative Finance Collector

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 developmentand Adobe Flash media design. On the web sitehttp://www.varcalc.com.au, it provides a series of innovative andcomprehensive financial calculators for both Australian andinternational investors. These online tools cover many aspects of financeand investment like home loan & mortgage, savings, personal finance,bond and financial derivatives. The VarCalc will launch new calculatorsregularly.

Tags - calculator

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

Page 53: Quantitative Finance Collector

Log Normal Distribution

A guest post by Sidharth Mallik.

The lognormal distribution is used extensively as an approxmiation tothe 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 andthe resources are even more limited. I tried finding books about thelognormal 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: Theoryand Application, Dekker, New York.

among all the books on statistics and millions of resources on normaldistribution the exponential counterpart only has two genuine referencebooks.

However my job is to give you some light in the matter. Lets start withthe 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(\lnx-\mu\right)^2}{2\sigma^2}}cdf: \frac12 + \frac12\,\mathrm{erf}\Big[\frac{\lnx-\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}\!\! - 3entropy: \frac12 + \frac12 \ln(2\pi\sigma^2) + \mumgf: (defined only on the negative half-axis, see text)cf: representation

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

Page 54: Quantitative Finance Collector

\sum_{n=0}^{\infty}\frac{(it)^n}{n!}e^{n\mu+n^2\sigma^2/2} isasymptotically divergent but sufficient for numerical purposesFisher 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 athttp://en.wikipedia.org/wiki/Log-normal_distribution.

now for the estimation properties. well conviniently you would want toestimate the mean and the variance of the corresponding logarithmicdistribution which happens to be normal and then may be use the aboveformulas to find the lognormal's parameters. but there is error associatedwith this.

An example of the error is :

say you decide on a parameter m as the mean of the correspondingnormal distribution and sigma^2 as the variance. the you may say thatthe 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 unbiasedestimator. Let E[.] denote the expectation of the quantity within thebrackets and let M denote the mean of the lognormal distribution.Then ifthe 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 knowwhat this is refer to the http://en.wikipedia.org/wiki/Jensen_inequality.

Hence there are problems with this form of the estimation. So i wouldredirect you to this page check out some other ways how this can bedone

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

Page 55: Quantitative Finance Collector

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

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

The parameters in this case are the two means, the two standarddeviations and the correlation coefficients. Now the natural question ishow 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 checkthe 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 applythe lognormal distribution. Now first identify if the variable under studyis throughout positive or not like a stock price. Next identify the fact thatthe variable contains kind of multiplicative factors in the sense that saythere are levels to the quantity in multiplicative terms. What I mean tosay is that the variable has let us say a level r on normal days.Then whenyou expect the variable to go up it goes upto 1.5 times r then even highermeans that it goes to say 5 times r. Similarly for the lower side. If yourvariable is indicative of this then it suggests a lognormal distribution.

Tags - distribution

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

Page 56: Quantitative Finance Collector

Black Litterman Model (II)

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

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

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

Case 1: Based on the simulated data, we consider a practitioner who hasa 10 bp steepening view on the 2-20 spread and a 5 bp bullish view onthe 2-5-10 butterfly, Further, we assume that those views are uniformdistributed, and the confidence level is 25% in both views. The resultsare:

Compared with table 1, we notice the means of 2y and 10y are decreasedsignificantly, and the means of 5y and 20y are increased, which areconsistent 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-20spread and a 5 bp bearish view on the 2-5-10 butterfly, other things beingequal. We expect that the means of 2y, 5y, 10y and 20y change anotherway around.

as expected, the means of 2y and 10y are increased significantly, themeans of 5y and 20y are increased, and the means of 6m and 30y are

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

Page 57: Quantitative Finance Collector

again the same as those of prior market.

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

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

Based on the posterior market values we are able to do return mappingand portfolio optimization.

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

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

Page 58: Quantitative Finance Collector

Black Litterman Model (I)

Black-Litterman model is widely used for asset allocation, however, mostof its applications are based on the assumption of normally distributedmarkets and views. In this paper Beyond Black-Litterman in Practice: AFive-Step Recipe to Input Views on Non-Normal Markets, the author AttilioMeucci extent the Black-Litterman model to allow non-normaldistribution assumption, specifically, skew t distribution is used formarkets and uniform distribution is for investors views as examples. Theauthor 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 prosand cons of Black litterman will be discussed, and a robust analysis willbe shown to demonstrate its consistence.

Markowitz mean-variance model is the foundation of modern portfoliotheory, it tries to maximize return and minimize risk by carefullychoosing different assets. Although Markowitz model is widely used inpractice in the financial industry, it has at least the followingshortcomings. First, in principle the Markowitz model offers a solutiononce the expected returns and covariance of the assets are known.Although the covariance of a few assets can be adequately estimated, it isdifficult to come up with reasonable estimates of expected returns. Initialestimates often lead to extreme portfolio solutions and have to beadjusted many times before they can be considered acceptable by thedecision makers. Second, Markowitz model assumes the futuredistribution of assets returns will be exactly the same as that of historicalreturns, therefore it does not allow an investor to have views on thedirection of assets growth.

Black-Litterman model bypasses these problems by not requiring theuser to input estimates of expected return; instead it assumes that theinitial expected returns are whatever is required so that the equilibriumasset allocation is equal to what we observe in the markets. The user isonly required to state how his assumptions about expected returns differfrom the market's and to state his degree of confidence in the alternativeassumptions. From this, the Black-Litterman model computes thedesired mean-variance efficient asset allocation. It is right because of thischaracter that makes Black-Litterman model be popular both in industryand academia since it was initially developed in 1990.

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

Page 59: Quantitative Finance Collector

However, the original Black-Litterman model helps portfolio managersto compute the distribution of the posterior market that incorporatestheir subjective views with respect to the prior distribution. All theseassumptions are being made considering the entire scenario is normallydistributed. In fact, it is frequently observed that returns in equity andother markets are not normally distributed. At the same time, you wouldexpect a practitioner to input his views in a less informative manner. Forinstance, instead of a view like ‘I am 90% sure that stock A will have a2% expected return’, he may have a more accurate view such as ‘I am90% sure that the return of stock A will stay between -1% and 1% withequal chance’, or for an Asian option Trader, his views may be a set ofprices at several specific monitoring times, when the option is supposedto be exercised.

Meucci (2006) solves the above-mentioned issues of the original Black-Litterman model by developing an approach called Copula-OpinionPooling (COP), the author relaxes the normal distribution assumptionand in principle allows any distribution. However, the proposedimplementation in the paper has a distinct distribution under certainassumptions. Indeed, the market has been assumed to be skew-tdistributed, this strong assumption makes the application of theapproach less evident, although the implementation is prettystraightforward for any distribution by Monte Carlo simulation, becauseMonte Carlo simulation can be applied for almost any distribution and issuitable for any dimension (at least in theory), COP approach can handlea portfolio with any number of risk factors.

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

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

Page 60: Quantitative Finance Collector

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 theledger. They were lined up this way—on the bullish side—in lateFebruary-early March of 2009. Today they are just as aligned but on thebearish 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, themonth when the Dow Industrials-plus-Transports combination made itsall-time high. But wait. The latest report pertains only through February.In March, the market rose virtually every day, so there is little doubt thatthe percentage of cash in mutual funds is now at an all-time low, lowerthan in 2000, lower than in 2007! We will know for sure when the nextreport comes out in early May. Regardless, the confidence that mutualfund managers and investors express today for a continuation of theuptrend rivals their optimism of 2000 and 2007, times of the two mostextreme expressions of stock-market optimism ever.

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

3,The VIX, a measure of volatility based on options premiums, has beensitting at its lowest level since May 2008, when wave (2) of ((1)) peakedout and led to a Dow loss of 50% over the next ten months. Lowpremiums indicate complacency among options writers. The quants whodesigned the trading systems that blew up in 2008 generally assumed

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

Page 61: Quantitative Finance Collector

that low volatility meant that the market was safe, so at such times theywould advise hedge funds to raise their leverage multiples. But lowvolatility is actually the opposite, a warning that things are about tochange. The fact that the options market gets things backward is a boonto speculators. Whenever options writers are selling options cheap, themarket is likely to move in a big way. Combined with the readings onthe 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 InvestorsIntelligence poll of advisors (which has categories of bullish, bearish andneutral), reported that more than half of advisors were bearish. InDecember 2009, it reported only 15.6% bears. This reading was thelowest percentage since April 1987, 23 years ago! As happens going intoevery market top, the ratio has moderated a bit, to 18.9% bears. In 1987,the market also rallied four months past the extreme in advisorsentiment. 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. Thereading has been registering highs in the 86-92% range ever since lastSeptember. Prior to recent months, the last time the DSI saw even asingle 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 acontrast in a short period of time.

6,The Dow’s dividend yield is 2.5%. The only market tops of the pastcentury at which this figure was lower are those of 2000 and 2007, whenit 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, hasimproved tremendously, from 122 to 23. But 23 is in the area of the peaklevels of P/E throughout the 20th century. Ratios of 6 or 7 occurred atmajor stock market bottoms during that time. P/E was infinite duringthe final quarter of 2008, when E was negative. We will see quite a fewquarters of infinite P/E from 2010 to 2017.

8,The Trading Index (TRIN) is a measure of how much volume it takes tomove rising stocks vs. falling stocks on the NYSE. The 30-day movingaverage of daily closing TRIN readings has been sitting at 0.90, the

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

Page 62: Quantitative Finance Collector

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

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

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

Page 63: Quantitative Finance Collector

Dealing with Excel Date in Matlab

I was drived crazy yesterday by dealing with the date in Matlab. I haveto download data from different sources, some from datastream, and theothers from Wharton Research Data Services, unfortunately, the date isin different format, either in a double format as 20081125, or in a cellformat as '25/11/2008' (or something similar) after I import the datawith xlsread() command in Matlab.

those different formats really bring a problem, as I need to match thedates and compare the prices, it is easy to convert a cell format date towhat matlab recognizes using cell2mat() and then datenum(), forinstance, 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 string25/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 adouble number I need 20081125, then I am able to use and match thedate from different sources.

It sounds lengthy, do you have a better idea? please share with us byleaving a comment, cheers.

Stanley suggests to use the following code:datenum(datevec(num2str(dates),'yyyymmdd')), here dates is doublenumber, perfect, it is much better than my method as it allows us notonly for date comparison but also for calculation, what's more, it ismore efficient. many thanks, stanley.Tags - matlab , excel

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

Page 64: Quantitative Finance Collector

Kalman Filter Finance Revisited

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

Specifically, Kalman Filter is applied to estimate the parameters of a CoxIngersoll Ross (CIR) one factor interest rate model, (Vasicek model issimplier than CIR, so the latter is chosen as an example), it is a widelyused 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 andimplementation" 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 bykalman filter " and "affine term structure models: theory andimplementation" to understand the transition and measurementequations. Below are the sample Matlab implementation:function [para, sumll] = TreasuryYieldKF()% author: biao from www.mathfinance.cn

%%CIR parameter estimation using Kalman Filter for given treasurybonds yields% check paper ""estimating and testing exponential-affine term structure% models by kalman filter " and "affine term structure models: theoryand% implementation" for detail% S(t 1) = mu F S(t) noise(Q)% Y(t) = A H S(t) noise(R)

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

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

Page 65: Quantitative Finance Collector

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 modeltheta = para(1); kappa = para(2); sigma = para(3); lambda = para(4);%volatility of measurement errorsigmai = para(5:end);R = eye(ncol);for i = 1:ncol

R(i,i) = sigmai(i)^2;enddt = 1/12; %monthly datainitx = theta;initV = sigma^2*theta/(2*kappa);

% parameter setting for transition equationmu = theta*(1-exp(-kappa*dt));F = exp(-kappa*dt);

% parameter setting for measurement equationA = 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 kappalambda)*tau(i)/2)/((AffineGamma kappa lambda)*...

(exp(AffineGamma*tau(i))-1) 2*AffineGamma));A(i) = -AffineAlpha/tau(i);H(i) = AffineBeta/tau(i);

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

Page 66: Quantitative Finance Collector

end

%now recursive stepsAdjS = initx;VarS = initV;ll = zeros(nrow,1); %log-likelihoodfor i = 1:nrow

PredS = mu F*AdjS; %predict values for S and YQ = 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);%updatingKalmanGain = 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';endsumll = -sum(ll);end

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

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

Page 67: Quantitative Finance Collector

Down and Out Call Barrier Option

This post is writen by Jovan, one of our contributors currently studyingMFE, thanks, Jovan.

A couple of weeks ago one of my friends had an interview at a localhedge fund and he had to prepare Greeks of exotics, so we decided toplot them. In Uwe Wystup’s book, Options in FX markets there is a niceand very clear analytical solution, and mathematica 7 is good insymbolic so the code just takes the derivatives and plots them. Also tocheck the solution of down and out call we plotted the down and in calland their payoff combines into a regular call so that there wasn’t amistake. If you do not have mathematica there is a mathematica free fileviewer form Wolfram.

Together with the codes there is a mini manipulate idea where you cansee the interaction of the Greeks with other input parameters such as aBarrier where you see that the delta explodes when you are close toexpiry and to the barriers. Uwe Wystup suggests that then one should doa barrier shift to prevent this so that one should rehedge your portfoliobased on that shifted barrier. If you are interested to see this pleasedownload the attached Mathematica files and check it out.

Click to downloadTags - barrier , option

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

Page 68: Quantitative Finance Collector

Top Ten Sites in Quant and Quantitative Finance

Xmarks is a hot web2.0 site offering bookmark synchronization, searchenhancement and web discovery based on sites bookmarked by users,therefore to some extent it shows the popularity of a site. Personally I useit frequently as it gives me a convenient way to bookmark my favouritewherever I am, no matter using a private laptop at home, or a sharedcomputer at a coffee bar, I am always able to find and read my interestedsites.

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

Quantitative Finance Collector is a Top Site in Quantitative FinanceReview This Site

Quantitative Finance Collector is a Top Site in QuantReview This Site

We have been looking for paid contributors and guest writers, pleaseconsider 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

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

Page 69: Quantitative Finance Collector

Kalman Filter Finance

A general example of Kalman filter algorithm was briefly discussed atthe blog post Kalman filter example, where a Matlab toolbox link wasshared as well. When it comes to an application of Kalman filter infinance, one of the best and ealiest paper is Estimating and TestingExponential-Affine Term Structure Models by Kalman Filter (a simple searchat 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 twospecial cases of interest rate models, namely the Gaussian case (Vasicek1977) and the non-Gaussian case (Cox Ingersoll and Ross1985 and Chenand Scott 1992), besides a detailed description of how to apply thisalgorithm step by step.

Download the programming files of Estimating exponential affine termstructure models at the author's home pagehttp://www.rotman.utoronto.ca/~jcduan/, however, they are inGAUSS language I am unfamiliar with (I used to use it when I studied inGermany seven years ago), so check yourself then.Tags - filter

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

Page 70: Quantitative Finance Collector

48 Hours Left For How to Spot Trading Opportunities

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

The How to Spot Trading Opportunities eBook features 47-pages ofeasy-to-understand trading techniques that help you identify high-confidence trade setups. Senior EWI Analyst Jeffrey Kennedy will showyou how some of the simplest rules and guidelines have some of themost powerful applications for trading.

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

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

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

Page 71: Quantitative Finance Collector

Free Data Directory

Data access is a prerequisite to quant finance study, unfortunately, datais not cheap, I once list the sites where we can download free data atfinancial data download, here is a good free data directory site I cameacross a few days ago: wikiposit - A searchable directory of numericaldata on the internet.

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

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

Tags - data

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

Page 72: Quantitative Finance Collector

Kalman Filter Example

The kalman filter is a time series estimation algorithm that is mainlyused combined with maximum likelihood approach to estimateparameters 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 thatall data is observed with measurement errors, which is one of the bigreasons why it becomes more and more popular in economics andfinance, as many models in these fields depend on data that are eithernon-observable, for example, bond prices are observable but interestrates are not; energy future prices are easily observed but underlyingassets are not, etc.; or subject to noise, such as due to bid-ask spreads.

There are two basic equations of a Kalman filter: the measurementequation and the transition equation, as the names suggest, themeasurement equation relates an unobserved variable (such as interestrates) to an observable variable (such as bond prices), and the transitionequation allows the unobserved variable to change over time, forexample, interest rates follow a Cox Ingersoll Ross (CIR) process.Essentially Kalman filter is a recursive algorithm, it starts with initialvalues 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 measurementequation, 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 thenext time period and finally we are able to estimate the parametersvalues by maximum likelihood. The following steps outline the specificprocedures 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 incorporatingkalman gain matrix and the prediction error;Step 4: forecasting the state vector of the next time period conditioningon the updated values of the previous period;Step 5: calculating the log-likelihood function under a certaindistribution assumption and maximize the log-likelihood, usually aGaussian distribution is applied.

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

Page 73: Quantitative Finance Collector

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

Tags - filter

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

Page 74: Quantitative Finance Collector

What You Need to Know About Option as A Beginner Part II

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

a) Call optionIt 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 particularcommodity or financial instrument (the underlying instrument) from theseller of the option at a certain time (the expiration date) for a certainprice (the strike price). Whereas the seller is obligated to sell thecommodity or financial instrument should the buyer so decide. Thebuyer 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 fora given stock. Let's use the current month for this example. Let yourrequirement be to buy 100 shares of the stock which is currently tradingat $110/share. And you are buying those stocks, not by the way ofoptions, then you would be paying $11000 for the 100 shares. This meansthat you will be losing around $1000 for buying the stocks. But if youwere to use this option contract and if it were to expire at the same stockprice of 110/share then you would have the option to buy 100 shares ofthat stock at $100/share. Thus you can have a profit of $1000; which isnothing but the cost to buy the option. Here in this, lets hope that thestock at the time of expiration will be, say, $115/share and so you wouldend up making $500 over what your option costs were. But of course, ifthe stock price drops to $105/share then you will end up losing $500 onthe deal, which will be the bad part of it.

The option value, and therefore price, varies with the underlying priceand with time. The call price must reflect the "likelihood" or chance ofthe option "finishing in-the-money". The price should thus be higherwith more time to expire and with a more volatile underlyinginstrument. The science of determining this value is the central tenet offinancial 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.

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

Page 75: Quantitative Finance Collector

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

Let’s look at the same example discussed for ‘Call option’, like you wantto buy an put option contract at a strike price of $100 for a given stock. Ifthe 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 $10or $11 in the option price listing. If the stock value doesn’t get increasedin 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 thisput option, it is always advisable to exercise the contract if the currentstock value is greater than your contract value. So that you can have aprofit, else if you let it expire then you would end up paying thepremium to the writer unnecessarily.

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

Again, Check Varieties of programming codes on option valuation forimplementation.

Tags - option

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

Page 76: Quantitative Finance Collector

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. Ifyou are a novice, then you are in the right spot. Here in this article, youcould get a basic knowledge about the Option, its type & pricing etc.

Basic definition of OptionIn order to understand about Option pricing, you need know about theoption first. Option is nothing but an official contract, between a buyerand a seller, that gives the buyer of the option the right, but not theobligation, to buy or sell a specified asset on or before the option’sexpiration 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 theunderlying asset at the strike price whereas the “Put option” gives theoption to sell the underlying asset at the strike price. If the buyer choosesto exercise this right, the seller is obliged to sell or buy the asset at theagreed price. The buyer may choose not to exercise the right and let itexpire. The underlying asset can be a piece of property, a security (stockor bond), or a derivative instrument, such as a futures contract.

Valuation modelsThe value of an option can be estimated using a variety of quantitativetechniques based on the concept of risk neutral pricing and usingstochastic 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 followingfactors:• The current market price of the underlying security,• the strike price of the option, particularly in relation to the currentmarket price of the underlying asset (in the money vs. out of the money),• the time to expiration together with any restrictions on when exercisemay occur, and• an estimate of the future volatility of the underlying security's priceover the life of the option.

Check Varieties of programming codes on option valuation for

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

Page 77: Quantitative Finance Collector

implementation.

To be continued...Tags - option

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

Page 78: Quantitative Finance Collector

Value at Risk Estimation with Copula

Value at Risk is widely used to measure the downside risk, and Copulais a generalized dependence structure instead of linear correlation tomodel dependence, especially for lower tail dependence, therefore thecombination of VaR with Copula is fantastic in terms of accuratelycapturing the true risk embedded.

I read roughly a working paper Value at Risk – MATLAB Application ofCopulas on US and Indian Markets, where the authors calculate the Valueat Risk (VaR) using the bivariate Gaussian Copula distributionimplemented in MATLAB for the Dow-Jones index and the NationalStock Exchange index. It is good to use Gaussian Copula together withsome rank correlation (like Spearman's rho or Kendall tau) to model thedependence, however, we must be very careful as basically GaussianCopula assumes the joint dependence structure normally distributed andas a result, no matter which marginal distribution you choose, the upperand lower tail dependence approach to zero when the significant levellimits to one and zero, in other words, in a bivariate case, the probabilitythat X2 exceeds its q-quantile, given that X1 exceeds its q-quantile (uppertail 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 underGaussian copula and the other one is under Student t copula, as you caneasily see, although both have the same marginal distribution, Gaussiancopula has much smaller upper and lower tail dependence than Studentt copula, which eventually underestimates the Value at Risk and otherrisk 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

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

Page 79: Quantitative Finance Collector

Looking for Paid Contributors

As the old saying goes: Many heads are better than one. After joined byBo, we are still looking for contributors who are able to write qualityposts to our blog readers. Different from guest post writers who areallowed to promote their sites or products, paid contributors can receivea little sum of cash for their contributions to this blog. Of course we can'tmake you rich but it is a show of our gratitude and bottles of beer we'dlike to invite you.

You will get paid $5 ~ $15 per post directly to your PayPal or bankaccount. 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 itsimplementation you wrote, the problem doesnot need to be sophiscatedat 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 goingto pay (currently between $5 and $15) depending on the quality, and ifyou agree, we'll publish your post under your name ASAP. At yourchoice, we can also leave your simple profile at About us section.

Payment will be sent without minimum amount limit soon after wepublish your articles. Please support us by sending your articles andfiles to abiao @ mathfinance.cn (remove the spaces), or write a guestpost if you prefer that way.

Cheers.Tags - blog

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

Page 80: Quantitative Finance Collector

Advertise with us

Thank you for your interest in advertising on MathFinance.cn. We haveapproximately 13,000 unique visitors that view 40,000 pages per month.Engage our valuable demographic of highly educated quantitativeresearch readers through multiple placement options including premiumdisplay, buttons and links, email and newsletters, co-registration andlead generation, sponsorships, home page takeovers and other creativeadvertising solutions.

InvestingChannel is one of the fastest growing financial mediacompanies and is our exclusive advertising partner. WithInvestingChannel’s seasoned team of professionals, you can optimizeyour campaigns to maximize return on investment with the highest levelof service. Available ad sizes include 728x90, 300x250, 160x600, 88x31and many more.

To learn more about advertising on MathFinance.cn contactInvestingChannel at:

[email protected](p) 646.467.7824(f) 646.290.8452

www.investingchannel.com

Tags - ad

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

Page 81: Quantitative Finance Collector

Monte Carlo Methods for Beginners

Biao has writen several posts on Monte Carlo simulation method foroption pricing and risk analysis, so what is indeed a Monte Carlomethod? 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 arecommonly referred to as are a class of computational algorithms that userepeated random sampling to obtain the desired results. They find theiruse in simulating mathematical and physical systems. Since these relyheavily on repeated computation of pseudo-random or random ornumbers 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 canbe easily solved using these methods. These are also effective in solvingcomplicated boundary conditions and multidimensional integralproblems. Today, these methods are being widely used in oil as well asspace explorations.

Monte Carlo is not a single method of problem solving. Instead, it is aclass of approaches that helps in solving complicated problems. Theseapproaches follow a defined pattern which includes defining the domainof possible inputs, generating input randomly from the domain,performing a deterministic computation and aggregating individualresult to the final results. If you are familiar with the term “what if”scenario, then you should note that Monte Carlo methods are totallyopposite of “what if” scenarios. These simulations or methods considerrandom sampling of the probability distribution functions as inputs toproduce thousands of results.

Monet Carlo method was introduced in 1940’s by physicists working inLos Alamos National Laboratory. After its introduction many newmethods came, but still Monte Carlo method is one of the most popularmethods used for problem solving. The basis of this method is theprobability theory, which also gave birth to a large number of methods.The popularity and use of Monte Carlo methods increased considerablyafter the introduction of computers in 1950’s. USAF and The RandCorporation were among the major organizations which started use of

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

Page 82: Quantitative Finance Collector

these methods in their day to day operations.

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

Tags - monte carlo

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

Page 83: Quantitative Finance Collector

Barrier Option Pricing Using Adjusted TransitionProbabilities

One big issue of pricing barrier option with Binomial tree or other latticemethod is its slow convergence rate, the barrier option value convergesvery slowly as the number of tree or lattice levels increase, oftenrequiring unattainably large computing times for even a modestaccuracy. A typical plot of barrier option binomial tree results against itsanalytic value looks like

source from paper Enhanced Numerical Methods for Options with Barrierswhere the pricing performance is in a sawtooth fashion, with severeperiodic spikes that move away from the correct result, which is anightmare for a researcher because adding more steps doesn'tnecessarily mean to yield a more accurate answer.The reason for this is that the barrier being used by the tree is generallydifferent from the true barrier value, for example, as demonstratedbelow, 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 lyingon barriers, and the adaptive mesh model. Interested readers please referto chapter 20, from page 467 to 472, the 5th version, Options, futures andother derivatives. Or read another paper in detail "Enhanced NumericalMethods for Options with Barriers" by Emanuel Derman, etcdownloadable at http://www.ederman.com/new/docs/gs-numerical_methods.pdf.

The way shared today is distinct from the three approaches, unliketraditional methods to ensure convergence through placing the barrier inclose proximity to, or directly onto, the nodes of the tree lattice, thismethod applies a suitable transition probability adjustment, thereaftercalled Barrier Option Pricing Using Adjusted Transition Probabilities,which exhibits increased convergence to the analytical option price,

source from paper Barrier Option Pricing Using Adjusted TransitionProbabilities

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

Page 84: Quantitative Finance Collector

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

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

Page 85: Quantitative Finance Collector

Stock Trader Report

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

A good stock trader is one who knows how to balance the capitalappreciation of shares with the dividend and bonus that he will get onthose shares. Portfolio plays a very important role in the world of stockmarket and dividend or bonus helps to increase the portfolioconsiderably.

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

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

Stock trader reports will give you a brief idea of what stock trading is allabout and what factors you should keep in mind when you are dealingin stocks. Download the most recent free reports at the free reportsection.

Tags - trading

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

Page 86: Quantitative Finance Collector

Binomial Tree

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

Binomial options pricing model or BOPM, as it is popularly known is ageneralized numerical method that is used for the valuation of options.This method was proposed by Rubinstein, Cox and Ross. This method ispopular in the sense that it can be used for variety of conditions, whilethe other numerical methods have limited use. The main reason why itcan be used in varied situations is that it is based on the underlyinginstrument spread over a period of time rather than a single point oftime. It is slower, but much more accurate than any other method.

This method traces the evolution of options underlying variable spreadover a period of time. This is done by using a binomial tree or binomiallattice. Each node in the binomial tree or lattice represents price of theunderlying at a single point of time. The valuation is performediteratively, i.e., it starts from the final node and goes backwards till itreaches the first node. The value that you will calculate in each node ofthe 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 binomialtree generation, a tree comprised of prices is produced by workingforward the date of valuation to expiration. It is assumed that at eachstep the value of underlying instrument is either moving down or up bya specific factor. The down and up factors are calculated usingunderlying volatility. The next step is to find the value of option at eachfinal node. The option value which is obtained is called the exercise orintrinsic value. The third step is to find the value of options at earliernodes, by moving backwards from the final nodes.

Check Nine Ways to Implement Binomial Tree Option Pricing forbinomial tree implementation.

Tags - binomial

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

Page 87: Quantitative Finance Collector

How much do you know about the Greeks?

Option Greeks measure the sensitivity of option's value to a change inunderlying parameters on which the value of an instrument or portfolioof financial instruments is dependent. Commonly used Greeks includeDelta, Gamma, Vega, Rho, and Theta, which represents partial derivativeto underlying asset price, delta, volatility, interest rate and time tomaturity, respectively. Obviously a good risk control depends largely onhow accurate the way a trader or risk manager compute Greeks, see oldpost Option Greeks analysis for nice Matlab files plotting Greeks forvanilla options.

No matter what the investment, an investor needs to know and fullyunderstand the potential risks of the investment prior to committingcapital to that investment. In the options market, the Greeks define andquantify 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 theproper strategy to fit the opportunity you selected, but also whichspecific options to use to create that specific strategy.

Without a full understanding of the risks of an investment, an investorshould never commit hard earned money. If you do not know yourGreeks, you have no business being in the options market! Watch thiscomplimentary seminar covering the Greeks…Option Greeks seminar.Tags - greeks

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

Page 89: Quantitative Finance Collector

High Dimensional Sobol Sequences

Quasi-Monte Carlo methods are very efficient in solving lowdimensional integration problems, for example, pricing a path-dependent exotic option, among those low discrepancy sequences, Sobolis undoubtedly one of the best and most widely used due to its highconvergence speed, how to generate Sobol Sequences was shared atposts Sobol sequence generator, Primitive polynomials for Sobolsequences, halton and sobol sequences and Sobol and Generalised Fauresequences.

However, empirical research have shown Quasi-Monte Carlo Sobolsequences perform poorly for high dimensional integration problems, itcan never be more efficient than the ordinary Monte Carlo simulation,some researchers suggest to use Sobol sequences with Brownian bridgefor a better result. A recent working paper shared at Articles uses a smalltrick - randomized Sobol sequences to avoid the poor performance highdimensional problem, indeed it is straightforward to add this trick intoyour codes. Below is a comparison graph demonstrating theperformance, 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

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

Page 90: Quantitative Finance Collector

Upcoming Webinars by MathWorks

Attending a free webinar is a good way to learn efficiently. Here is a listof upcoming one-hour live online webinars about MathWorks productswhich I think useful to math finance studying.

Date Title Session Time24Mar2010

Data Acquisition with MATLAB 10:00 a.m. (Centraleuropean Time)

6 Apr2010

Global Optimization with MATLABProducts

9:00 a.m. (U.S.EDT)2:00 p.m. (U.S.EDT)

8 Apr2010 Digital Signal Processing Using MATLAB

9:00 a.m. (U.S.EDT)2:00 p.m. (U.S.EDT)

13 Apr2010

Best Practices for Verification, Validation,and Test in Model-Based Design

9:00 a.m. (U.S. EDT)2:00 p.m. (U.S. EDT)

15 Apr2010

MATLAB for Excel Users inComputational Finance

10:00 a.m. (UnitedKingdom-GMT)

Enjoy.Tags - webinar

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

Page 91: Quantitative Finance Collector

Binomial Tree Option Pricing with Discrete Dividends

How to value a stock option with discrete dividend was brieflyintroduced at http://www.mathfinance.cn/valuation-of-stock-option-with-discrete-dividend/, where the main goal is to compare theperformance of different methods, namely, Escrowed dividend model,Chriss volatility adjustment model, Haug & Haug volatility adjustmentmodel, Bos volatility adjustment model, and Haug, Haug and Lewismethod. I didn't include lattice method for comparison because non-recombining binomial tree is computer intensive, especially when thenumber of dividends is large.

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

(source from Options, futures and other derivatives)

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

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

Page 92: Quantitative Finance Collector

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

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

Page 93: Quantitative Finance Collector

Quant Project Outsourcing

I haven't updated my blog for several days as I have been very busy lastweek with my own research, courses. In the mean time I also did a fewoutsourcing projects, for example, some recent projects including aportfolio Value at Risk calculation excel with macro supportingadvanced input & output form; an American option calculatorconsidering discrete dividends in VBA; data clean, missing dataimputation for a small hedge fund; probability of future stock priceexceeding a barrier in Matlab, etc.

Some selected customers' review:Very satisfied, with the level of work - muzammmilFantastic effort abiao, I really appreciated you turning this job around for me soquickly. If I ever have the need for a quant to help with another custom function,you are my man. - ABCInvestorThanks 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, youmay consider to give my group and me chance. Although we can'tguarantee we are capable of meeting all your requirements, we can trybest to insure you a satisfied result as long as we promise to undertakethe 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

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

Page 94: Quantitative Finance Collector

The Big Short: Inside the Doomsday Machine

Most of us have read the book Liar's Poker: Rising Through theWreckage on Wall Street, one of the books that define Wall Street duringthe 1980s and are highly recommened by many people in academia andindustry, where the author Michael Lewis described his experiences as abond salesman in a humon sense. I just got to know today from a friendof mine recommending a new book The Big Short: Inside the DoomsdayMachine , as described:QuotationA brilliant account—character-rich and darkly humorous—of how theU.S. economy was driven over the cliff. Truth really is stranger thanfiction. Who better than the author of the signature bestseller Liar’sPoker to explain how the event we were told was impossible—the freefall of the American economy—finally occurred; how the things that wewanted, like ridiculously easy money and greatly expanded homeownership, were vehicles for that crash; and how shareholder demandfor profit forced investment executives to eat the forbidden fruit of toxicderivatives.

I don't know, considering the high quality of Liar's Pocker, it may beworth reading. I pre-ordered just now at Amazon, if you also want a bedreading book, order one at only $15.09 at Amazon to be released onMarch 15, 2010. The Big Short: Inside the Doomsday Machine.

Tags - amazon , book

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

Page 95: Quantitative Finance Collector

Calibrating Stochastic Volatility Models with HeuristicTechniques

Stochastic volatility models, specifically, Heston model, SABR model, areintroduced before and become the widely used among academia andindustry. However, the calibration process is difficult because generallythe pricing requires numerical integration, and calibration requires tofind five and eight parameters instead of only one for Black Scholesmodel.

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

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

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

Page 96: Quantitative Finance Collector

How to Spot Trading Opportunities

How To Use Bar Patterns to Spot Trade Setups30 Instructional Charts With Simple Explanations

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

But without the right education, you could be missing high-probabilitytrade setups that should be staring you right in the face.

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

Download Your Free Bar Patterns Report Now.Tags - trading

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

Page 97: Quantitative Finance Collector

VaR Historical Simulation

Following Value at Risk xls and var backtesting, a third post about usinghistorical simulation for Value at Risk calculation. We know oneshortcoming of historical simulation is: the result highly depends on thechoice of sample data length, VaR result does not vary often or changessuddenly. Despite this weakness, HS is still popular due to its obviousadvantage: easy to implement, and no distribution assumption required,which is especially appealing if the estimate of distribution assumptionis difficult. Several ways have been proposed to improve HS'sperformance, here are two selected methods with good results Ipersonally use.

1, The Best of Both Worlds: A Hybrid Approach to Calculating Value atRisk by Jacob Boudoukh1, Matthew Richardson and Robert F. Whitelaw.By hybrid it means this approach is a combination of RiskMetrics'sparametric method and Historical Simulation. The basic idea is: since wecan allocate larger weight to recent data and smaller weight to remotedata for exponential weighted moving average (EWMA) volatilitycalculation, hence improves the backtesting performance of parametricmethod, why can't we then apply a similar principle to historicalsimulation? make sense? so it estimates the VaR of a portfolio byapplying exponentially declining weights to past returns and thenfinding the appropriate percentile of this time weighted empiricaldistribution. The following results are from the paper The Best of BothWorlds: A Hybrid Approach to Calculating Value at Risk, page 11. It doesimprove compared with the vanilla historical simulation and EWMAparametric method, nice.

2, INCORPORATING VOLATILITY UPDATING INTO THEHISTORICAL SIMULATION METHOD FOR VALUE AT RISK by JohnHull and Alan White. The idea is to "adjust" return based on the ratio ofcurrent volatility to the past volatility, and use historical simulation onthe adjusted returns. Their argument is supposing today's volatility is20%, while volatility was say, 30%, then past returns obviouslyexaggerate the current market situation if used directly. They evencompare their performance with the first one above and the results are:

source from INCORPORATING VOLATILITY UPDATING INTO THE

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

Page 98: Quantitative Finance Collector

HISTORICAL SIMULATION METHOD FOR VALUE AT RISK page 17.

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

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

Page 99: Quantitative Finance Collector

Friday reading list of this week

Friday again, just a final kind remind, since Change of Friday ReadingList Setting, I have been updating Friday reading list on page articles, forexample, 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 andSkewness , 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

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

Page 100: Quantitative Finance Collector

Inverse Graphing Calculator

An interesting application of Inverse Graphing Calculator, where youenter any word from A to Z into your calculator and then get a graph ofthe 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.phpTags - graph

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

Page 101: Quantitative Finance Collector

Sudoku Spreadsheet Example of Matlab Excel Link

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

I happened to find Cleve Moler solved Sudoku using recursivebacktracking method and the speed is fast, the minor error is it doesn'treport an error when the initial 9*9 matrix you give violates Sudokurules (you can test it later, the code starts to run and returns a result evenyou give repetitive numbers along a same row or column). Sincebuilding a GUI in matlab isn't easy, I choose to build a Sudokuspreadsheet using Matlab Excel link for an example.

Once you install Excel Link module and turn it on, you will notice theshort-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 athttp://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 be9*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

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

Page 102: Quantitative Finance Collector

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

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

Page 103: Quantitative Finance Collector

Change of Friday Reading List Setting

I made a small change to the Friday reading list section by adding a newcategory Articles, which can be easily seen above at the menu bar. Sofrom now on all recommended paper, together with shared interestingarticles, will not be shown on the main page any more but rather underseparated Articles category . For one thing, this movement facilitates mysharing process, I don't have to add paper/articles to my reading listonly on Friday; for another, since not all people like reading technicalpaper, they can now choose not to see them at all, which is especially abenefit to blog feed readers as the reading list will "disappear" fromupdate.

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

Have a nice weekend.Tags - friday

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

Page 104: Quantitative Finance Collector

Free market reports and articles

For over ten decades, the mainstream financial world has embraced theview that external news events drive trend changes in the markets. Inless than ten minutes, EWI's senior tutorial instructor Wayne Gormanshatters 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 UseThe Wave Principle," Wayne first assesses the pitfalls of relying onmacroeconomic models to forecast; namely: "An investor is lured into themarket at just the worst time, when it's time to sell, and forced out just atthe best time to buy."

As for real world examples of this happening, Wayne spans threehundred years of financial history to reveal how the most pivotaleconomic, political, and environmental events failed to alter the course oftheir respective markets. Here, the free video includes groundbreakingcharts on these (and more) well known episodes:

The S&P 500 and Enron from 2000-2002: The stock market ROSE andcontinued to proceed upward AFTER the largest US corporate scandaland 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 themost part ROSE, just the opposite of what most market analysts andinvestors expect.The Dow and profound political events over the last 80 years: In the1930s and 1940s, a series of negative incidents -- i.e. Hitler rising topower, World War II, and the Holocaust -- preceded a powerful uptrendin stocks all the way into the 1960s.Stock market charts of the five countries most affected by the 2004 IndianOcean 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 atotal of 40 charts that capture failed fundamental analysis of the world'sleading financial markets. Wayne recalls this expression from a famous,Nobel Prize winning economist:

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

Page 105: Quantitative Finance Collector

"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 thepitfalls shown on the previous charts. That's why the Wave Principle isso important. It offers a unique perspective and a market discipline ofrules and guidelines that help investors avoid buying at tops andliquidating at bottoms. It helps to explain and understand trends beforethey happen."

The flaw in Economic 101, cause-and-effect theory is one of the easiestthings to prove. But it's also one of the hardest things for many investorsto accept. Now is the time to do so. Watch the free "Why Use The WavePrinciple," video in its entirety today at absolutely no cost. Simply signon to join the rapidly expanding Club EWI and take advantage of theamazing educational benefits membership has to offer.Tags - report

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

Page 106: Quantitative Finance Collector

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 isstraightforward in principle to do that but since we have to calculatedaily VaR for multiple periods in order to do backtesting, I simply didn'tadd that in an excel for speed reason.

The Backtesting framework developed by the Basel committee is themain methodology to judge the performance of VaR model, it typicallyconsists of a periodic comparison of the portfolio’s or asset’s daily VaRvalues with the subsequent daily profit and loss (P&L). Obviously, theideal model should generate the times of VaR exceeding P&L equal to(1-alpha) multiplied by time periods for backtesting. For a single equitycase it is obvious what we need to do is comparing daily VaR resultswith daily return; but for a portfolio we have to be careful with thetrading positions.

Basel committee (1996) introduces a three-zone approach, where thegreen zone means the possibility of erroneously accepting an inaccuratemodel is low; yellow zone is risk manager should be careful to check themodel before take action; red zone means the probability of erroneouslyrejecting an accurate model is remote. For example, the backtesting threezones boundaries for a sample of 250 observations, source from Baselcommittee, 1996 look like

Backtesting results can therefore be judged by counting the number ofexceptions and seeing intuitively which colour zone it falls into.

Alternatively you can rely on some statistical testing, for instance, theexception 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

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

Page 107: Quantitative Finance Collector

Financial Analytics Risk Management Tools

Found a site providing financial analytics & risk management tools,FinCalc, as introduced by its webmaster: "FinCalc provides you with thetools to build advanced financial functions under Excel. ...FinCalccovers bonds, money market, futures, options and interest ratederivatives."

Key points are:Calendar with business holidays for the major financial centers.Bond analytics: yield to maturity, duration, accrued interest; valuationfunctions and sensitivity measures; bond cash flows; forward price andrepo rate.Derivatives: valuation functions and sensitivity measures european andamerican options; exotic options.Discount curve construction based on money market rates,short termfutures 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 atrisk, portfolio optimization on an absolute basis or relative to abenchmark.User friendliness: meaningful function and parameter names; user'smanual, numerous examples and applications.Excel add-in and examples to download.

For example, after downloading FinCalc.xla, opening it and other filessaved 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

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

Page 108: Quantitative Finance Collector

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, calledcash-or-nothing option, or shares, called asset-or-nothing option.Intuitively, cash-or-nothing option holders receive cash if the optionfinishes in the money, asset-or-nothing option holders receive shares ofasset if in the money, thereafter binary options are often named as digitaloptions.

The pricing of binary options is straightforward under GBM framework,the widely used Black Scholes formula can be easily adopted for binaryoption valuation. Once we understand the principle and know how toprice it, the next step probably is to trade binary options. There areseveral online option trading platform for an individual investor tochoose, the one I'd like to review is EZTrader, who has revolutionizedthe way binary options are traded on the internet today, by supplyingits customers with a simple, exciting, dynamic and highly profitabletrading platform, very different from traditional option trading. Due tothe simplicity and speed of our binary options trading system and thelow minimum investment amount, it is able to reach investors withdifferent profiles all over the world. Ranging from sophisticatedinvestors that are looking for ways to hedge their positions in thetraditional market, to amateur day traders looking for some "action"without risking large amounts of money, EZTrader developed a systemsuitable to most of everyone's goals.

EZtrader have taken the fear and uncertainty out of Forex trading tofocus on an existing new kind of trade. At EZtrader you can trade BinaryOptions. With binary options you simply choose whether the stock pricewill go up or down by the expiration time and place you call or putaccordingly. With EZtrader your winning return is fixed, you don’t haveto leverage millions of dollars with every trade or setup complicatedstop loss strategy. With EZtrader binary options everything you need isright in front of you.

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

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

Page 109: Quantitative Finance Collector

- 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 providedwith a complete set of tools to help them optimize their trading. Toolsinclude live financial news, references to financial sites and a widevariety of tradable options, and more. Check EZtrader home pageregularly for new promotions that will help you to get the most out ofyour trades, for example, one promotion is: If you deposit a total of$550.00 today, Monday, February 22nd, 2010, you will receive a bonusof $250.00 (%45)Registration is totally free and there are no commissionsto pay ever.

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

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

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

Page 110: Quantitative Finance Collector

Value at Risk xls

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

Before checking the excel, few sentences explaining Value at Riskcalculation are necessary: Value at Risk (VaR) is the maximum loss notexceeded with a given confidence level 0

Given confidence level and horizon day, the crucial point for quantileestimation is to find a suitable distribution of underlying risk factors,once distribution is known, VaR and ES can be easily calculated by thedefinition. Mina and Xiao (2001) explains in detail three popularmethods to compute VaR: parametric approach (the simplest one isdelta-normal), Monte Carlo simulation (MC) and Historical simulation(HS). I am not going to talk in detail how to calculate them as interestedreader can refer to the paper or the book by John Hull, a shortcomparison 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 doesnot 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 ortoo exotic to implement.

Attached is the ValueatRisk.xls file, where for simplicity, I treatvolatility as normal standard deviation, Value at Risk is computed bydelta-normal, monte carlo simulation and historical simultion for anysingle equity, you have to make sure internet is accessible fordownloading data from Yahoo. Please keep in mind this file is createdfor illustration only, use at your own risk.

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

Page 111: Quantitative Finance Collector

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

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

Please let me know any error, cheers.Excel:Click to downloadMacro Code:Click to downloadTags - var

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

Page 112: Quantitative Finance Collector

Friday reading list 19/02/2010

1, Market Timing & Trading Strategies Using Asset Rotation, "In thispaper we present empirical results on the statistical and economicviability of a market timing trading strategy that is based on rotationbetween two risky assets. We use data on Exchange Traded Funds(ETFs) and models for both the returns and the volatility of theunderlying assets." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=15379142, Hedging the Black Swan: Conditional Heteroskedasticity and TailDependence in S&P500 and Vix, "In this paper, we show how theconditional approach of Heffernan and Tawn (2004) can be implementedto model extremal dependence between financial time series. A hedgingexample based on VIX futures is used to demonstrate its flexibility andsuperiority against the conventional OLS regression approach."http://papers.ssrn.com/sol3/papers.cfm?abstract_id=15491643, Stability of Mean-Variance Portfolio Weights, "The mean-varianceportfolio weights are known to be strongly affected by the estimationerrors of the parameters of asset distribution. Our paper studies thisphenomenon from a new angle. We distil the stability measurements ofseparate coordinates of portfolio weights estimator into a single number.We derive analytical formulas that relate this measure with the meanand the covariance matrix of asset returns." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=15530734, Unusual News Events and the Cross-Section of Stock Returns, "Weshow that stocks that experience a sudden increase in idiosyncraticvolatility earn abnormally high contemporaneous returns butsignificantly underperform otherwise similar stocks in the future."http://papers.ssrn.com/sol3/papers.cfm?abstract_id=13621215, Exact Simulation of Point Processes with Stochastic Intensities, "Thispaper develops a method for the exact simulation of point processes withstochastic intensities. The method is based on a change of the filtrationthat describes the information flow in the point process model."http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1551647Tags - friday

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

Page 113: Quantitative Finance Collector

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 somestock market pundit utter these words? Have you ever wondered if thestatement were true? Read this item from the latest issue of The ElliottWave Financial Forecast, and you'll wonder no more:

Myth -- Cash on the sidelines is bullish for stocks. This refrain ranglike 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% inNovember), 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 showsnet cash available to investors plotted beneath the DJIA. In December2007, available net cash expanded to a new high, besting all extremessince at least 1992, a 15-year time span. Despite the presence of thismountain of cash, the DJIA lost more than half its entire value over thenext 15 months. Indeed, as the chart shows, cash remained high right asthe stock market entered the most intense part of the crash in 2008.Available cash does correlate with the market’s moves, but the market isin 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 thesestatements as a market myth. You can discover how we exposed theseideas as myths, and in turn make more informed decisions about your

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

Page 114: Quantitative Finance Collector

investing.

We've gathered the writings that expose these 10 statements as marketmyths in our 33-page eBook, called Market Myths Exposed. They comefrom two of our premier publications, The Elliott Wave Theorist and TheElliott Wave Financial Forecast, as well as two of our books, Prechter'sPerspective and The Wave Principle of Human Social Behavior. The33-page eBook takes the 10 most dangerous investment myths head onand exposes the truth about each in a way every investor canunderstand. You will uncover important myths about diversifying yourportfolio, the safety of your bank deposits, earnings reports, investmentbubbles, inflation and deflation, small stocks, speculation, and more!Protect your financial future and change the way you view yourinvestments forever! Learn more, and get your free eBook here.Tags - elliott , stock

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

Page 115: Quantitative Finance Collector

High Probability ETF Trading Strategies on Stock

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

I tested 5 strategies out of 7 for a randomly selected Chinese stockdownloaded from Yahoo, since shorting selling is hard in Chinesemarket I exercise long strategy only (which might influence theirperformance, I admit). Starting with capital 12500, transaction cost 0.5%and running for one year data, the results are (pls bear with me, thegraphs 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 only0.01 sharpe ratio, compared with the best one the %b strategy 3.34 andbuy & hold strategy 0.74. R3 strategy generates 2.67 sharpe ratio highenough for trading but we have to be very careful as the slipage cost dueto whipsaw position may kill our profit.

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

Page 116: Quantitative Finance Collector

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

Tags - strategy , trading

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

Page 117: Quantitative Finance Collector

Friday reading list 12/02/2010

Tomorrow is the last day of this lunar year, wish all of you and me happyChinese lunar new year.抬板凳看春晚

1, Modeling the Cross Section of Stock Returns: A Model PoolingApproach, "This paper illustrates the advantages of a model poolingapproach in contrast to model selection. Model pools of several assetpricing models including the CAPM, the Fama-French (1993) three-factormodel, and the Carhart (1997) four-factor model are considered for thepurpose of forming expectations (i.e., predictions) of the one-step-aheadreturns 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 Jumpsand Regime-Switching, "In this paper, I address systematically how toenhance the most existing option models with piecewise-constantparameters, and how to derive the corresponding closed-formcharacteristic function under the risk-neutral measure. As long as thecharacteristic function with piecewise-constant parameters is analyticalknown, the pricing formula for a European call is then given by inversetransform of the derived characteristic function."http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1547036;3, Comparison of Numerical and Analytical Approximations of theEarly Exercise Boundary of the American Put Option, "In this paper wepresent qualitative and quantitative comparison of various analyticaland numerical approximation methods for calculating a position of theearly exercise boundary of the American put option paying zerodividends." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1547783;4, Multivariate GARCH Models with Correlation Clustering, "Thispaper 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 Tseand Tsui (2002) by determining a natural grouping of the correlationsamong 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 inderivative pricing for reconstructing the pricing operator at a given day,

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

Page 118: Quantitative Finance Collector

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

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

Page 119: Quantitative Finance Collector

14 Critical Lessons Every Trader Should Know

A post from our blog sponsor, Elliott Wave International, the world'slargest market forecasting firm founded in 1979 by Robert R. Prechter Jr.Its staff of full-time analysts provides 24-hour-a-day market analysis toinstitutional and private investors around the world.

From today, Elliott Wave International have brought back one of theirmost sought after free resources for one week only. The Best of Trader'sClassroom eBook serves up the very best lessons from their popular --and expensive -- Trader's Classroom Collection in one valuable 45-pagereport. If you aren't one of the thousands who downloaded this valuableresource 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, youneed to get your free report by February 16, the price will be back tonormal $59 after that day for all blog readers. Cheers.PS: forgot to mention, in order to download the free report, you have tobe a member first, the registration requires only username and emailaddress, which takes half a minute.

Tags - trading , elliott

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

Page 120: Quantitative Finance Collector

Research Topic Wanted

I have been struggling to find a suitable research topic for my PhD infinance these days, initially I chose to research on convertible bondunderpricing considering multiple features other paper might fail to doso, but later on I realized the potential margin contribution is small withmore knowledge on this field, indeed a few latest paper dealing with thisissue already.

Do you happen to have an interesting topic that you or your colleagueswant to work on while without enough time and resources? thenprobably 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, portfolioconstruction 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 youfrom 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 anycomment or hint or suggestion, especially from industry side.

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

Page 121: Quantitative Finance Collector

Quadrature method for convertible bond pricing

A follow up post of my previous entry Using Quadrature method foroption valuation, where the accuracy and computational speed aredemonstrated briefly with a simple European option based on the paper"universal option valuation using quadrature methods". Today I play theQuadrature method for a vanilla convertible bond, still, the results arepromising, for example, below is price performance comparision underQuadrature and PDE (specifically, finite element method) numericalsolutions, 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 ofconvergency rate, it is several times faster than finite element, in my case,Quadrature costs me less than ten seconds but finite elements costs mearound one minute.

PS: the y-axis should be relative error.

Tags - quadrature , convertible bond

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

Page 122: Quantitative Finance Collector

Dolphin in Taiji

This post has nothing to do with quantitative finance, so please skip it ifyou have no interest at all.

A friend of mine, who is an active animal protectionist, asked me if it ispossible to embed a video on my blog. I didn't promise at the beginningworrying the video has nothing to do with my topic, but decide to do soafter watching it, in addition, today is Sunday, take a rest then.

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

The video tells us how cruel the fishermen in Taiji are, how the activistshope 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 Chinesegovernment 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 Chinesescripts.

Tags - dolphin

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

Page 123: Quantitative Finance Collector

Friday reading list 05/02/2010

Several good working paper have been found this week, hope you willalso 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 propagationlaw 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 varianceswaps are constructed taking account of both autocorrelation and crossasset dependencies. Market prices of variance swaps are extracted fromoption surface calibrations. The methods developed permit simulation ofcash flows to arbitrary portfolios of variance swaps. The optimal designmaximizes 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 , "TheFourier transform methods provide the valuable and indispensable toolsfor option pricing under L´evy processes since the analyticrepresentation of the haracteristic function of the underlying asset returnis more readily available than that of the density function itself. Whenused together with the FFT algorithms, real time pricing of a wide rangeof option models under L'evy processes can be delivered using theFourier transform approach with highaccuracy, efficiency andreliability." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1534544;4, Interest Rates and The Credit Crunch: New Formulas and MarketModels , "We start by describing the major changes that occurred in thequotes of market rates after the 2007 subprime mortgage crisis. Wecomment on their lost analogies and consistencies, and hint on apossible, simple way to formally reconcile them. We then show how toprice interest rate swaps under the new market practice of usingdifferent curves for generating future LIBOR rates and for discountingcash flows. Straightforward modifications of the market formulas forcaps 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 howhigh-frequency trading decisions (especially the choice of market versuslimit orders) of individual investors are influenced by past price changes.

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

Page 124: Quantitative Finance Collector

Specifically, we address the question whether trading decisions to openor close a position are different in the case in which investors alreadyhold 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 precisionwith which financial models are handled, in particular optimisationmodels. We argue that precision is only required to a level that isjustified by the overall accuracy of the model. Hence, the requiredprecision should be specifically analysed, so to better appreciate theusefulness and limitations of a model." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1547173Tags - friday

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

Page 125: Quantitative Finance Collector

Valuation of stock option with discrete dividend

When asked how to value a stock option without dividend or withcontinuous dividend, many people would refer to Black Scholes formula,but how to price an option with discrete dividend then? certainly BlackScholes model can't be used directly since one of its assumptions iscontinuous payout. Paper Back to Basics: a new approach to the discretedividend problem by Haug, Haug and Lewis summarizes the followingways:1, Escrowed dividend model, which is the simplist and the least accurateway as a result. The basic idea of Escrowed dividend model is to adjustthe current stock price by deducting the present value of futuredividends, and plug in the replaced stock price to Black Scholes formula;2, Chriss volatility adjustment model, besides replacing current stockprice, this model adjusts volatility as well because the Escroweddividend model alone decreases the absolute price standard deviation,hence underestimates an option's value. However, Chriss model yieldstoo high volatility if the dividend is paid out early in the option’slifetime, which generally overprices call options;3, Haug & Haug volatility adjustment model; which is moresophisticated than Chriss model and takes into account the timing of thedividend, unfortunately, the authors show this method performsparticularly poorly for multiple dividends stock option;4, Bos volatility adjustment model, a even more sophiscated model thanHaug & Haug, but still, it performs poorly for large dividends or longterm options;5, Lattice method, for example, non-recombining binomial treeintroduced in the bible book Options, Futures, and Other Derivativeswith Derivagem CD (7th Edition), we all know it is time-consuming;6, Haug, Haug and Lewis method introduced in the above-mentionedpaper, the basic idea is to calculate first the ex-dividend option price byBlack Scholes model, then discount back the ex-dividend value underequivalent martingale measure. The authors demonstrate the highaccuracy of their model with several examples afterwards.

Below is sample Matlab codes I wrote for comparision, a single dividendis 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,

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

Page 126: Quantitative Finance Collector

%read paper by Haug for detail;%dt: dividend timeBSprice = 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.500111.1039 11.0781 11.1062, respectively.

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

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

Page 127: Quantitative Finance Collector

On the Brink: Inside the Race to Stop the Collapse of theGlobal Financial System

Henry Merritt Paulson, Seventy-five men served as Treasury Secretary ofthe United States, blurted out when he learned U.K.'s Financial ServiceAuthority was reluctant to approve a prebankruptcy deal for BarclaysPLC to acquire Lehman, "The British screwed us." This was revealed inPaulson's new book "On the Brink: Inside the Race to Stop the Collapse of theGlobal Financial System", where the author tell us the key decisions thathad 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 toStop the Collapse of the Global Financial System:QuotationThe pace of events during the financial crisis of 2008 was trulybreathtaking. In this book, I have done my best to describe my actionsand the thinking behind them during that time, and to convey thebreakneck 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 crisissince the Great Depression. There can't be many other examples ofeconomic leaders managing a crisis who had as much trust in oneanother as we did. Our partnership proved to be an enormous assetduring an incredibly difficult period. But at the same time, this is mystory, and as hard as I have tried to reflect the contributions made byeveryone involved, it is primarily about my work and that of mytalented and dedicated team at Treasury.

--Henry M. Paulson

Tags - book

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

Page 128: Quantitative Finance Collector

Most recent quant job offers

Most recent job offers from Quant jobs board:

Scientific programmersCBCS in Cambridge MASenior Quantitative Analyst-Modeling at RiskMetrics in LondonTrader Exotic Options at ING in BrusselsEquity Quantitative Research Analyst at JPMorgan in NewYorkPHD Internships at Bank of England in LondonAssociate Program at Partners Group AG in LondonQuantitative Research Analysts at State Street in LondonTags - quant , job

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

Page 129: Quantitative Finance Collector

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 includeequity 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 isunderstandable considering it is a newly launched website, take a look ifinterested, http://www.volopta.com/index.html.

Have a nice weekend.Tags - derivative

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

Page 130: Quantitative Finance Collector

Friday reading list 29/01/2010

1, On the Heston Model with Stochastic Interest Rates, "We discuss theHeston [Heston-1993] model with stochastic interest rates driven byHull-White [Hull,White-1996] (HW) or Cox-Ingersoll-Ross [Cox, etal.-1985] (CIR) processes. A so-called volatility compensator is definedwhich guarantees that the Heston hybrid model with a non-zerocorrelation between the equity and interest rate processes is properlydefined. Two different approximations of the hybrid models arepresented in order to obtain the characteristic functions. Theseapproximations admit pricing basic derivative products with Fouriertechniques [Carr,Madan-1999; Fang,Oosterlee-2008], and can thereforebe used for fast calibration of the hybrid model. The effect of theapproximations on the instantaneous correlations and the influence ofthe correlation between stock and interest rate on the implied volatilitiesare also discussed." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1382902

2, Dynamic Copula Modelling for Value at Risk, "By using copulas, wecan separate the marginal distributions from the dependence structureand estimate portfolio Value-at-Risk, assuming for the risk factors amultivariate distribution that can be different from the conditionalnormal one. Moreover, we consider marginal functions able to modelhigher moments than the second, as in the normal. This enables us tobetter understand why VaR estimates are too aggressive or tooconservative. We apply this methodology to estimate the 95%, 99% VaRby using Monte-Carlo simulation, for portfolios made of the SP500 stockindex, the Dax Index and the Nikkei225 Index. We use the initial part ofthe sample to estimate the models, and the the remaining part tocompare the out-of-sample performances of the different approaches,using various back-testing techniques." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1542608Tags - friday

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

Page 131: Quantitative Finance Collector

The Quants: How a New Breed of Math Whizzes ConqueredWall 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 NearlyDestroyed It, what a looong name. The book is written by a Wall StreetJournal 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. InThe Quants he does an admirable job of debunking the myths of blackbox 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 Aeronchairs, while the rest of us read in horror about their greed and theirimpact on the wider economy. A gripping tale right until the lastpage...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 ScottPatterson explains a group called "The Quants" developed complexsystems to trade securities such as mortgage derivatives, which were atthe 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 Streetand Nearly Destroyed It

Tags - quant

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

Page 132: Quantitative Finance Collector

Elliott Wave Analysis

Last weekend I reviewed a service called elliott wave analysis atPopular Culture and the Stock Market, some of my blog readers joinedthe free EWI club and downloaded the free report. As a result, elliottwave international sent me a book elliott wave principle, key to marketbehavior and a pen with club logo on, thank you.

So this weekend I'm gonna talk few more words about Elliott WaveAnalysis, what is elliott wave principle then? as described on wikipedia,"it is a detailed description of how financial markets behave. Thedescription reveals that mass psychology swings from pessimism tooptimism and back in a natural sequence, creating specific wave patternsin price movements." Therefore it is a type of investment disciplinecombining technical analysis with behavioral finance that attempts toexplain and predict the market trend (of stock, forex, etc.). Unlike thosequantitative techniques we often hear or apply, Elliott Wave Analysisassumes it is unnecessary to be based on past price charts to decidewhere a market is in its wave patten, which is instead decided byinvestors' psychology, therefore Elliott Wave Analysis has got criticism,for example, quantitative researchers tend to blame it is just an art wherethe subjective judgement is more crucial than the objective, replicableverdict 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" andattend the free courses then.

Or watch this classic video from Elliott Wave International's ChiefCurrency Strategist, Jim Martens, to see how useful the basics of Elliottwave analysiscan be. Jim explains how the same basic pattern that R.N.Elliott discovered back in the 1930s is often all you need to makeinformed 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.

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

Page 133: Quantitative Finance Collector

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

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

Page 134: Quantitative Finance Collector

Friday reading list 22/01/2010

1, Time-Varying Momentum Profitability, "In this paper, we present acomprehensive examination of the time-series predictability ofmomentum profits. We uncover a list of intriguing features of the time-variation in momentum profits: (1) market volatility has significantpower to forecast momentum payoffs, which is even more robust thanthat of market state or business cycle variables; (2) the time-seriespredictability is centered on loser stocks; and (3) the time-series patternsappear 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-CallParity: Evidence from the Currency Options Market, "this studydeveloped a transaction cost-adjusted put-call parity (TC-Adj-PCP)econometric model to examine the efficiency of options markets. Thefundamental analysis of the proposed model concludes that transactioncosts represent an omitted variable for the PCP model, where theuniqueness of this variable is demonstrated under PCP in the context ofoptions market efficiency. The novelty of the TC-Adj-PCP modelresolves controversial transaction costs issues for traders andresearchers." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1537834

3, Short-Selling Bans Around the World: Evidence from the 2007-09Crisis, "find that bans (i) were detrimental for liquidity, especially forstocks with small market capitalization and high volatility; (ii) sloweddown price discovery, especially in bear market phases, and (iii) failed tosupport stock prices. " http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1533163

4, On the Volatility and Comovement of U.S. Financial Marketsaround Macroeconomic News AnnouncementsTags - friday

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

Page 135: Quantitative Finance Collector

Matlab File Exchange

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

Specifically, financial services, Mathematical modeling and Statistics andProbability are three categories I keep eyes on.

Besides Matlab central, Matlab M-files database built by university ofStuttgart is another site I often visit, it has a smaller size but growquickly, focusing on using Matlab for numerical calculation.

Stay tuned.Tags - matlab

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

Page 136: Quantitative Finance Collector

Meta Financial Functions Library

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

At the moment Meta Financial Functions Library covers a wide range ofvanilla and exotic options, which can be obviously seen from the name offunctions, 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 athttp://www.metasystems.no/, which is free and the author makes thesource code clean and publicly available, learning from others is alwaysenjoying.

Tags - library

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

Page 137: Quantitative Finance Collector

Popular Culture and the Stock Market

Long time I haven't reviewed service provided by other site, thisweekend's review is about a club service by EWI, as stated by its authors:"Elliott Wave International (EWI) is the world’s largest marketforecasting firm. EWI’s 20-plus analysts provide around-the-clockforecasts of every major market in the world via the internet andproprietary web systems like Reuters and Bloomberg. EWI’s educationalservices include conferences, workshops, webinars, video tapes, specialreports, 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 itsclub, take a look if interested. Wall Street legend and best-selling authorRobert Prechter says "You can almost hear the Dow going up and downover the airwaves." Watch this 3-minute clip from his documentaryHistory's Hidden Engine to see how social mood governs movements inthe stock market and trends in popular culture. Then access his 50-pagereport "Popular Culture and the Stock Market" free.

Access Robert Prechter's 50-page report "Popular Culture and theStock Market" FREE!

Tags - stock , elliott

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

Page 138: Quantitative Finance Collector

Fridays reading list 15/01/2010

Two paper I find pretty interesting this week, both are published inMathematical 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 withcontinuous dividend yield. We solve the integral equation and derive anew analytical formula in a series form for the critical stock price.American options can be priced and hedged analytically with the help ofour critical-stock-price formula. Numerical tests show that our formulagives very accurate prices. With the error well controlled, our formula isnow ready for traders to use in pricing and hedging the S&P 100 indexoptions and for the Chicago Board Options Exchange to use incomputing the VXO volatility index."

2, ACHIEVING HIGHER ORDER CONVERGENCE FOR THE PRICESOF EUROPEAN OPTIONS IN BINOMIAL TREES, by MARK S. JOSHI,"A new family of binomial trees as approximations to the Black–Scholesmodel is introduced. For this class of trees, the existence of completeasymptotic expansions for the prices of vanilla European options isdemonstrated and the first three terms are explicitly computed.Asspecial cases, a treewith third-order convergence is constructed and theconjecture of Leisen and Reimer that their tree has second-orderconvergence is proven." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=976561Tags - friday

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

Page 139: Quantitative Finance Collector

A Finite Element Differential Equations Analysis Library

Attended a training of NAG Toolbox for MATLAB today (NAG is shortfor Numerical Algorithms Group), nice presentation and persuasiveperformance against Matlab toolbox. I will soon get a licence and start toexperience 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 toenable rapid development of modern finite element codes, using amongother aspects adaptive meshes and a wide array of tools classes oftenused in finite element program. As stated on its webpage: "deal.II is aC++ program library targeted at the computational solution of partialdifferential equations using adaptive finite elements. It uses state-of-the-art programming techniques to offer you a modern interface to thecomplex data structures and algorithms required." It should be veryuseful for those people playing often with PDE numerical solution.

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

Have a nice weekend.

Tags - nag , finite-element

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

Page 140: Quantitative Finance Collector

Friday reading list 01/08/2010

1, Yes, the Choice of Performance Measure Does Matter for Ranking ofUS Mutual Funds, "Recent literature in performance evaluation hasfocused on preferences and characteristics of returns’ distribution that gobeyond mean and variance world. However, Eling (2008) compared theSharpe ratio with some of these performance measures, and foundvirtually identical rank ordering using mutual fund data. This papercompares 13 performance measures with the traditional Sharpe Ratiousing a sample of US Fixed-Income, Equity and Asset Allocation MutualFunds. Results show that performance measures based on absolutereward-risk ratios have similar rankings, when the numerator (meanexcess return) is the same. However, when we move to other types ofperformances 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 toFactor-Based Portfolio Construction and Beyond, "The Fama and French(1992 and 1993 etc.) factor ranking approach is very popular amongquantitative fund managers. However, this approach suffers fromhidden 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 andelegantly resolves these issues. This model explicitly seeks forward-looking factor views and smoothly blends them to deliver robustallocation to securities. Our numerical experiments show this is anintuitive 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 andUnified 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, somestraightforward linear algebra gives you the diversified and efficientBayesian allocation that allows greater performance accountability. Allyou need is just a factor risk model. How does this sound? This paperderives a transparent version of the ABL model (Cheung, 2009B) with anexplicit allocation expression, including components for all the neededfunctionalities. In addition to further insights, it allows more tangible

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

Page 141: Quantitative Finance Collector

implementation of strategy combination, factor mimicking, hedging, andstock-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 ofhomogeneous volatility bridge estimators for log-price stochasticprocesses. The main tool of our theory is the parsimonious encoding ofthe information contained in the open, high and low prices of incompletebridge, corresponding to given log-price stochastic process, and in itsclose value, for a given time interval. The efficiency of the new proposedestimators is favorably compared with that of the Garman-Klass andParkinson estimators." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1523225

5, A PDE Pricing Framework for Cross-Currency Interest RateDerivatives, "We propose a general framework for efficient pricing via aPartial Differential Equation (PDE) approach of cross-currency interestrate derivatives under the Hull-White model. In particular, we focus onpricing long-dated foreign exchange (FX) interest rate hybrids, namelyPower Reverse Dual Currency (PRDC) swaps with Bermudan cancelablefeatures." http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1502302

Have a nice weekend.Tags - friday

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

Page 142: Quantitative Finance Collector

Google Quant Staff

Sharing a Google Quant Staff page I created initially for myself, themotivation was to make the job more convenient since I had to search inGoogle too many times per day, what's worse is sometimes I prefervideo results, while sometimes what I need is just PDF documents orMatlab files. Adjusting frequently with Google advanced search makesme feel silk.

Google Quant Staff is by no means an invention, I just put severalsearching 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 Googleas what I did was creating a page to filter results. You can also choose tosearch books in Amazon below.PS: the page can also be used for keywords nothing to do with Quantstaff as long as google catches them.

Anyway, hope you find it somehow useful: Google Quant Staff,bookmark if you like.Tags - google , quant

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

Page 143: Quantitative Finance Collector

Vanna Volga Method

The vanna volga method is a popular pricing model for impliedvolatilities, especially for foreign exchange options, it is an empiricalprocedure that can be applied to "draw" an implied volatility smile curvefrom three given quotes (reversal, ATM and butterfly) for a certan timeto maturity. Empirical research shows the vanna volga method has acomparable pricing performance with some stochastic volatility model,for example, Castagna and Mercurio (2007) show the implied volatilitycurve of vanna volga method outperforms that of Malz (1997), andperforms equally well as of SABR (2002).

By building a self-financing portfolio consisting a unit of option at strikeK, -delta1 units of underlying asset, and -xi units of options at strike ki,Castagna and Mercurio (2007) calculate the weight xi for three givenquotes with the help of Ito's lemma and then approximate the Europeanoption value under vanna volga method, as stated in the paper, VVpricing model has several advantages: "it has a clear financial rationalesupporting, based on the hedging argument...; it allows for an automaticcalibration to the main volatility data...; ... it can be extended to anyEuropean-style derivative..."

Below is a simple Matlab code to price a call option based on Castagnaand Mercurio (2007):% option price under Vanna volga model for any strike k% sigma2 is ATM implied vol, k2 is ATM strikes = 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);

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

Page 144: Quantitative Finance Collector

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 formulafunction 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 VVpricing model. Interested ppl please refer to http://www.risk.net/risk/technical-paper/1506580/the-vanna-volga-method-implied-volatilitiesor an advanced one www.mathfinance.de/wystup/papers/wystup_vannavolga_eqf.pdfTags - volatility

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

Page 145: Quantitative Finance Collector

Post your article on this blog

Happy new year!

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

Forgive me if I didn't reply individually, the general answer is: YES, youcan, but subject to the following criteria:1, the content of the article must be relevant to quantitative finance ingeneral, specifically, any article about quantitative trading, quantitativerisk analysis, derivative pricing code and software, etc., is highlywelcomed;2, the article must be unique and writen only for Quantitative financecollector 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 recoganizedby 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-winstrategy.Tags - blog

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

Page 146: Quantitative Finance Collector

Friday reading list 12/25/09

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

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

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

Page 147: Quantitative Finance Collector

Happy Christmas 2009

Christmas & New Year are around the corner, many thanks for your visitand 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

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

Page 148: Quantitative Finance Collector

Earn money as a part-time Quant

Thought twice before typing these words, ok, let me make it clear, thispost is only for those people with similar situation with me: either beinglaid 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 nowstudying for my PhD. I am writing the post to share my experience as apart-time Quant, earn little cash to cover my living costs (plus expensesfor beer in weekends), most importantly, to do jobs we like (pleaseforgive me if you notice I add ad block on my blog, I increase my alcoholintake, practice really makes perfect...)

I know Elance several weeks ago refered by a friend of mine, who is asoftware engineer and gets used to do SOHO jobs, "why not try to be afreelancer since you now have enough self-controlled time?", that's thefirst reaction he had, then I knew the site and started to earn sparemoney. Basically Elance is a portal where companies find, hire, manageand pay contractors online, and is a place independent professionals tomeet clients and get paid for delivering great results. I personally foundseveral great projects already, not bad payment plus opportunities topractice our quant knowledge, for example, two randomly chosenprojects 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 atElance and search over 30,000 jobs today. and Bid on the Project, onceyour 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 peopleto register as a tutor and to teach part time.

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

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

Page 149: Quantitative Finance Collector

Friday reading list 12/18/09

Instead of posting Chinese financial news, I will collect a list ofinteresting paper to read on every Friday, hope you'll enjoy them (pleasedon'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 empiricalresults highlight the potential for 'stock-picking' in international indexes,using characteristics such as value and momentum, with thecharacteristic-based portfolios obtaining Sharpe ratios approximatelythree 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 onwhich the no-arbitrage condition can be imposed. We estimate this newAFGNS 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 WaveletsAnalysis. "we provide MATLAB routines for two major used tradingrules, the moving average indicator and MACD oscillator as also theGARCH univariate regression with Monte Carlo simulations andwavelets 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 andEvidence. "We develop a reduced-form approach for valuing callablecorporate bonds by characterizing the call probability via an intensityprocess. Asymmetric information and market frictions justify theexistence of a call-arrival intensity from the market's perspective. ...Empirical results show that the reduced-form model fits callable bondprice 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/

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

Page 150: Quantitative Finance Collector

remembering_paul_samuelson.html.

Have a nice weekend, everyone.Tags - friday

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

Page 151: Quantitative Finance Collector

Conference on Computational Topics in Finance

As an ETH alumni, I am always with pleasure to post any issueregarding ETH, let alone this conference is highly relevant to our topic:quantitative finance and Rmetrics. Please read the conferenceannouncement, 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 NationalUniversity of Singapore.

The conference will bring together developers, practitioners, and usersfrom academia, finance and insurance, providing a platform for commondiscussions and exchange of ideas. The topics will include usingR/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 arenow accepting submissions; please send your one-page abstracts tosubmissions [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 WuertzJuri HinzMahendra MehtaDavid ScottTags - conference , r

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

Page 152: Quantitative Finance Collector

Derivative pricing Engines

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

Interested reader shall check at its website athttp://www.derivativeengines.com/index-3.asp

Tags - derivative

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

Page 153: Quantitative Finance Collector

Quant jobs received within last ten days

Ten days ago we set up a quant jobs board and introduced at theprevious post Publish / Apply Quant Jobs, so far with the help ofsubmitters there are over 10 jobs listed,

Market Risk Associate at Goldman Sachs in NewYork ;Quantitative Analyst (Market Risk) at Credit Suisse in LondonSenior Quantative Analyst at ICBC in BeiJingSummer Internship Opportunities 2010 at Macquarie in LondonTrainee - Capital Markets at Calyon in HongKongHedge Fund Associate at Apex Capital Management in HongKongBarclays Capital Summer Internships at Barclays Capital in LondonLong-Term Internships at BNP Paribas, AnywhereJ.P. Morgan summer internship programme - London at JP Morgan inLondonGlobal Modelling and Analytics Group - Quantitative Summer Institute(QSI) 10 week internship progra at Credit Suisse in LondonAssistant Fixed Income and CDS Trader at AXA in Paris

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

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

Page 154: Quantitative Finance Collector

Computational Finance Virtual Conference

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

Still Time to Access Exclusive Content from the Computational FinanceVirtual Conference.

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

Conference HighlightsKeynote SpeakersManaging Diversification[Dr. Attilio Meucci, Head of Research Bloomberg ALPHA PortfolioAnalytics and Risk] Dr. Attilio Meucci, Head of Research BloombergALPHA Portfolio Analytics and Risk

Rigorous Intraday Trading: Best Quantitative Practices to Minimize YourTracking Error[Charles-Albert LeHalle Head of Quantitative Research Credit AgricoleChevreux] Charles-Albert LeHalle Head of Quantitative ResearchCredit 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 conferencepresentations by MathWorks product experts, research the latestinformation on MATLAB and several products designed specifically for

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

Page 155: Quantitative Finance Collector

the financial industry.

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

After a simple free registration you will be led to a page where visualconference is being hold, where you can watch conference video atconference hall, download resource at resource center, chat withrepresentatives at exhibition hall, have a casual talk with other people atnetworking lounge, etc.

Interesting, register Until January 15 here.‏Tags - conference , matlab

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

Page 156: Quantitative Finance Collector

My tweets of the week 12.05 ~ 12.11

1, Want to invest like the former Merrill Lynch champ? Bob Farrell's 10Rules 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

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

Page 157: Quantitative Finance Collector

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-sampleperformance, to name a few, heston stochastic volatility model, SABRstochastic volatility model and Garch option pricing. Here is a paper "OnJustifications for the ad hoc Black-Scholes Method of Option Pricing"where the author interpolates the implied volatility, substitutes the resultinto Black Scholes formula, which outperforms the original BlackScholes model. Straightforward and few more lines to your codes areenough.

QuotationAbstract: One of the most widely used option valuation proceduresamong practitioners is a version of Black-Scholes in which impliedvolatilities are smoothed across strike prices and maturities. A growingbody of empirical evidence suggests that this ad hoc approach performsquite well. It has previously been argued that such a procedure worksbecause it amounts to a sophisticated interpolation tool. We show thatthis is the case in a formal, asymptotic sense. In addition, we conductsome simulations which allow us to examine the importance of thesample size, the order of the polynomial, and the recalibration frequencyin controlled settings. We also apply the ABS approach to daily S&P 100index options to show that the procedure outperforms the Black-Scholesformula in valuing actual option prices out-of-sample.

Download the PDF at http://www.uh.edu/~jberkowi/ and the matlabfiles at http://www.bepress.com/snde/vol14/iss1/art4/.

Tags - black scholes , volatility

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

Page 158: Quantitative Finance Collector

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-costlibraries,* 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.htmlTags - numerical

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

Page 159: Quantitative Finance Collector

Paul Wilmotts new book on quantitative finance

Paul Wilmott has written a new book Frequently Asked Questions inQuantitative Finance since his first version two years ago. I was reallyexcited when I read the first version as he explained every questionwithin several extremely easy paragraphs even for starters, which makesme recall what the CEO of alibaba once said during his presentation: "Iwould explain my business plan to my grandmother to make sure she isable to understand before we take action."

Anyway, I have ordered the new book and am still waiting for mypackage. Just a short comparision from the contents between first andsecond version, it seems besides the up-to-date of several chapters like"Popular Quant Books", "The Most Popular Search Words and Phraseson Wilmott.com" and "Brainteasers", the author adds a new chapter "thecommon mistakes in quantitative finance", which might refer to thecurrent credit crisis and draw lessons from it. Plus, the author adds twomore ways to derive Black Scholes formula to a total of twelve differentways, interesting.

Look forward to reading it.Tags - wilmott

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

Page 160: Quantitative Finance Collector

Publish / Apply Quant Jobs

We added a new section into our site: Quant Jobs, which is a portal topublish 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 thefield of quantitative finance, financial engineering from the rightbeginning of inception. All of its visitors are quant wannabe or alreadyquants (analyst, trader or developer, including the bloggers), therefore aquant job listed here is able to attract the exact types of jobseekers, or putanother way, to maximize the recruiters' utility under the constraint ofresources spent in posting.

Traffic and GrowthBelow is a snapshot of traffic this site received in Oct, 2009.Among them, nearly 40% is from United States and Canada, 30% is fromUnited Kindom and other European countries (mainly France, Germany,Switzerland and Italy), 10% is from China (HongKong), Singapore andJapan. And we will be actively increasing the exposure of this quant jobboard.

CostJobseekers and recruiters from the hiring financial institutions are free touse & publish opportunies, while we charge 20 US dollar or 12 GBPpounds per job posted by recruiters from headhunter agency. As we tryseriously to benefit all parties involved, we will NEVER delete any jobpublished as long as the link keeps alive, which means you can leaveyour company profile, URL link at this job board forever. (even cheaperthan 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 necessaryinformation such as job requirement, link to the job, contact info, etc. andfinish. You have to pay if you are an agent, otherwise we have the rightto delete your post.

How to apply for a job?If a recruiter chooses "Allow Online Applications", applicants are able to

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

Page 161: Quantitative Finance Collector

apply directly by clicking "Apply Online" at the lower side of page andsending 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

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

Page 162: Quantitative Finance Collector

My tweets of the week

Weekend again, list a selected Tweets of this week to read, have a niceweekend 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 Equitieset 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 ForChina, No Default In Europe - Wall Street Journal: http://url4.eu/qfdz;7, Pawel_Schwab, Value-at-a probability not to/to succeed in financialengineering (assets allocation), the real eng-ing is it? http://arxiv.org/pdf/0911.4030.

Tags - twitter

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

Page 163: Quantitative Finance Collector

Zero coupon CIR bond price

A simple Matlab code to calculate a zero-coupon bond price under theCox-Ingersoll-Ross (CIR) Interest Rate Model, where r0 is the currentinterest rate, alpha, kappa, sigma are CIR parameters standing for meanreversion speed, long term mean rate, and volatility of interest rate, T isthe maturity of bond.h = sqrt(kappa^2 2*sigma^2);A = (2*h*exp((kappa h)*T/2)/(2*h (kappah)*(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

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

Page 164: Quantitative Finance Collector

Watch Free Business TV online

Below are a list of free online TVs relevant to business/finance/stockmarket I often watch, hope you also enjoy them. To watch, simple click"Open/close the player" (I assume you install windows mediaplayeralready). 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 Forexforecasts FREE through February 10. Get your free Forex forecasts.

Tags - tv , online

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

Page 165: Quantitative Finance Collector

Pricing Parisian Options

A parisian option pricer was shared at the post before athttp://www.mathfinance.cn/parisian-option-pricer/, where the authorsHaber, Schoenbucher, and Wilmott values Parisian and Parasianoptions via explicit finite difference method. (Parisian option is a barrieroption but becomes activated only after stock prices have spent a certaincontinuous, pre-decided time, called a window, above or below thebarrier.)

Unfortunately, the authors don't release their codes for us to study, Itried to program according to that paper with theta scheme finitedifference, where theta =0, 0.5, 1 refer to explicit, Crank-Nicolson, andimplicit finite difference, respectively. Below is a runnable naive Matlabcode, please correct me if you find errors, cheers & have a nice weekend.% set parameterN = 201; M = 200; s = 10; T = 1;Tau = 0.1; �rrier window 20 dayssigma = 0.2; r = 0.05; K = 10;Bar = 12; �rrierbar = log(Bar);% time-space gridR = 3;h = 2*R/(N 1);k = T/M;NoTau = floor(Tau/k);x = linspace(-R,R,N 2)';

% compute finite difference matrix Ae = 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 schemetheta = 0.5;B = speye(N,N) theta*k*A;C = speye(N,N) - (1-theta)*k*A;% compute initial datau = max(exp(x)-K,0);

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

Page 166: Quantitative Finance Collector

u = repmat(u,1,NoTau 1);inx = find(x>bar,1,'first');u(:,1) = 0; %up and out when j=tauf = zeros(N,1);% start timesteppingfor m = 1:M

lastu = u;% compute right hand sidefor j = 2:NoTau 1

f = C*[lastu(2:inx-2,NoTau 1);lastu(inx-1:end-1,j-1)]; �low usingtau=0, above using tau=tau 1;

u(:,j) = zeros(N 2,1);% solve the linear systemu(2:N 1,j) = B\f;

endu(inx-1,2:NoTau) = u(inx-1,NoTau 1);%reset value at barrier point for

parisianlastu = u;

end

Plots of the Parisian option and its delta W.R.T stock prices and barrierTau.

Tags - parisian , finite-difference

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

Page 167: Quantitative Finance Collector

My Thanks This Year

2009's Thanksgiving day has come, I would like to show my thanks ofthis year to:1, my professors at ETH and university of Zurich for their professionalguide 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 supervisemy 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 madedeliberately;4, my former colleagues at xQuant and AHL for their encouragementduring my gloomy days;5, all readers of my blog, especially those leaving comments and sharingwith me cool web sites;6, ...

Back to my old post 10 Bestselling Quant books below $17.55, since thereare 2 people participating, my first run randint(1,1,[1,2]) returns 2, soCongratulations Eugene! Please drop me a line about your postaladdress in US, the book you like to [email protected], I'll send thebook to you ASAP. Sorry nico. Thanks both for your participation.

Tags - thanksgiving

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

Page 168: Quantitative Finance Collector

Online stock practice

Suppose you have created several quantitative trading strategies, testedboth the in-sample and out-of-sample performance of those strategiesusing free historical stock data, and found some of them are reallyprofitable and have good sharpe ratio, what will you do next? put yourreal money into the stock market and start trading? Yes, you can, but youare in the danger of slippage risk of your mis-estimated model (or youeven don't consider that for backtesting at all), which might kill yourprofit. (slippage is the difference between estimated transaction costsand the amount actually paid, or between the price you want to buy/selland the price you indeed execute.) Many investment firms prefer to usepaper trading (sometimes also called "virtual stock trading"), which is asimulated 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 partywilling 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 marketsituation (bid, ask, etc.) and therefore is an excellent free tradingpractice. Today I introduce two online stock practice portal, one inEnglish and one in Chinese: first one is Up & Down Practice InvestingWithout Risk, registration is free and easy, simple filling in basicinformation 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 realmoney if you are a student and have .edu mailbox. Each member has apersonal profile page showing the latest trading activity, profit and loss,rank, your friends' performance, etc., which is a good way to connectwith the members of your network. Starting stock trading practice issimple, go to trading section you will find

where you are able to place orders, to make it as real as possible, thereare 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 yourtotal portfolio value are not allowed.# Trades that take your position in any stock to more than 5% of its

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

Page 169: Quantitative Finance Collector

average daily volume are not allowed.# You can only sell short if your buying power exceeds the size of theshort position.# Your portfolio account is a margin account with a 100% initial marginrequirement (total positions cannot exceed portfolio value).Ready? Join The Investing Social Network and Begin Online StockPractice.

The other portal is http://www.cofool.com/, which is similar except thesite is in Chinese and special trading rules of Chinese stock market areapplied.

Have fun practice stock trading.

Tags - trading

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

Page 170: Quantitative Finance Collector

RQuantlib

Quantlib is a free library for modeling, trading, and risk management inreal-life providing a comprehensive software framework for quantitativefinance, it is written in C++, which might be inconvenient for someusers. 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 sourcecode is at http://cran.r-project.org/web/packages/RQuantLib/index.html, which is self-contained and does not even require aQuantLib (or Boost) installation. Nothing more to say, following theprocess, 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 offixed-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

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

Page 171: Quantitative Finance Collector

10 Bestselling Quant books below $17.55

You might wonder why I named the title, today I received a gift cardfrom Amazon with value of $17.55, because Amazon pays mecommision 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 isless appealing to me as I am not in US, nor have a friend there, so I amthinking it should be valuable for those readers of my blog located in US.

The story is like this: I search "quantitative finance" and "financialengineering" at Amazon, sort the results by bestselling, and select thosebooks below $17.55. If you happen to be in US (or have a postal addressin US), just leave a comment at the end of this post telling the number ofbook you would like. One week later, that is 2009-11-27, a randomcommentator will be chosen and wins the book s(he) likes. Here randominteger generator randint(1,1,[1,N]) in Matlab will be used, N is numbersof commentator, for example, if two people leave a comment, each onehas 50% chance; if one people replies (s)he will definately win; if nobodyparticipates, the gift card will be expired and Amazon smiles. (no needto 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

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

Page 172: Quantitative Finance Collector

Missing data imputation

Probably all of us have met the issue of handling missing data, from thebasic portfolio correlation matrix estimation, to advanced multiple factoranalysis, how to impute missing data remains a hot topic. Missing dataare unavoidable, and more encompassing than the ubiquitousassociation of the term, irgoring missing data will generally lead tobiased estimates. The following ways are often applied to handle theproblem:1, simple deletion strategies: including pairwise deletion and listwisedeletion, the former may lead to inconsistent results (e.g., not positivedefinite correlation/covariance matrices), while the cumulation ofdeleted cases may be enormous except in the case of very few missingvalues for the latter method;2, so called ‘Working around’ strategies, for example, the FullInformation Maximum Likelihood (FIML) integrates out the missingdata when fitting the desired model;3, imputation strategies, these are the most widely used methods both inacademia and industry, replacing missing value with an estimate of theactual value of that case. For instance, ‘hot-deck’ imputation consists ofreplacing the missing value by the observed value from another, similarcase from the same dataset for which that variable was not missing;mean imputation consists of replacing the missing value by the mean ofthe variable in question; expectation Maximization (EM) arrives at thebest point estimates of the true values, given the model (which itself isestimated on the basis of the imputed missings); regression-meanimputation replaces the missing value by the conditional regressionmean; 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 IIdeveloped by professor Gary King from Harvard university, as itswebpage introduces: Amelia II "multiply imputes" missing data in asingle cross-section (such as a survey), from a time series (like variablescollected for each year in a country), or from a time-series-cross-sectionaldata set (such as collected by years for each of several countries). AmeliaII implements bootstrapping-based algorithm that gives essentially thesame answers as the standard IP or EMis approaches, is usuallyconsiderably faster than existing approaches and can handle many morevariables....Unlike...other statistically rigorous imputation software, it

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

Page 173: Quantitative Finance Collector

virtually never crashes.

Amelia II was developed based on R language, so users have to install Rbefore running it, installation of Amelia is staightforward: download andrun the exe file, that's it. For me, the beauty of Amelia II is its friendlyinterface, I don't even need to run R software myself. Double clickingAmelia 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 imputeddata, amazing, isn't it?

Downloading the software and help documents athttp://gking.harvard.edu/amelia/.

Tags - missing-data

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

Page 174: Quantitative Finance Collector

Yahoo chinese historical stock data

Wrote a simple script to fetch historical stock data from Yahoo.cnfinance and to save as a csv file, please be aware this script is only forthose interested into downloading free historical prices of firms listed inShanghai and Shenzhen stock exchanges only, (indeed not only stockdata, but also Chinese warrant data.) Plese check free real time stockquotes or historial stock price from Yahoo if you prefer non-Chinesestocks.

1, why do I write it since finance.yahoo.com provides such a modulealready, 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 tradingstrategies involve historical open, close, high, low data, for example, awidely used stochastic indicator compares current prices to the high andlow range over a look-back period, therefore unadjusted high, low datamight mistakenly treat a lose strategy as a win strategy. Below aresnapshots of stock prces downloaded directly from finance.yahoo.comand from this script, where on 20090610 the stock paid out a dividend.

2, you prefer to download historical stock data from Yahoo, dividendinfo for each stock and adjust the data yourself instead of using thisscript.Fine, if you are happy.

3, you have option to download daily, weekly or monthly data using thisscript, 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. Forinstance, http://www.mathfinance.cn/yahoo-chinese-stock-

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

Page 175: Quantitative Finance Collector

quotes.php?stockNo=600030&exchange=ss&dateType=day will pop upa window asking you to save or open the data in csv. Leave a messagehere for any error or share with others if it is helpful, thanks.

All stock data is from Yahoo finance China, please obey the policy ofYahoo finance.Tags - yahoo , data

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

Page 176: Quantitative Finance Collector

Garch option pricing

We all know one assumption of Black Scholes model is constantvolatility during option period, which has been relaxed by severalmethods including Heston stochastic volatility, SABR stochasticvolatility, etc. Here is another way proposed by Jin-Chuan Duan,Geneviève Gauthier, and Jean-Guy Simonato in their paper "Ananalytical 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.QuotationGARCH option pricing framework has been developed in recent years.However, an efficient method for computing option prices in thisframework remains lacking. In this article, a fast analyticalapproximation is developed for computing European option prices inthe GARCH framework. The approach, following that of Jarrow andRudd (1982), uses the Edgeworth expansion of the risk-neutral densityfunction. Analytical expressions for the first four moments of thecumulative asset return over any horizon under the GARCH model arederived in this paper. A numerical analysis shows that these momentformulas are accurate under fairly general conditions. The analyticalGARCH option pricing formula based on the Edgeworth expansion isfound to work well for short-maturity options. For long-maturityoptions, the approximate formula is generally satisfactory, except whenthe volatility dynamic of the GARCH model exhibits an extremely highlevel of persistence.

Matlab codes can be downloaded at http://www.rotman.utoronto.ca/~jcduan/mainfram.html, several other programming files can be alsofound 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, Estimatingexponential affine term structure models, and Maximum likelihoodestimation method for Merton's deposit insurance pricing model.Tags - garch , volatility

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

Page 177: Quantitative Finance Collector

Jim cramer stock market

Spent the half afternoon watching Jim cramer's mad money TV show onCNBC, it is a really interesting and inspiring programme, I didn't realizethe time passed so quickly till my roommate invited me for a dinner, theonly 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, aformer hedge fund manager, and a best-selling author (Wikipedia saysso). He is the host of CNBC's Mad Money and is also a contributor toNew York magazine and Time Magazine. The TV program Mad Moneywith Jim Cramer began on CNBC in 2005. as mentioned on CNBC's Website: the show"...is not to tell you what to think, but to teach you how tothink 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 – tipsare for waiters. Our mission is educational, to teach you how to analyzestocks and the market through the prism of events."

Sounds good so far? here is a collection of Jim cramer's video on stockmarket, cheers.http://www.cnbc.com/id/24109723/, and gain full access to hispersonal portfolio at

Tags - jim-cramer

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

Page 178: Quantitative Finance Collector

Numerical Integration Code

A followup post of my previous entry Using Quadrature method foroption valuation, where I tested the alternative numerical method foroption valuation, QUAD. If you read the original paper, you will noticeat the end all option valuation problems are to solve an integralequation, therefore a good & proper numerical integration methodbecomes especially crucial.

My example in that post used simply Matlab embedded command"quadl", however, when the option becomes exotic, or the option hasmultiple observation times (for example, a Bermudan option), quadlcan't be applied anymore as we have to match the nodes of thesedifferent observation times. (quadl does not allow users to specify howmany points and how small interval an integral can have, correct me if iam wrong). Here is a good site on numerical integration code I just dugyesterday: Transforming Numerical Methods Education by University ofSouth Florida, which is for undergraduate student at engineering ormathematics and is therefore in plain language, easy to understand. Forexample, 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 explaineddocuments, matlab and MATHEMATICA codes, and even Youtubevideo......

Have fun at http://numericalmethods.eng.usf.edu/index.html. A minordefect is its gauss quadrature point is up to 10 only, no worry, shouldyou are unhappy with that, another C/C++ code on Gauss quadraturecan be found at http://www.holoborodko.com/pavel/?page_id=679.

Tags - quadrature , integral

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

Page 179: Quantitative Finance Collector

56 ethnic groups in China

I often saw how surprised my friend was when I told him there are 56ethnic groups in China, in many people's eyes, Chinese look like thesame, which is understandble as around 91.59% of the population wasHan Chinese and most minority ethnic groups Chinese have kept thetradition to live and stay where their ancestors used to live, hereafterleading to immobility and normally what we see overseas Chinese areHan Chinese (good or not?). I myself have only got in contact with lessthan 10 ethnic groups so far, however, it is indisputable each group hashad a brilliant contribution to the development of China, no single groupis allowed to be separated. Anyway, a beautiful flash shows theappearance difference of 56 ethnic groups in China.

Tags - china , ethnic

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

Page 180: Quantitative Finance Collector

Using Quadrature method for option valuation

Reading an interesting paper "universal option valuation usingquadrature methods", which provides an alternative method to valueoptions. Compared with lattice (binomial and trinomial trees), finitedifference, and Monte Carlo techniques, quadrature method (QUAD)possesses exceptional accuracy and speed, while isn't harder toimplement. Basically what we need to do is to write down the problemin an integral function and to solve the function with techniques likeSimpson's rule or Gauss Quadature, ect.

For s short comparison, a simple QUAD code to price a vanilla Europeancall option is as follows, please refer to the original paper for themeaning of symbols:%using QUAD to calculate a vanila european callx0 = 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 embeddedquadraturecallprice = 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 is1.71429100893328, with 0.005681 seconds elapsed time using my humblelaptop, in contrast with the embedded Black Scholes matlab functionvalue 1.71429100824415, and 100 time steps binomial tree value1.71422035929822. QUAD performs quite good, isn't it?

The exotic option pricing is left for further experiment, have a niceevening.

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

Page 181: Quantitative Finance Collector

PS: i was seriously drunken last weekend, my poor stomach.Tags - quadrature , integral

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

Page 182: Quantitative Finance Collector

SOCR of UCLA

Statistics Online Computational Resource (SOCR) is a great applicationbuilt by University of California, Los Angeles (UCLA). What is SOCR?QuotationThe aims of the Statistics Online Computational Resource (SOCR) are todesign, validate and freely disseminate knowledge. Our Resourcespecifically provides portable online aids for probability and statisticseducation, technology based instruction and statistical computing. SOCRtools and resources include a repository of interactive applets,computational and graphing tools, instructional and course materials.

What are the main SOCR Components?QuotationThe core SOCR educational and computational components include:Distributions (interactive graphs and calculators), Experiments (virtualcomputer-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 (toolsfor distribution, polynomial and spectral model-fitting and simulation),Graphs, Plots and Charts (comprehensive web-based tools forexploratory data analysis), Additional Tools (other statistical tools andresources), SOCR Wiki (collaborative Wiki resource), EducationalMaterials and Hands-on Activities (varieties of SOCR educationalmaterials), SOCR Statistical Consulting and Statistical ComputingLibraries.

As its name suggests, SOCR is mainly for people learning statistics, forexample, to fit a certain probability, to draw density graph of a selecteddistribution, 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.htmlTags - statistics

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

Page 183: Quantitative Finance Collector

Rejection (or offer) season

It seems the time or to most people time has come this year, many peopleof a quant job board I often visit complain how many rejection lettersthey have got today, which makes me recall my gloomy life half a yearago. Anyway, cheer up & take a rest, a joke forwarded by a friend ofmine, have a nice day:

Dear **,

Thank you for your letter of today. After careful consideration, Iregret to inform you that I am unable to accept your refusal to offer me aQuantitative analyst position in your department.

This year I have been particularly fortunate in receiving an unusuallylarge number of rejection letters. With such a varied and promisingfield of candidates, it is impossible for me to accept all refusals.

Despite your outstanding qualifications and previous experience inrejecting applicants, I find that your rejection does not meet my needsat this time. Therefore, I will assume the position of Quant analyst inyourdepartment this December. I look forward to seeing you then.

Best of luck in rejecting future applicants.Sincerely,**Tags - job , joke

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

Page 184: Quantitative Finance Collector

Quantitative trading strategies

Spent several days reading a book named Quantitative TradingStrategies: Harnessing the Power of Quantitative Techniques to Create aWinning Trading Program, compared with the book QuantitativeTrading: How to Build Your Own Algorithmic Trading Business I read &shared at my earlier post Matlab trading code, this one is in more detailand more practical. For me, Quantitative trading is a good introductorybook showing starters what algo trading is and how to begin and whatto prepare in order to be an independent quant trader, whileQuantitative trading strategies explains what a good trading strategy is,how to test a trategy a trader has, what's more, the author is kind enoughto disclosure dozens of strategies he created. Whether those tradingstrategies still work or not is another issue, but at least readers are able tohave a rough picture in mind the pros and cons of each strategy, thepossible way to modify them for our own use after reading it.

Anyway, it is your turn to compare them. I write M files of severalselected quantitative trading strategies from the book I have played, beaware 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 daymoving average, short when x day moving average crosses below y daymoving averagepos=zeros(size(price,1),1);[lead,lag]= movavg(price,x,y,'e');lead = [zeros(x-1,1); lead]; %to avoid dimension mismatchlag = [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 CUpperTrigger = price(i-1) multiplier*sqrt(C);LowerTrigger = price(i-1)-multiplier*sqrt(C);

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

Page 185: Quantitative Finance Collector

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); %embeddedMatlab functionm = 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 shortlongmom = 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 signalpos=zeros(size(p,1),1);macs = zeros(size(p,1),20);for i=1:20

j=i*4;

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

Page 186: Quantitative Finance Collector

[lead,lag]= movavg(p,i,j,'e');lead = [nan(i-1,1); lead]; %to avoid dimension mismatchlag = [nan(j-1,1); lag];macs(lead>lag,i) = 5;

endmacssum = sum(macs,2);macssum(1:80) = 50; %first 80 observations with zero positionpos(macssum>=N)=1;pos(macssum<=(100-N))=-1;

There are other strategies left to you to backtest the effectiveness oftechnical analysis, for example, Kestner’s Moving Average System,Second Order Breakout, MACD Histogram Retracement, NormalizedEnvelope Indicator, etc. Have fun.Tags - trading , strategy

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

Page 187: Quantitative Finance Collector

Featured Entries of blog

1, Free real time stock quotesThis weekend's review is about a free real time stock quotes website:

ADVFN. Who is ADVFN? ADVFN is the one of the worlds largest stocksand shares websites. Offering the private investor FREE streaming pricesfrom NASDAQ, NYSE, Dow Jones...2, Quantitative trading strategies

Spent several days reading a book named Quantitative TradingStrategies: Harnessing the Power of Quantitative Techniques to Create aWinning Trading Program, compared with the book QuantitativeTrading: How to Build Your Own Algorithmic Trading Business I read &shared at my earlier post Matlab trading code, this one is in more detailand more practical...3, Neural Network Prediction

Neural network matlab source code accompanying the book NeuralNetworks in Finance: Gaining Predictive Edge in the Market byprofessor Paul D. McNelis. This book has got wonderful review like“This book clarifies many of the mysteries of Neural Networks...

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

Page 188: Quantitative Finance Collector

Financial Engineering Resource Center

This week's review is about Financial Engineering Resource Center(FERC). What is FERC, as the site describes, "Basically, Financialengineering resource center (FERC) aggregates useful posts/info from allaround 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 websiteson FERC only, hopefully it will save the time and improve workefficiency.

Currently FERC has the following sections: Books, Daily news, Job,Journal, Quant answer, Software, Trading and Video. Simply from thename we can guess the content under each section, for example, dailynews is about some recent interesting news might be worth reading;trading is the latest model and technique written by well-known quanttrader, etc. There are subsections under several categories, Job consists ofUK, US, Asia and world, Journal includes Journal of finance, Journal offinancial economics, Mathematical finance, etc., where people can trackthe latest publications for each selected Journal.

Overall I find FERC makes my daily reading easier, check FinancialEngineering Resource Center (FERC) if you are curious as well.Tags - financial-engineering

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

Page 189: Quantitative Finance Collector

Algorithmic Trading with MATLAB Webinar

Just a followup of my previous entry Matlab trading code, where youcan watch Algorithmic Trading with MATLAB Webinar following oneof the links. Dr. Aly Kassam again introduces in plain language how touse 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

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

Page 190: Quantitative Finance Collector

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 Ioften heard is its slow speed. As an Interpreted Language, Matlab is insome sense less efficient than Compiled language, however, we canspeed it up by using tricks like vectorization, to fly your Matlab, beloware 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. Beready to take off.Tags - matlab

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

Page 191: Quantitative Finance Collector

Gaussian Process Regression

I recently read a paper comparing the performances of different modelsto predict stock returns, at the end the authors rank the models by theirout-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 bythe authors, as stated: "A List of different monitored learning techniqueshave been attempted to predict future stock returns, both for potentialmonetary make and because it is an interesting research problem. Weuse regression to capture changes in stock price prediction as a functionof a covariance(kernel or Gram) matrix. For our aims it is natural to think of the price ofa stock as being some function over time. Generally, a Gaussianprocesses can be cosidered to be defining a distrubution over functionswith the inference step occurring directly in the space of functions. Thus,by using Gaussian process regression to extend a function beyondknown price data, we can predict whether stocks will rise or fall the nextday, and by how much."

Should you are interested, here is a book Gaussian Processes for MachineLearning to be freely downloaded, accompanying Matlab package is alsoavailable at the website.http://www.gaussianprocess.org/gpml/Tags - regression

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

Page 192: Quantitative Finance Collector

Neural Network Calculator

A friend recommended me this software, frankly speaking, I am not fullyconvinced by the effectiveness of those black-box models like neuralnetwork 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 beeninspiгed bү һow biologicаl neural networks work. Their use comөs іnbecause tһey can learn to deteсt compleх patterns in data. Inmathematical tөrms, they aгe universal non-lineаr functionapproximators 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 theserіes of ruleѕ for generating өntry/exit signals but also provides abridgө 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, theiraccuracy and prediction capabilitіes can bө both mathematiсally аndempirically tested. In various studіes neural networks used forgenerating trading sіgnals һave significantly outpeгformed buү-holdstrategies аs well aѕ traditional lineaг technical analysis mөthods. Whilethe advanced mаthematical nature of ѕuch adaptive systems haνe keptneural networks for financiаl analysis mostly within academіc reѕearchcirс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 οfstο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гelooked 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, whilethө υser participates by сontrollin# rөlating the priсes аnd volumes tothe 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

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

Page 193: Quantitative Finance Collector

and rigorous backtesting. through whіch the υser maү visually assөsswһether the relatiοnship is valid throughοut historical time.* The relationshiр іs extended intο the future to мake a forecast, by tһenuм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 onthө user'ѕ visual verification οf tһe matсh between the tωo grаphsoЬtained during backtesting, and the his estimation of the likelihood thattһe mathematical relationship which has bөen found will continue tohold 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

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

Page 194: Quantitative Finance Collector

Basic Bond Calculator on Gphone

Compared with option calculators on Gphone introduced before, Basicbond calculator is a simple application aiming to price a vanilla bondvalue and yield to maturity (YTM) only. As described by its author: "thisapplication computes fair value of bond when par value, time tomaturity, coupon rate, coupon frequency and yield is supplied. Itcomputes yield when bond price is supplied. Maturity time can beentered or selected. Coupon is paid semi-annually by default. Currentdate is auumed to be the settlement date."

A snapshot looks like

To install the application, just search "bond calculator" at the Marketsection of your gphone.Tags - calculator , gphone

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

Page 195: Quantitative Finance Collector

Chinese financial news

From this weekend on, I will collect Chinese financial news (ideally onquantitative finance) of the past week, hoping to help those people whohave 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-42270120090907Bank of China to invest in hedge funds, http://www.ft.com/cms/s/0/2e1eaef0-9da0-11de-9f4a-00144feabdc0.html;

Tags - china

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

Page 196: Quantitative Finance Collector

Test cointegration with R

Cointegrated pairs of securities are crucial for mean reversion tradingportfolio construction, Play with cointegration has several good papersto start with. Should you want to test pairs of securities for cointegrationusing R, here is an excellent webpage with data, code and detailedexample, cheers.

http://quanttrader.info/public/testForCoint.htmlTags - cointegration

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

Page 197: Quantitative Finance Collector

Matlab trading code

I have been on vacation for exactly two weeks, reading Chinese fictions,visiting parents and friends, enjoying delicious food, etc. Life iswonderful except I have a little worry about my British visa.

Quantitative Trading: How to Build Your Own Algorithmic TradingBusiness is a great book I bought several months ago but had fewchances to read until recently. It is an easy-to-understand book onimplementing quantitative (or algorithmic) trading for independenttraders. This is the area fascinating me from right the beginning oflearning quantitative finance. Therefore I have started to play algorithemtrading with Matlab, the three sites I have visited often within the lastweek are:Recorded Webinar: Algorithmic Trading with MATLAB for FinancialApplications: http://www.mathworks.com/company/events/webinars/wbnr30376.html?id=30376&p1=50647&p2=50649Trading with Matlab: http://www.tradingwithmatlab.com/homeInteractive 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 onMatlab trading, for instance, Pairs Trading, Intraday Data Acquisition.Enjoy.Tags - matlab , trading

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

Page 198: Quantitative Finance Collector

Free real time stock quotes

Get your free real time stock quotes here, one of the worlds largeststocks and shares websites. Offering the private investor FREE streamingprices from NASDAQ, NYSE, Dow Jones and many more indices fromaround the world, We provide free service like Stock Quotes, Watchlists, Charts, Financials News, etc. Being a free member you can access toreal-time Dow Jones and NASDAQ indices, FOREX, managed funds,plus delayed US and world markets stock prices and indices. You willalso 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 quoteTags - data

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

Page 199: Quantitative Finance Collector

FX option calculator

Another FX online option calculator by MathFinance covers Vanillaoption, digital option, touch options (one touch, no touch, double onetouch, double no touch), barrier option (single barrer, double barrier)and Black-Scholes Implied Volatility Calculator.

For detail about options description and calculator please visithttp://www.mathfinance.com/tools/calculator/index.phpTags - calculator , fx

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

Page 200: Quantitative Finance Collector

My last day in office

Today is my last day in the office, I have made up my mind to continueto study a PhD, it is a hard decision without getting much support frommy 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 fornearly two months, visiting my family and friends, travelling around,etc., and come back to UK by the end of August, hopefully. In themeantime I have to reduce blog publishing frequency, but if you do haveany interesting staff, please leave me at http://www.mathfinance.cn/contact-me, thanks.

Have a nice summer.

Tags - career

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

Page 201: Quantitative Finance Collector

Find MFE Program

Master of Financial Engineering (MFE) degree has increasingly becomea shortcut for people willing to work at a financial institution, especiallyto pursue a Quantitative finance related career. There are dozens ofuniversities around the world providing with MFE program, forinstance, Haas MFE, Columbia FE, and NYU are indisputably amongthe best. Sadly or not, only a few people have the chance to study atthese top schools, how do you choose other program then? which factorswill you give priority when applying? location, tuition, possibility to getfinancial aid, job placement?

Find MFE is a simple php+mysql page I wrote yesterday evening, thegoal is to filter your ideal MFE program by the self-defined criteria, forexample, 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 returnthe following MFE programs:1.) Bentley College in Massachusetts2.) Florida State University in Tallahassee3.) Kent State University in Kent4.) Princeton University in Princeton5.) Purdue University in West Lafayette6.) The University of Arizona in Arizona7.) Vanderbilt University in NashvilleClicking the link leads you to a page showing the more detailedintroduction of this program, including length of study, size of class,program website, etc. (some content requires you to be able to get accessto those sites like Youtube, Flickr and Twitter.)

I have no idea if people would find it useful or totally rubbish, it justtests the water, anyway. I fully understand the accuracy of the searchingresults depends largely on the information collected, please do help toimprove it by rating the MFE program, adding a comment or leaving amessage. Thank you. Advanced search like the job placement can beeasily added technically, depending on your feedback.

Find your ideal MFE at http://www.finmath.cnTags - mfe

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

Page 202: Quantitative Finance Collector

Regime-Switching Model library in Gauss

This is the most up-to-date version of the switching regressionprocedures built by Simon van Norden and Robert Vigfusson with helpfrom Jeff Gable. This Regime-Switching Model library lets you toestimate a general class of regime-switching models along the lines ofthose described in James Hamilton's textbook. Key features andlimitations of the code include:one independent variable onlytwo states onlyarbitrary number of observed variables may be included to explain time-varying transition probablities or state-dependent meansexternal c-code, analytical gradients and combined maxlik()/EMalgorithms for fast calculationdescriptive statistics, plots and White's model-misspecification testscascading estimationseparate, faster code for "simple switching" models (i.i.d. mixtures ofregimes.)

learn more and download at http://www.hec.ca/pages/simon.van-norden/codepage.html and a Guide to the Bank of Canada GaussProcedures at http://papers.ssrn.com/sol3/papers.cfm?abstract_id=50565.

Tags - regime , switch

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

Page 203: Quantitative Finance Collector

Vault career guide

This weekend's review is about vault career guide, I bet many peoplehave heard of it or even used it, I remember when I looked for a jobbefore graduation, the two books I read often were Heard on the Street:Quantitative Questions from Wall Street Job Interviews and Vault CareerGuide to Investment Banking, 6th Edition, both of which provide withclear explanation and insightful experience on how to look for a job andprepare interviews efficiently, expecially on investment bankingindustry.

Vault.com is the leading media company focused on careers. Job seekers,students and professionals have discovered that Vault is the Internet'sultimate destination for insider career and education information.

Vault publishes over 120 career guides and its web site, featuresthousands of company, university, industry and occupational profiles.Additionally, Vault provides salary surveys, articles on workplacetopics, a network of message boards for professionals, and job-relatedvideo, blogs and research tools.

Here is an opportunity to sign up for free membership on Vault.com andget Career Guides for Free., enjoy!Tags - career

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

Page 204: Quantitative Finance Collector

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 ofthis paper is to use Monte Carlo simulation, along with Maximumlikelihood estimation (MLE), to reduce the biases caused by MLEmethod alone,QuotationA new methodology is proposed to estimate theoretical prices offinancial contingent claims whose values are dependent on some otherunderlying financial assets. In the literature, the preferred choice ofestimator is usually maximum likelihood (ML). ML has strongasymptotic justification but is not necessarily the best method in finitesamples.This paper proposes a simulation-based method. When it is used inconnection with ML, it can improve the finite-sample performance of theML estimator while maintaining its good asymptotic properties. Themethod is implemented and evaluated here in the Black-Scholes optionpricing model and in the Vasicek bond and bond option pricingmodel. It is especially favored when the bias in ML is large due to strongpersistence in the data or strong nonlinearity in pricing functions. MonteCarlo studies show that the proposed procedures achieve bias reductionsover ML estimation in pricing contingent claims when ML is biased. Thebias reductions are sometimes accompanied by reductions in variance.Empirical applications to U.S. Treasury bills highlight the differencesbetween the bond prices implied by the simulation-based approach andthose delivered by ML. Some consequences for the statistical testing ofcontingent-claim pricing models are discussed.

Download the paper and accompanying matlab code athttp://www.mysmu.edu/faculty/yujun/research.htmlTags - simulation , mle

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

Page 205: Quantitative Finance Collector

Quantitative Asset Management library

I would like to take this opportunity to thank the author Thierry Roncallifor letting me know this great source.

QAM (Quantitative Asset Management) library:QAM is the Gauss library which has been developped for the lecturenotes on Quantitative Asset Management.

This library contains procedures:for computing backtest (monthly rebalancing, currency hedging, strategyleveraging, fees managing, performance reporting, etc.).for portfolio allocation (Black-Litterman, Markowitz, ERC, MDP, riskBbdgeting, 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, Quantileregression, 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, varianceswaps, vix, long/short equity, absolute return strategy, trend-followingstrategy, etc.);for stock screening (gini optimization, scoring methods, boosting, bagingmethod, 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

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

Page 206: Quantitative Finance Collector

Morningstar investment research

This weekend's review is about Morningstar investment research,needless to say, research is the key to success for investment. Founded in1984, Morningstar is one of the most respected names in independentinvestment research and opinion, as well as the recognized leader instock and mutual fund analysis. The mission is to create great investingproducts 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 managementtools, financial data, unbiased stock and fund analysis, videocommentary, and more.

Because the products focus on sound investing fundamentals and take afriendly, easy-to-understand approach, Morningstar appeals to a widerange of investors -- from beginners to the most experienced. They arelikely 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

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

Page 207: Quantitative Finance Collector

Vector autoregression (VAR)

Neil left me a message: "...I am looking for examples of VectorAutoregression so I can code into excel, do you know of any links or anybooks 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 timeseries. It is a natural extension of the univariate autoregressive model todynamic multivariate time series. The VAR model has proven to beespecially useful for describing the dynamic behavior of economic andfinancial time series andfor forecasting. Wikipedia has a detailed explanation on it.

Unfortunately I have not used it except once I tried the built-in VARfunction in Eviews over 5 years ago, when one of my classmates did aseminar presentation on it. Sorry I couldn't find useful VBA code, what ido 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 themodel, hope it helps, http://www.rri.wvu.edu/WebBook/LeSage/etoolbox/var_bvar/contents.htmlTags - vector-autoregression , var

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

Page 208: Quantitative Finance Collector

Sobol sequence generator

Sobol sequence has been shared at posts Sobol and Generalised Fauresequences, halton and sobol sequences, and Primitive polynomials forSobol sequences, respectively. Please read Low-discrepancy sequence atWikipedia for introduction.

Here is another Sobol sequence generator containing the primitivepolynomials and various sets of initial direction numbers for generatingSobol sequences. The reason I open a new post for it is it is able tosupport up to dimension 15000, incredible. Check it out athttp://web.maths.unsw.edu.au/~fkuo/sobol/index.html.Tags - sobol , monte carlo

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

Page 209: Quantitative Finance Collector

Matlab toolbox

Dozens of Matlab toolboxes(packages) for downloading, including thefollowing classifications:Audio - Astronomy - BiomedicalInformatics - Chemometrics - Chaos -Chemistry - Coding - Control - Communications - Engineering - DataMining - 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 Toolboxhttp://ssg.mit.edu/~ihler/code/

BOOTSTRAP MATLAB TOOLBOXhttp://www.csp.curtin.edu.au/downloads/bootstrap_toolbox.html

CompEcon Toolbox for Matlabhttp://www4.ncsu.edu/~pfackler/compecon/toolbox.html

Random Neural Networkshttp://www.cs.ucf.edu/~ahossam/rnnsimv2/

Logistic regressionhttp://www.spatial-econometrics.com/

ARfit: A Matlab package for the estimation of parameters andeigenmodes of multivariate autoregressive modelshttp://www.gps.caltech.edu/~tapio/arfit/

Time Series Analysishttp://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.htmlTags - matlab , toolbox

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

Page 210: Quantitative Finance Collector

Matlab optimization introduction

it is indisputable that optimization has been a crucial part to ourfinancial world, the application of optimization routine ranges fromfundamental mean-variance Markowitz efficient frountier to advancedneural network stock price prediction. Here is a carefully selected groupof methods for unconstrained and bound constrained Matlaboptimization problems including:Line Search Methods:steep.m : Steepest Descentgaussn.m : Damped Gauss-Newtonbfgswopt.m : BFGS, low storagePolynomial line search routines: polyline.m , polymod.mNumerical Derivatives: diffhess.m : Difference Hessian,requires dirdero.m : directional derivative, as do several other codesTrust Region Codes:ntrust.m : Newton's Method with Simple Dogleglevmar.m : Levenberg-Marquardt for nonlinear least squarescgtrust.m : Steihaug CG-doglegBound Constrained Problems:gradproj.m : Gradient Projection Methodprojbfgs.m: Projected BFGS codeNoisy Problems:imfil.m : Implicit Filteringnelder.m : Nelder-Meadsimpgrad.m : Simplex Gradient, used in implicit filtering and Nelder-Mead codeshooke.m : Hooke-Jeeves codemds.m : Multidirectional Search codeCheck http://www.siam.org/books/kelley/fr18/matlabcode.php fordetail.Tags - optimization

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

Page 211: Quantitative Finance Collector

Online Swap Valuation

Bramaan.com is an online facility for the valuation and risk managementof interest rate derivatives.

Bramaan.com provides everything needed to quickly determine the netpresent value, the accrued interest as well as the value of a basis pointfor virtually any interest rate swap contract. This includes, but is notlimited to, the development of custom software platforms and theimplementation of processes and procedures for the dailyadministration, risk-management, quantitative analysis, accounting andtrading of the previously mentioned financial instruments.

Further details can be found here:http://www.bramaan.com/Tags - swap , rate

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

Page 212: Quantitative Finance Collector

Heuristic Optimization for Downside Risk Minimization

Modern portfolio optimization started with Markowitz Efficient Frontier,Heuristic search and optimization is a new approach for solvingcomplex problems that overcomes many shortcomings of traditionaloptimization techniques. Heuristic optimization techniques are generalpurpose methods that are very flexible and can be applied to many typesof objective functions and constraints, especially where the objectivefunction is non-convex and has many local minima. This is in particularthe case when the risk is expressed as VaR, expected shortfall, Omega,maximum loss etc., and when the future returns of the individual assetsare modelled as scenarios.

An interesting paper "A Data-Driven Optimization Heuristic forDownside Risk Minimization" demonstrates how to apply Heuristicoptimization method under constraint of downside risk, code can bedownloaded at http://comisef.eu/?q=resources_data_driven_opt, take alook if interested.Tags - heuristic , optimization

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

Page 213: Quantitative Finance Collector

The end of 100% mortgages is definitely a positive

Consumer Credit awareness website, CreditChoices.co.uk reports thatMajor British lenders such as Abbey Mortgages will not be returning tothe practice of issuing 100% mortgages in the near future. In fact mostUK lenders are requiring as much as 20% deposits on home purchaseloans. While on the surface this may seem an unfair adjustment, onemust also consider that those generous loans were based upon inflatedreal estate values. Further the larger sum that one finances the larger themonthly payment will be. This latter statement illustrated by using theremortgage calculator found at Credit Choices. So we combine these twofactors and arrive at a unique conclusion... we are better off without100% mortgages and easy credit. Consider this, a house costing £200,000just two years ago is selling for around £150,000 today. With a deposit of20% or £30,000 there remains a principle due of £120,000 pounds. Thisresults in a difference of over £500.00 monthly! Imagine the total costover 25 years. Even factors such as mortgage protection are more costlyon the larger loan. Yes many of us may not have the larger sum to placeas deposit but that does not negate the data showing that 100%mortgages do no one any favour.

Tags - mortgage

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

Page 214: Quantitative Finance Collector

SIMTOOLS and FORMLIST Excel add-ins

Simtools.xla and Formlist.xla are add-ins for Microsoft Excel (version 5and later). Simtools adds statistical functions and procedures for doingMonte Carlo simulation and risk analysis in spreadsheets. Formlist is asimple auditing tool that adds procedures for displaying the formulas ofany 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 athttp://home.uchicago.edu/~rmyerson/addins.htmTags - excel

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

Page 215: Quantitative Finance Collector

CreditMetrics spreadsheet

CreditMetrics is a framework for measuring credit risk of portfolios oftraditional credit investments (for example, loans, commitments to lend,financial letters of credit), fixed income products, and market-driveninstruments subject to counterparty default (swaps, forwards, etc.).

It is a lot more complex than RiskMetrics, and thus requires a deliberateinspection. Actually, within the CreditMetrics framework, users areconfronted with a mixture of choices. For instance, CreditMetrics grantsusers to follow one of four different approaches to calculating correlationamong several credit types-historical data, bond spreads, equitycorrelations or consistent constants.

Here is an Excel 7.0 spreadsheet demonstrating how to useCreditMetrics to compute credit risk of a portfolio, technical documentis free to download at http://www.ma.hw.ac.uk/~mcneil/F79CR/CMTD1.pdf. Functions for calculating the CreditMetrics risk model in Rare at: http://cran.r-project.org/web/packages/CreditMetrics/index.htmlTags - creditmetrics , spreadsheet

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

Page 216: Quantitative Finance Collector

My blog is published at Amazon Kindle

Amazon Kindle is a software and hardware platform for readingelectronic books developed by Amazon.com, few days ago a friend ofmine told me Amazon had a new service called Kindle blog, whichgives 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 largestwebsites, I submitted immediately and 10 minutes ago found my blogwas successfully listed at Amazon Kindle.

I intent to make it free but I am not allowed to do so, Amazonautomatically sets the Monthly Price at $0.99 and includes wirelessdelivery via Amazon Whispernet, nevertheless, blog subscription startswith a 14-day free trial, and you can cancel at any time during the freetrial period. (I double checked the publisher's policy, Amazon willcharge 70% of subscription fee while bloggers receive the left 30%, that isto say, I earn only $0.297 per subscription.)

I don't expect people to subscribe my blog via Amazon Kindle as it istotally free on web, however, if you happen to use Kindle and wouldlike 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

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

Page 217: Quantitative Finance Collector

Binomial tree for American option

This is a follow up post of my previous entry Nine Ways to ImplementBinomial Tree Option Pricing because the latter covers European optiononly. Compared with pricing American option by Crank-Nicholsonfinite difference or American Options via least square Monte CarloSimulation, Binomial tree is the easiest to implement, what you need todo is just adding a MAX expression on every node of your tree.

Here is a paper on the implementation of binomial tree methods for thepricing of American option' value and Greeks, matlab codes can befound in the paper or separately here.Tags - binomial , american

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

Page 218: Quantitative Finance Collector

Eight rules a risk manager must remember

Unlike launching rocket, managing risk is a combination of art andscience that should incorporate a number of fundamental characteristics.This post is by no means another ex post analysis of the reasons ofcurrent credit crisis, instead, it is about eight simple while crucial rules arisk manager or risk analyst must keep in mind (print out and post it onyour 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, notmathematical 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 aconstantly changing strategy.8. Use common sense. It is better to be approximately right, than to beprecisely wrong.

Tags - risk , rule

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

Page 219: Quantitative Finance Collector

Nine Ways to Implement Binomial Tree Option Pricing

Binomial tree model is almost the most popular yet easiest way foroption pricing, for one thing, it can be used for most option classes inmarket, for example, European option, American option, Bermudaoption, etc.; for another, Binomial tree is straitforward to implement,several lines are enough for a vanilla option. Besides, it has a not-badconvergence speed, read my old post A Simple Trick to AvoidOscillation in Binomial Trees for improvement.

But how many ways are you able to implement binomial trees? here is apretty interesting paper on Nine Ways to Implement Binomial TreeOption Pricing, unlike Mr. espen haug's more than 30 languagescollection of Black Scholes model, these nine ways are all runnable inMatlab 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 binomialtree implemention is not such easy .

Enjoy.

Tags - binomial

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

Page 220: Quantitative Finance Collector

Wolfram Alpha Computational engine test feedback

No bigger news recently than Wolfram Alpha computational knowledgeengine is finally available today, on 10/03/2009 I briefly wrote a postabout what is wolfram alpha engine and what can it be used to serviceus, immediately after that, I applied to be a volunteer tester but got noreply. Anyway, it officially opens to public and we have chance to test itsmagic.

When talking about the pros and cons of Wolfram Alpha engine andGoogle, different people will offer different opinions, some people take itfor granted that Wolfram Alpha will be a big threat to Google andeventually replace Google, however, others hold that Wolfram Alpha isjust a computation calculator, and no matter how powerful it is, it is atmost a calculator with search function . Weighing up these twoarguments, I would say they complement each other, for example, beforeyou calculate an Europen option with Wolfram Alpha computationalengine, you need to google at least what an Europen option is.

In my previous post I joked about if Wolfram Alpha would return aresult 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 aform similar to the following graph

Input your parameter and select option types, the value of option youset, together with its Greeks and plots, are calculated as

So far so good, but it seems the products Wolfram Alpha covers arelimited, when I try to type Barrier option or Asian option, two simpleexotic options, it says "Wolfram|Alpha isn't sure what to do with yourinput." 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 anambitious, long-term project to make all systematic knowledgeimmediately computable by anyone.

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

Page 221: Quantitative Finance Collector

Play around at http://www.wolframalpha.com/.Tags - mathematica , wolfram

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

Page 222: Quantitative Finance Collector

Quant job hunting related sites

Since I have been looking for a quant-related job, I share several sites Ipersonally find useful:

Worldwide:http://www.efinancialcareers.comhttp://www.quantspot.comhttp://www.quantster.com/http://www.quantfinancejob.com/forum/http://www.wilmott.com/categories.cfm?catid=5http://www.monster.com

Germany & Switzerland:http://www.stepstone.de/home_fs.cfmhttp://www.jobpilot.de/http://www.monster.de/http://www.jobware.de/

Asia (excluding China):http://quantfinanceasia.com/index.phphttp://www.monster.com.sg/index.htmlhttp://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.htmlhttp://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

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

Page 223: Quantitative Finance Collector

Nonparametric High-Dimensional Time Series Analysis

Functional Gradient Descent (FGD) is a method of nonparametric timeseries analysis, useful in particular for estimating conditional mean,variances and covariances for very high-dimensional time series. FGD isa kind of hybrid of nonparametric statistical function estimation andnumerical optimization. In fact, the idea of FGD comes from the fact thatboosting 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 approximatethe first two conditional moment functions of a multivariate process. Anappealing feature of this expansion is that it is a nonlinear nonparametricmodel that directly nests the Gaussian diagonal VAR model, theGaussian GARCH model and the multivariate CCC-GARCH as simple,starting special cases. The FGD model is fitted using conventionalmaximum likelihood together with a cross-validation strategy thatdetermines the appropriate number of additive terms in the finalexpansions.

Interested ppl shall download the Splus codes and data athttp://www.raffonline.altervista.org/fgd/PS: to be honest, this is not the area i am family with at all, download atyour own riskTags - nonparametric

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

Page 224: Quantitative Finance Collector

The Long Vega Financial Engineering Tool

This tool can replicate and price any non path-dependent, continuouspiecewise linear payoff function on a stock. You can use the tool to priceand value option positions and simple structured products on a stock.

The Financial Engineering tool automatically replicates and prices agiven continuous piecewise linear payoff function. So far the tool canonly handle payoffs on a stock, where the payoff is denominated in thesame currency as the stock.

Calculate your option at http://longvega.com/FETool/feapplet.phpTags - calculator

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

Page 225: Quantitative Finance Collector

Free Financial Spreadsheets

Long ago I shared a Financial Model Excel Spreadsheets Library byThomas Ho, here is another long list of free financial excel spreadsheetsfor financial planning and analysis, although most of them are forcorporate finance practitioners in my view, there are some sampleswhich 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 ExcelBreakeven Analysis - Pricing and breakeven analysis for optimal pricingOption Trading Workbook - Educational toolkit for using Excel forOptionsEVA Model - Template worksheets for calculating Economic ValueAdded (EVA)...

Download at http://www.exinfm.com/free_spreadsheets.htmlTags - excel

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

Page 226: Quantitative Finance Collector

ATOM C++ option calculator

Another derivative calculator shared with you, ATOM - Advanced Toolfor 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 andnormal 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 unlimitedmaximum number of trials and time intervals in Monte carlosimulations;exotic option support: Asian average price, binary cash-or-nothing andasset-or-nothing, chooser option;

Download at http://www.atomproject.org/download.shtmlTags - calculator , option

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

Page 227: Quantitative Finance Collector

Twitter of the week

One good way to keep updated of my latest quantitative financecollector entries is to subscirbe by RSS or email at the righ panel "RSSfeed & subscribe" section, or if yor happen to use twitter, you can followmy twitter at http://twitter.com/a_biao, where i share my latest blogpost and also my life & feeling of job hunting. For example, my latest oneweek 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 fromtwitterfeed

# Interview is delayed to next week due to an unexpected meeting. Havea nice weekend and bank holiday9:03 AM May 1st from twidroid

# Exotic Options Calculator http://tinyurl.com/csw7g85:48 AM May 1stfrom 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 Apr30th 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 fromTwitterRide

# Volatility Forecasting and Trading http://tinyurl.com/cgffv24:47 AM

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

Page 228: Quantitative Finance Collector

Apr 28th from twitterfeed

# Why do only headhunters contact me? :)9:34 AM Apr 27th fromTwitterRide

# @cosbeta agree.7:34 AM Apr 27th from TwitterRide in reply to cosbeta

# Terrible monday morning. Coupled ewma makes me dizzy.6:39 AMApr 27th from TwitterRide

# think about my future over several bottles of beer8:36 AM Apr 26thfrom web

# prepare Tier 1 general5:56 AM Apr 26th from TwitterRide

# finally finished exam, henghenghahie10:57 AM Apr 25th fromTwitterRide

# got lost, finally am here. waiting outside of classroom.7:13 AM Apr25th from TwitterRide

# on the train to univ of greenwitch for visa english test, have to leave ukif fails. bless myself.Tags - twitter

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

Page 229: Quantitative Finance Collector

Stress test analysis

In recent months and years both practitioners and regulators haveembraced the idea of supplementing VaR estimates with stress-testing.Today The Federal Reserve is postponing the release of stress tests onthe biggest U.S. banks. Risk managers are beginning to place anemphasis and expend resources on developing more and better stresstest analysis.

Here is a good introductory paper aiming to give you a rough idea howto do stress test, to help demystify stress tests, and illustrate theirstrengths and weaknesses. The author use an Excel-based exercise withinstitution-by-institution data through stress testing for credit risk,interest rate and exchange rate risks, liquidity risk and contagion risk inthe design of stress testing scenarios. The purpose of the workbook is toillustrate basic stress tests (and related tools) that can be used to assessrisks in a small and relatively non-complex banking system, using arealistic (but fictional) example.

Paper is available at http://papers.ssrn.com/sol3/papers.cfm?abstract_id=973989&rec=1&srcabs=181931.

Tags - stress-testing

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

Page 230: Quantitative Finance Collector

Exotic Options Calculator

MG Soft Exotic Options Calculator is a freeware software to calculatethe option value and greeks of vanilla and exotic options, mainly usingMonte 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.aspxTags - calculator , exotic , option

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

Page 231: Quantitative Finance Collector

Finite Difference Method for EXCEL

Finite difference method has been repeatedly introduced to solve partialdifferential equation (PDE), for example, in past entries Crank-Nicholsonfinite difference solution of American option, Crank-Nicolson for aEuropean put, PSOR for American option, etc.

here is a Finite Difference Method for EXCEL addin which containsmacro to solve numerically partial differential equations (PDE) andordinary differential equations (ODE) with the Finite DifferencesMethod (FD). Seems it can only be applied for two dimensionalproblem, but should be enough for normal cases me meet.

Document and macro are at: http://digilander.libero.it/foxes/diffequ/fdsolver_review.htmTags - pde , finite-difference

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

Page 232: Quantitative Finance Collector

Parisian option pricer

Parisian option might sound unfamiliar to you, it is basically a barrieroption but becomes activated only after stock prices have spent a certaincontinuous, pre-decided time, called a window, above or below thebarrier. One of possible motivations for the existence of the Parisianoption, as stated in Haber, Schoenbucher, and Wilmott (1999) is: "...thereis a need to make the option more robust against short-term movementsof the share price..., in particular, it is far harder to effect the triggering ofthe barrier by manipulation of the underlying..."

Taking an up barrier Parisian option as an example, the barrier time tauis defined as the length of time the stock prices have been above thebarrier in the current excursiontau := t − sup {s <= t|S(s)<= L}with up barrier L, tau measures the difference between the current time tand the last time the stock price S below L, the call feature is activatedonly if tau>= D, with D being barrier window.

Interested reader shall download a Parisian option pricer athttp://paul.wilmott.com/software.cfm, where the authors priceParisian options by a finite-difference solution of a three-dimensionalpartial differential equation.Tags - parisian , option

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

Page 233: Quantitative Finance Collector

Volatility Forecasting and Trading

Excel spreadsheets of the course Volatility Forecasting and Tradingtaught by Professor Ser-Huang Poon at Manchester business school,mainly including:

Estimation and Forecasts :What is Volatility?Volatility estimationData frequency vs. reference periodRealised volatility, quadratic variation and bipower variationMarket microstructure issueVolatility Forecast and EvaluationError statisticsTest for significant differenceRegression based efficiency testsVolatility Time series modelsHistorical vol modelExponential smoothing, EWMA, Regime switchingARCHGARCH, IGARCH, EGARCH, GJR-GARCHShort vs. Long memory modelsStochastic Volatility ModelsExtension to Multivriate and JumpsVaR (Value at risk)...

more about pdf lectures and excel sample codes are at:http://www.personal.mbs.ac.uk/spoon/VolatilityForecastingAndTrading.htmhttp://www.personal.mbs.ac.uk/spoon/DataProgrammes.htmTags - volatility

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

Page 234: Quantitative Finance Collector

LAPACK++: High Performance Linear Algebra

LAPACK++: A Design Overview of Object-Oriented Extensions for HighPerformance Linear Algebra. LAPACK++ (Linear Algebra PACKage inC++) is a software library for numerical linear algebra that solvessystems of linear equations and eigenvalue problems on highperformance computer architectures.

Computational support is provided for supports various matrix classesfor vectors, non-symmetric matrices, SPD matrices, symmetric matrices,banded, triangular, and tridiagonal matrices; however, it does notinclude all of the capabilities of original f77 LAPACK. Emphasis is givento routines for solving linear systems consisting of non-symmetricmatrices, symmetric positive definite systems, and solving linear least-square systems.

Download at http://math.nist.gov/lapack++/Tags - algebra

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

Page 235: Quantitative Finance Collector

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 ifinterested.

The Innovative Forex Platform - Download for FREE!

More than investment news... In-depth Investing Analysis & TrustedOpinion. GET YOUR FREE TRIAL NOW!

Finance Career: Learn about finance firm profiles, finance jobs, financecareer message boards and more.

Join The Investing Social Network

TradingSolutions: Financial analysis and investment software thatcombines technical analysis with neural network and genetic algorithms.

Tags - source

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

Page 236: Quantitative Finance Collector

Download historical stock price

A friend of mine asks me how to download stock historical priceautomatically with Excel, here are two ways I have played:

1, using Excel 2003/2002 Add-in to download from MSN Money StockQuotes. This add-in for Microsoft Office Excel 2003 and Microsoft Excel2002 allows you to get dynamic stock quotes from the MSN Money Website. The add-in allows you to easily gather and study the stocks ofinterest 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. whereyou have to input start, end date and stock symbolSub GetData()

Dim DataSheet As WorksheetDim EndDate As DateDim StartDate As DateDim Symbol As StringDim qurl As StringDim nQuery As Name

Application.ScreenUpdating = FalseApplication.DisplayAlerts = FalseApplication.Calculation = xlCalculationManual

Set DataSheet = ActiveSheet

StartDate = DataSheet.Range("B1").ValueEndDate = DataSheet.Range("B2").ValueSymbol = DataSheet.Range("B3").ValueRange("C7").CurrentRegion.ClearContents

qurl = "http://ichart.yahoo.com/table.csv?s=" & Symbolqurl = qurl & "&a=" & Month(StartDate) - 1 & "&b=" &

Day(StartDate) & _"&c=" & Year(StartDate) & "&d=" & Month(EndDate) - 1 & "&e="

& _

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

Page 237: Quantitative Finance Collector

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.TextToColumnsDestination:=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 datafrom Yahoo! data servers.Tags - download , data

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

Page 238: Quantitative Finance Collector

Neural Network source code

Neural network matlab source code accompanying the book NeuralNetworks in Finance: Gaining Predictive Edge in the Market byprofessor Paul D. McNelis. This book has got wonderful review like“This book clarifies many of the mysteries of Neural Networks andrelated optimization techniques for researchers in both economics andfinance. It contains many practical examples backed up with computerprograms for readers to explore. I recommend it to anyone who wants tounderstand 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 atthe author's webpage: http://www.bnet.fordham.edu/mcnelis/recent.htm or try using TradingSolutions: Financial analysis andinvestment software that combines technical analysis with neuralnetwork and genetic algorithms.

Download TradingSolutions

Tags - neural-network

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

Page 239: Quantitative Finance Collector

Managing Diversification

Needless to say, diversification plays a pivotal role in investment, notonly for risk management, but for return generation. Attilio Meucci andhis colleagues have another wonderful paper on managingdiversification:QuotationWe propose a unified, fully general methodology to analyze and act ondiversification in any environment, including long-short trades inhighly correlated markets. First, we build the diversificationdistribution, i.e. the distribution of the uncorrelated bets in the portfoliothat are consistent with the portfolio constraints. Next, we summarizethe wealth of information provided by the diversification distributioninto one single diversification index, the effective number of bets, basedon the entropy of the diversification distribution. Then, we introducethe mean-diversification efficient frontier, a diversification approach toportfolio optimization. Finally, we describe how to perform mean-diversification optimization in practice in the presence of transaction andmarket impact costs, by only trading a few optimally chosen securities.

Click for codes http://www.mathworks.com/matlabcentral/fileexchange/23271Tags - diversification

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

Page 240: Quantitative Finance Collector

Forecast Volatility with Regime-Switching GARCH Models

Volatility estimation and prediction is crucial for risk management, forexample, the portfolio's Value at Risk (VaR) and expected shortfall arepartly decided by your volatility estimated, by partly I mean otherfactors, like dependence structure decide their values as well. GARCHmodel is one of the popular models for volatility estimation, you mightargue volatility regime should also be included to your model given thetotally different performance (hence different parameters) between lowvolatility regime and high volatility regime. Here is a good papercomparing a set of different standard GARCH models with a group ofMarkov Regime-Switching GARCH (MRS-GARCH) in terms of theirability to forecast the US stock market volatility at horizons that rangefrom one day to one month. To take into account the excessivepersistence usually found in GARCH models that implies too smoothand too high volatility forecasts, in the MRS-GARCH models allparameters switch between a low and a high volatility regime. Bothgaussian and fat-tailed conditional distributions for the residuals areassumed, and the degrees of freedom can also be state-dependent tocapture 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 parametersare unstable with the change of this number. no idea if it is my dataproblem.Tags - garch , regime

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

Page 241: Quantitative Finance Collector

Scholarship to apply for

ALMOST NOTHING POSITIVE, these are the most heard wordsrecently whenver I have a talk with my former colleagues andclassmates, 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 couldonly stay in my office till the end of June, which means I have to eitherlook for a new job, for instance, Finance Career: Learn about finance firmprofiles, finance jobs, finance career message boards and more. , or findanother way out, for instance, study for a MFE or PhD.

Staying at university for a while is no doubt a good way to decrease theimpact of credit crisis on you, since the job hunting competition getstough and tough, even a humble position requires "ideally an applicantwith PhD degree with 2 or more years work experience". How to choosea good MFE or PhD in QF program is natually a question everybody hasbefore application, here by good program I mean good placement withaccepted tuition fee (PS: I saw two weeks ago The University of Hawai’iShidler College Of Business is offering one year Master of FinancialEngineering program with scholarship available, search in Google if youare happy with the location). I happen to see such a rank, which mightbe suggestive to you, although this rank is too old,

After you are lucky enough to get an admission from one of these Topprograms, you might wonder how to arrange money for enrolling in agraduate school? Is money a real concern for you? Getting an admissionto a graduate is not an easy job but the big cheese is to collect money topay tuition. All students would be pleased to recognise that state andprivate lenders offer awards and scholarships for you. It doesn't matterwhether you have just finished undergraduate level or have beenworking for some years. The scholarships are available almost for all butstandards changes within financial institutions. Some lenders award onmerit basis with a proved track record in undergraduate school andsome grants are provided on the basis of the amount required for the fullgraduate school degree program. To apply for a scholarship is not thateasy as it looks to be. one source to search and apply for a scholarship Ihave ever tried is Find scholarships today at ScholarshipExperts.com -providing US & international students with customized scholarship info!

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

Page 242: Quantitative Finance Collector

, should you are interested, please take a try.

Good luck to all of you (including me) for job hunting or graduate schoolapplication. Enjoy life.

Tags - scholarship , mfe

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

Page 243: Quantitative Finance Collector

Salih Neftci (1947-2009) passed away

Bad news for all of us, Professor Neftci passed away yesterday inGeneva.

He is a such an important person to my quant-related life, his bookIntroduction to the Mathematics Of Financial Derivatives is so clearand easy to understand for anybody without any stochastic background,which helped me to work through my first master thesis at 2004; and hisanother book Principles of Financial Engineering is almost a must-owned one...

Silent Salute!

Tags - salih-neftci

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

Page 244: Quantitative Finance Collector

Binary Option Calculator on Gphone

Equity Option Calculator on Gphone was shared in this post. The authorhas published a binary option calculator for Gphone, as the author'swebpage says:

QuotationBinary Option Calculator is for advanced options traders. Calculateoption prices and Greeks for discontinuous payoff functions.

Can price any combination of:Calls or PutsEuropean or American styleCash-or-nothing or Asset-or-nothingOption value or Implied volatility.

To download, either search "Binary Option" on Gphone, or simply go tothe author's blog http://jwdevg1.blogspot.com/2009/04/binary-option-calculator-published.htmlTags - gphone , calculator , binary , option

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

Page 245: Quantitative Finance Collector

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 EfficientFrontier model, among others, is BL allows users to input certain viewsunder confidence level on assets, say, "I am 85% confident S&P 500 willhave 5% excess return", or "Bond index will outperform equity index by1.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 anoptimized portfolio, and this portfolio can be adjusted under given riskconstraint, Attilio Meucci, going further step, has a paper incorporatingnatually stress testing and scenerio analysis under Black Littermanframework, they propose a unified methodology to input non-linearviews from any number of users in fully general non-normal markets,and perform, among others, stress-testing, scenario analysis, and rankingallocation. Paper "Fully Flexible Views: Theory and Practice" and Matlabcodes 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 withouteven a detailed technical question, I suspect if it is really a Quant relatedjob position or the desire the company indeed needs a people. Anyway,fighting.Tags - black-litterman , stress-testing

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

Page 246: Quantitative Finance Collector

Play with cointegration

Cointegration is the foundation upon which pair trading (“statisticalarbitrage”) is built, basic cointegration function can be easily found inany popular statistical software package, for instance, Unit root andcointegration tests for time series data (urca) in R. Should you areinterested in playing with advanced cointegration test, go there, forinstance, estimating a threshold bi-variate VECM, and testing for thepresence 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 errorcorrection models," with Byeongseon Seo, Journal of Econometrics(2002).

Tags - cointegration

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

Page 247: Quantitative Finance Collector

Estimation of Structured t-Copulas

A collection of codes on Copula estimation and simulation is shownhere, where you can find parameter estimation for t-copula, Grouped-tcopula, asymmetric copula, etc., another simple recursive routine toestimate by maximum likelihood the correlation matrix and the degreesof freedom for structured t-copula is shared athttp://www.mathworks.com/matlabcentral/fileexchange/19751, theauthors impose extra structure on the correlation matrix in theestimation process, where the number of variables is large as comparedto the number of observations.

The paper "Estimation of Structured t-Copulas" is available at:http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1126401, morepaper and codes are at the author's homepage:http://www.symmys.com/AttilioMeucci/Home/Home.htmlTags - copula

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

Page 248: Quantitative Finance Collector

GMM and Empirical Likelihood

Generalized method of moments (GMM) estimation has got more andmore popularity for linear and non-linear models with applications ineconomics and finance. GMM estimation was formalized by Hansen(1982), and since has become one of the most widely used methods ofestimation for models in economics and finance. Unlike maximumlikelihood estimation (MLE), GMM does not require completeknowledge of the distribution of the data. Only specified momentsderived from an underlying model are needed for GMM estimator. Insome cases in which the distribution of the data is known, MLE can becomputationally very burdensome whereas GMM can becomputationally very easy. The log-normal stochastic volatility model isone example. In models for which there are more moment conditionsthan model parameters, GMM estimation provides a straightforwardway to test the specification of the proposed model. This is an importantfeature that is unique to GMM estimator.

Download Programs for GMM and Empirical Likelihood athttp://www.ssc.wisc.edu/~bhansen/progs/progs_gmm.html

Finally, Happy easter day to all of you, while I will have to stay at homepreparing interview

Tags - gmm

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

Page 249: Quantitative Finance Collector

Nonparametric Density Estimation

A simple, straightforward way to estimate density nonparametrically iskernel density estimator, for instance, in R a built-in function density() isfor this, with different kernel choices "gaussian", "epanechnikov","rectangular", "triangular", "biweight", "cosine", and "optcosine". Shouldyou are unhappy with this function and eager for an extention, take alook 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

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

Page 250: Quantitative Finance Collector

Newey West estimator

This function returns the Newey-West estimator of the asymptoticvariance matrix. What is Newey West? it was proposed by the authorWhitney K. Newey and Kenneth D. West in their paper "A simple,positive semi-definite, heteroskedasticity and autocorrelation consistentcovariance matrix" at 1987. It rests on considerations of the so-called“frequency domain representation” of the Ft’s and also of a number ofnotions associated with nonparametric estimation procedures.

One possible application of Newey West estimator is for long runvariance covariance calculation; another might be for the improvementof OLS regression when the variables have heteroskedasticity andautocorrelation.

Download at http://www.homepages.ucl.ac.uk/~uctprgi/Matlabcode.htmTags - covariance

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

Page 251: Quantitative Finance Collector

Allan variance

Long term memory has frequently been observed in time series.Statistical theory for long term memory stochastic processes is largelydifferent from the standard time series analysis, which assumes shortterm memory. The Allen variance is a particular measure of variabilitydeveloped 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 alsoknown as the two-sample variance. It is defined as one half of the timeaverage of the squares of the differences between successive readings ofthe 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 longterm variance by Allan variance? any idea?

Allan variance Matlab code is easy to write and can also be downloadedat: http://www.alamath.com/index.php?option=com_content&task=view&id=19&Itemid=31

Tags - variance

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

Page 252: Quantitative Finance Collector

Black Scholes on excel

Excel Add In (Visual Basic) for Black Scholes, Numerical Integrationand Probability Density Estimation

This is a MS Excel Add In (with Visual Basic Source Code) for severalseparated 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 OptionGreeks

Many of these functions can also be used in standalone Visual Basicapplications.

Read Installation and Use Instructions. Download Excel Add-In andVisual Basic source code as a zip file or as tar.gz file athttp://www.iimahd.ernet.in/~jrvarma/software.phpTags - black scholes

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

Page 253: Quantitative Finance Collector

Financial Engineering Toolbox

A toolbox accompanying the book "Financial Engineering: DerivativesPricing, Computer Simulations, Market Statistics", (couldn't find thebook on Amazon, surprisingly), which provides a comprehensiveoverview of financial markets and a cutting-edge discussion ofmathematical and numerical methods employed in financialengineering. The primary topics covered include: in-depth reporting ofderivatives' pricing models, constructions and practical application ofexotic options, and market statistics with a comprehensive review oftime series models.

Selected chapters:1. Introduction2. Financial markets3. Securities4. Basic derivatives (forwards, futures, swaps and options)5. Financial mathematics of discrete models6. Financial mathematics of continuous models7. Term structure models8. Construction and pricing of exotic derivatives9. Market statistics10. Alternative models

Downloading at: http://www.im.pwr.wroc.pl/~hugo/stronaHSC/Podstrony/ksiazki/if_gb.htmlTags - toolbox

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

Page 254: Quantitative Finance Collector

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 oftension. Most of those tensions stem from bills. From student loans toschoolbooks, college life costs expensive. A lot of pupils apply for forstudent credit cards at school.

Student credit card is given to any member of the academicorganizations disregarding whether he or she is part time or full time,undergraduate or graduate student, international students who areexchanging, working or learning in the United States, university staffseither full time or part time faculty and executives who are 16 year oldage and above. For those students who are less than 18 years of ageaccepted from the parents or the guardian is compulsory.

Applying for a student credit card is suggested because it can helppupils in making their accredit history which might be useful in thefuture particularly in finding loans like automobile, real estate or evenimmediate payment loans. Most of international students and scholarsdiscover it actually hard to receive a credit card as they lack a credit cardhistory. For them to make a credit card history they ought to have acredit card or at the least consume a history in paying back debts ofwhatever case. It is indeed a frustrative position specially if you areseriously in need of financial help.

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

Page 255: Quantitative Finance Collector

Shit happens everywhere

Today is the first day of G20 summit, is also the strongest protest in thelast fews days, which will last at least till tomorrow. Company suggestsus to have dress down to avoid unnecessary conflict with protestors, (forthose of you who have no idea what's happened or how seriou thisprotest is in London recently, what I can tell you is the slogan of aprotestor group being "Burn a banker"), I do enjoy dress down, wearingjeans, t-shirt and looking relaxed (although not).

Protest itself is fair enough and welcomed, everyone has the right tospeak out his or her own views, this is a kind of freedom we shouldcherish, but freedom does not mean you can do anything you want. Ifully understand the feeling of losing job (I myself will be one of themsoon), 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, shithappens everywhere.

there is still "hero"

more pics can be found http://www.flickr.com/search/?q=london+protest&s=rec

Tags - protest

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

Page 256: Quantitative Finance Collector

MFE toolbox

Oxford MFE package was shared there, here is a new MFE Matlabtoolbox accompanying the book "Modeling and Forecasting ElectricityLoads and Prices: A Statistical Approach", which is grouped into thefollowing 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 datadecomposition.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.htmlMore 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

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

Page 257: Quantitative Finance Collector

Financial data download

Financial data is the center of quantitative finance research,undoubtedly. Here is a list of free financial data for downloading, formore 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 theworld. SEE MORE2. Historical FX Rates: http://oanda.com/convert/fxhistory3. Historical Stock Prices: http://finance.yahoo.com/q/hp?s=yhoo4. Recent LIBOR rates: BBA - British Bankers' Association - BBA LIBOR5. Some Implied Volatilities: http://www.ivolatility.com6. Delayed Commodities: http://www.liffe-commodities.com.7. US Fundamentals: http://www.sec.gov

Tags - data

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

Page 258: Quantitative Finance Collector

Independent Components Analysis

The FastICA package is a free (GPL) MATLAB program that implementsthe fast independent component analysis.

Independent component analysis (ICA) or blind source separation is amodern signal processing technique to multivariate financial time seriessuch as a portfolio of stocks to multivariate financial time series such as aportfolio of stocks. The key idea of ICA is to linearly map the observedmultivariate time series into a new space of statistically independentcomponents (ICs). This can be viewed as a factorization of the portfoliosince joint probabilities become simple products in the coordinate systemof the ICs.

The major difference between Independent component analysis andmore familiar principal component analysis (PCA) is in the type ofcomponents obtained. The goal of PCA is to obtain principal componentswhich are uncorrelated. Moreover, PCA gives projections of the data inthe direction of the maximum variance. The principal components (PCs)are ordered in terms of their variances: the first PC defines the directionthat captures the maximum variance possible, the second PC defines (inthe remaining orthogonal subspace) the direction of maximum variance,and so forth. In ICA however, the aim is to obtain statisticallyindependent components. What's more, PCA algorithms use only secondorder statistical information (variance dominates). On the other hand,ICA algorithms may use higher order2 statistical information forseparating the signals.

To download FastICA and more about the book IndependentComponent Analysis check http://www.cis.hut.fi/projects/ica/fastica/, the book can be bought at Amazon through: IndependentComponent AnalysisTags - multivariate

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

Page 259: Quantitative Finance Collector

Equity option calculator on Gphone

I bought a Gphone several months ago, its main attraction to me is Gmaileverywhere as long as there is signal since I can't use Gmail box with myPC at company (my boss won't read my blog). Another shining point ofGphone is its Android platform and Market, where people can publishapplications on entertainment, finance, news, weather, etc.

Yesterday I downloaded a free application named Equity optioncalculator, a simple equity options pricer for European style no dividendcalls and puts using your own inputs under Black Scholes modelframework. Alternatively enter a ticker and let the market data calibratorfill 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 derivativecalculator wherever as you go, isn't it? the code is written in Java that Iam not familiar with, but have downloaded The Android SDK fordevelopers to see if I am able to build an application covering moreoptions like Matlab-GUI equity derivative calculator does.

if you happen to own a Gphone, this option pricer can be found bytyping "equity option calculator" in Market. Have fun.

Publisher's blog: http://jwdevg1.blogspot.com/Tags - calculator , gphone , option

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

Page 260: Quantitative Finance Collector

Kernel principal component analysis

EasyPCA is a small educational program intended to help to understandhow the Principal Component Analysis (PCA) algorithm works. It hasbeen coded in a very modular way in order to make it easy tounderstand the code.

PCA is a useful statistical technique that has found application in fieldssuch as face recognition and image compression, and is a commontechnique for finding patterns in data of high dimension.

For more detail please check http://transp-or2.epfl.ch/pagesPerso/javierFiles/software.phpTags - pca

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

Page 261: Quantitative Finance Collector

Create your own websites

This is a review of the week.

You are perhaps a modest enterprise owner who already holds awebsite, You might be a SOHO work-at-home self-employee who wouldlike to make additional revenue for yourself. You may be an cyberspaceseller who prefer to bring affiliate or marketing to the advanced level.Disregarding what you wish to do on internet you're likely becoming toneed to understand how to make a website that operates.

While it refers to constructing websites there's many confusion about thebest method to do. Nevertheless, it is crucial to choose what yourpurpose 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 whetheror 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 youproduce a personal website to share experiance or make friends online.

However, if you prefer to create website that looks appealing or moreprofessional, you will have to plan a little more carefully. BlueVoda is adrag & drop Web site builder that enables a user with almost noexperience to build a fantastic Web site. No HTML, PHP or any othercoding knowledge is demanded. From a simple homepage to a fancyWEB2.0, you can also own one with few simple steps.

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

Page 262: Quantitative Finance Collector

VIX calculation

CBOE Volatility Index, VIX, was originally designed to measure themarket’s expectation of 30-day volatility implied by at-the-money S&P100 Index (OEX) option prices. Now VIX is used to reflect a new way tomeasure expected volatility, one that continues to be widely used byfinancial theorists, risk managers and volatility traders alike. The newVIX 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 ofSPX puts and calls over a wide range of strike prices. By supplying ascript for replicating volatility exposure with a portfolio of SPX options,this new methodology transformed VIX from an abstract concept into apractical 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 thesquare root of that value and multiply by 100 to get VIX.

Matlab code: http://docs.google.com/Doc?id=ddb2j6dw_12fjk57bfxTags - volatility , vix

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

Page 263: Quantitative Finance Collector

Top Quant codes collection you shouldnt miss

To search and backup easier, I make a PDF file which includes so farmost of entries of the Quantitative finance collector blog. ThisQuantitative finance codes list is partly what I have collected during myfinancial engineering learning journey. Most of the entries were writtenwhen I was at university, apparently many codes can not be useddirectly for a certain purpose, we can, certainly, learn the way the codersapplied.

Although I try best to check each file before recommendation,downloading and using are at your own risk. Should you are interestedand would like to track my latest collection, please visit my blog orfollow 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 wantto post somewhere, thank you.

Downloading the PDF file at: http://www.mathfinance.cn/attachment/QuantitativeFinanceCollector.pdf (right click and save as)

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

Page 264: Quantitative Finance Collector

Option pricing with excel

A nice paper on step-by-step option pricing with excel, VBA codes areincluded in the paper as well.

The authors first briefly review the principles of pricing by no arbitragein a binomial tree, and show how this can be implemented in Excel; thenmove to continuous-time model - Black scholes pricing model; after ashort discussion on the parameter estimation issues, they turn to twonumerical methods for pricing, which are Monte Carlo simulation andFinite difference for Partial differential equation (PDE); at last, optionhedging is introduced, advantages and disadvantages of spreadsheets ingeneral and Excel in particular are analyzed shortly.

Download paper "Option pricing with the Excel" athttp://www.math.ku.dk/~rolf/REV.excelpaper.pdfTags - option , excel

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

Page 265: Quantitative Finance Collector

Cheap web hosting solution

This is a short review of web hosting.

Many folks would like to own Web sites nowdays, however they concernabout the cost. Purchasing the real domain name is really cheap, around10 US dolloars you can get a fancy dot com name, therefore it's notactually a problem. What's crucial, although, is the hosting. it ismeaningless to have a domain name should you do not go forward andmake a site on it, begin appealing subscribers and customers, and dosomething to earn revenue. Even if you are merely blogging, you maynot prefer to utilize the free services. If you are not blogging and you'reindeed marketing a product or service, you truly can not bear freehosting. You'll have to own a Web site that allows more than what youare able to do on free services, most probably. There are dozens of waysto acquire that hosting, though, and the best way for most people is touse the Web Hosting service that accompanies the host name. Numerouscorporations who sell domain names feature these hosting packages, andthey aren't really expensive. For instance, 4 Cheap Web Hosting is aguide 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.

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

Page 266: Quantitative Finance Collector

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 asubstantial improvement in robustness over the original UCSD GARCHcode, although in its current form it only contains univariate routines.

Contents include:1 Stationary Time Series 51.1 ARMA Simulation1.1.1 Simulation: armaxfilter_simulate . . . . . . . . . . . . . . . . . . . . . . . . . . 51.2 ARMA Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.2.1 Estimation: armaxfilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.2.2 Residual Plotting: tsresidualplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.2.3 Characteristic Roots: armaroots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171.2.4 Information Criteria: aicsbic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.3 ARMA Forecasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211.3.1 Forecasting: arma_forecaster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211.4 Sample autocorrelation and partial autocorrelation . . . . . . . . . . . . . . . .. . . . . . . 231.4.1 Sample Autocorrelations: sacf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231.4.2 Sample Partial Autocorrelations: spacf . . . . . . . . . . . . . . . . . . . . . . . . . .251.5 Theoretical autocorrelation and partial autocorrelation . . . . . . . . . . . . .. . . . . . . . 271.5.1 ARMA Autocorrelations: acf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271.5.2 ARMA Partial Autocorrelations: pacf . . . . . . . . . . . . . . . . . . . . . . . . . . .291.6 Testing for serial correlation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .311.6.1 Ljung-BoxQ Statistic: ljungbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311.6.2 LM Serial Correlation Test: lmtest1 . . . . . . . . . . . . . . . . . . . . . . . . . . . .332 Nonstationary Time Series 372.1 Unit Root Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372.1.1 Augmented Dickey-Fuller testing: augdf . . . . . . . . . . . . . . . . . . . . . . . .. 372.1.2 Augmented Dickey-Fuller testing with automated lag selection:augdfautolag . . . . 403 Vector Autoregressions 43

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

Page 267: Quantitative Finance Collector

3.1 Stationary Vector Autoregression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . 433.1.1 Vector Autoregression estimation: vectorar . . . . . . . . . . . . . . . . . . . . . .. 433.1.2 Granger Causality Testing: grangercause . . . . . . . . . . . . . . . . . . . . . . . .503.1.3 Impulse Response function calculation: impulseresponse . . . . . . . . . .. . . . 534 Volatility Modeling 574.1 GARCH Model Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .574.1.1 ARCH/GARCH/GJR-GARCH/TARCH/AVGARCH/ZARCHEstimation: tarch . . . . . . 574.1.2 Some behind the scenes choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .594.1.3 EGARCH Estimation: egarch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634.1.4 APARCH Estimation: aparch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .665 Density Estimation 715.1 Kernel Density Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71

Code and documention are available at:http://www.kevinsheppard.com/wiki/MFE_ToolboxTags - garch

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

Page 268: Quantitative Finance Collector

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 Financialservices sector. The figure looks not bad at all, given the terrible marketof 2008. I have to say for many cases the quant salary does not mean theexact number the quant get, especially in China, other income exceedingsalary is pretty possible.

I also had a survey for quant salary in mainland, China, results areshown below (basic salary + bonus, about 1~3 years work experience inChinese Yuan):number percentage of voters50K ~ 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 mastergraduates is about 60K, quant salary is exicting, isn't it?Tags - salary

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

Page 269: Quantitative Finance Collector

Video lectures

Just share with you guys two free online video lecture sites I haverecently used, both time- and cost- saving, isn't it? enjoy.

http://videolectures.net/Top/Computer_Science/Machine_Learning/

http://videolectures.net/Tags - video

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

Page 270: Quantitative Finance Collector

Asymmetric copula analysis

http://www.mathfinance.cn/Grouped-T-copula-simulation-estimation/shared a sample code for grouped-t copula simulation, further, severalcopula estimation and simulation package can be found. But, most of thecase we talk about an exchangeble copula due to its relatively easier toexplain, however, it has limited applications especially in the area ofcredit risk, or derivative markets where asymmetric dependence plays acrutial role. For example, a desire to maintain the competitiveness ofJapanese exports to the United States. with German exports to the UnitedStates. would lead the Bank of Japan to intervene to ensure a matchingdepreciation of the yen against the dollar whenever the Deutsche mark(DM) depreciated against the U.S. dollar. Such rebalancing behaviorwould also lead to greater dependence during depreciations of the DMand yen against the dollar than during appreciations. It is certainlynatural to enquire whether there are extensions that are not rigidlyexchangeble.

A scatter plot of the return of S&P 500 index and that of its impliedvolatility difference series is shown above, clearly the dependence isstronger in left-up corner than right-down corner.

Interested reader shall refer to the following papers and Matlab codes fordetail:Modelling Asymmetric Exchange Rate Dependence, 2006, InternationalEconomic Review, 47(2), 527-556.Paper (PDF), Abstract (HTML), Slides June01 (PDF), Code (MATLAB)

-- This paper was previously circulated as “Modelling Time-VaryingExchange Rate Dependence Using the Conditional Copula”, Universityof California, San Diego, Discussion Paper 01-09.-- The Joe-Clayton and symmetrised Joe-Clayton copula densityfunctions can be found here (PDF). Matlab functions for these can befound here.http://econ.duke.edu/~ap172/research.html

Tags - copula , asymmetric

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

Page 271: Quantitative Finance Collector

c++ for finance

A c++ class list for finance, specifically, a derivative calculator sourcecode, is available, including:

american_option_approximation: uses the Black Scholes formulae forEuropean options, to approximate the values of American options.

american_option_fudge: approximates the value of American Options asthe value of the corresponding European option, plus the addition of afudge 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 tothe secant algorithm /// on every other iteration

european_option_pair : Black Scholes option pricing formulae for putsand calls

...

Click for more and downloading http://acumenconsultinginc.net/TechNotes/public_options/html/annotated.htmlTags - option , c++

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

Page 272: Quantitative Finance Collector

WolframAlpha computational knowledge engine

You might have no idea who is Wolfram, but you might knowMathematica more or less, right, Wolfram is the computer scientist whohas developed Mathematica. A recent post of his blog shows his anothermore ambitious project named Wolfram|Alpha will be available in May,2009.

What is Wolfram|Alpha? its own logo says WolframAlpha is acomputational knowledge engine, It doesn't simply return results thatcontain (match) the keywords you search, like Google, Yahoo, or MSNlive does, and it isn't only a giant database of knowledge, like theWikipedia; Instead, Wolfram Alpha indeed computes the answers to thequestion 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 wecan'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 tomaturity 1 year, interest rate 3%, and 25% annual volatility"? LOL, I amtoo demanding.

Anyway, should you be interested, please check it at:http://www.wolframalpha.com/

Tags - mathematica , wolfram

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

Page 273: Quantitative Finance Collector

Maximum likelihood estimation of CIR interest rate

QuotationThe square root diffusion process is widely used for modeling interestratesbehaviour. It is an underlying process of the well-known Cox-Ingersoll-Rossterm structure model (1985). We investigate maximum likelihoodestimationof the square root process (CIR process) for interest rate time series. TheMATLAB implementation of the estimation routine is provided andtested onthe 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 beenundertaken, we moved all codes collection posts under category Quantcode, which makes browse easier and more convenient (hopefully). Inaddition, we added Quant newssection where selected news andresources, focusing on Asian Quant markets, will be published. Hopethis change won't bring trouble to you, thanks.Tags - cox ingersoll ross

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

Page 274: Quantitative Finance Collector

Compound option pricing

A compound option is simply an option on an option. The exercisepayoff of a compound option involves the value of another option. Acompound option then has two expiration dates and two strike prices.Take the example of a European style call on a call. On the firstexpiration date T1, the holder has the right to buy a new call using thestrike price X1. The new call has expiration date T2 and strike price X2.

The pricing of many other derivative instruments can be modeled ascompound options. By visualizing the underlying stock as an option onthe firm value, an option on stock of a levered firm that expires earlierthan the maturity date of the debt issued by thefirm can be regarded as a compound option on the firm value (Geske,1979). On the expiration of the option (the first expiration date of thecompound option), the holder chooses to acquire the stock or otherwise.The decision depends on whether the stock as a call on the firm value ismore valuable than the strike price.

Attached is a sample matlab code computing the value of a compoundcall option with the Black-Scholes pricing model using Geske's analyticformulas.

Click to downloadTags - compound , option

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

Page 275: Quantitative Finance Collector

Credit card bailout

A review of credit card bailout.

It appears as if day-to-day at present that we hear about a governmentbought at bailout of additional major company. Numerous smallercommercial enterprise, as well as individual people, are left enquiringwhere is their bailout from the dishonest loaning practices of thedepository financial institution and credit card corporations.

In recent years, consumers have been promoted to Apply Credit Card fordaily purchases, including groceries, fast food meals, and even themorning cup of coffee en route to office. All of these purchases, inaddition the interest and fees appended, have only ramped up a hugepile of debt for the ordinary cardholder.

This is not much unlike the debt built up by companies, who now beartheir hand out, calling for for help. And the government appears veryamenable to offer that help, at the long-run expense of the Americantaxpayer.

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 matterof fact, there is really no money needed in this bailout. Through debtelimination, a person can lawfully and entirely discharge 100% of theirdebts from credit cards and consumer loan*. Totally without afresh loan,subsidy, or government takeover.Tags - credit , bailout

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

Page 276: Quantitative Finance Collector

CDS Standard Model

JP. Morgan has release its CDS pricing and analysis model code!

QuotationThe ISDA CDS Standard ModelThe ISDA CDS Standard Model is a source code for CDS calculationsand can be downloaded freely through this website. The source code iscopyright of ISDA and available under an Open Source license.

BackgroundAs the CDS market evolves to trade single name contracts with a fixedcoupon and upfront payment, it is critical for CDS investors to match theupfront payment amounts and to be able to translate upfront quotationsto spread quotations and vice versa in a standardized manner.Implementing the ISDA CDS Standard Model and using the agreedstandard input parameters will allow CDS market participants to tie outcalculations and thus improve consistency and reduce operationaldifferences downstream.

Besides the code for CDS, a Yield Curve Specifications PDF file abouthow the yield curve is constructed and calculated is also available at thewebpage, enjoy!

http://www.cdsmodel.com/Tags - cds , credit

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

Page 277: Quantitative Finance Collector

Modelling the implied volatility surface

The volatility surface implied by option prices presents a structure thatchanges overtime. The aim of this paper is to present a framework to model theimplied volatilityof the FTSE options in real time, and to present a prototype applicationthatimplements this framework. The authors adapt the parametric modelspresented in Dumas etal (1998) to estimate the surfaces across moneyness instead of acrossstrikes, theydiscuss how this framework can be used in applications of option pricingand riskmanagement.

Paper and attached matlab/VB/mathematica codes:http://www.amadeo.name/working_papers/volatility_surface_may04.pdfTags - volatility , surface , smile

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

Page 278: Quantitative Finance Collector

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 anautomatic testing tool doing these boring, repetitive procedures for you?YES. Automatic Testing is a great tool to increase productivity and savetime. It helps you catch bugs early by allowing frequent retesting of yourcode as you develop. This prevents code "regressing" in the sense ofreintroducing previously identified and fixed bugs in later updates toyour code.

Automatic Testing is made simple and quick through the use of unittesting frameworks, the most popular amongst these is xUnit which hasimplementations in most modern programming languages. For Matlabwe have a version of mlUnit available for your use. In python, pyUnit ispart of the standard library and is available as a standard packageunittest. 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 willcatch incompatibilities early.

Sounds nice? Downloading packages at:http://mlunit.dohmke.de/Main_Page for Matlabhttp://docs.python.org/library/unittest.html for Pythonhttp://cran.r-project.org/web/packages/RUnit/index.html for R.

Tags - code , test

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

Page 279: Quantitative Finance Collector

Managing MATLAB Projects

Whenever I opened my m files with Matlab, I was tired of looking forthem one by one; the situation became worse for a big project withdozens of small m files. You might argue what we can do is to save allfiles of one project at a separated directory, well, that’s what I did, butwith the expanding of project, sub-projects are created and some files areinter-correlated among those sub-projects. It therefore becomesunrealistic to separate those files any more. Is there a projectmanagement tool like Visual C++ does for cpp/hpp? mlProj is one goodapplication 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 isopened. The projects are shown as a tree, which provides simple accessto 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_PageTags - matlab

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

Page 280: Quantitative Finance Collector

wavelet analysis

WaveLab is a collection of Matlab functions to implement a variety ofalgorithms related to wavelet analysis. A partial list of the techniquesmade 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.htmlTags - wavelet

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

Page 281: Quantitative Finance Collector

Historical Volatility Estimation

Dozens of ways to calculate historical volatility, let alone volatility (Imean, implied volatility, stochastic volatility, for instance.). Here is theMATLAB code that one could use to estimate historical volatility usingdifferent methods

Historical Close-to-Close volatilityHistorical High Low Parkinson VolatilityHistorical Garman Klass VolatilityHistorical Garman Klass Volatility modified by Yang and ZhangHistorical Roger and Satchell VolatilityHistorical Yang and Zhang VolatilityAverage of all the historical volatilities calculated above

Enjoy. http://tradingwithmatlab.blogspot.com/2008/06/estimate-historical-volatility.htmlTags - volatility , stochastic

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

Page 282: Quantitative Finance Collector

Several matlab packages

Several matlab packages to download, including:

Complexity - for estimating various temporal and spatial signalcomplexitiesDenoising - for removing noise from signalsKalman filter - for Kalman filterIndependent Components - for ICA based on `accelerated' covariantalgorithm (natural gradient)Gaussian mixture models - for analysis of Gaussian mixture models fordata set clustering etc.MinEnt clustering - for minimum-entropy (maximum certainty)partitioningExtreme 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

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

Page 283: Quantitative Finance Collector

Generalized Linear Models in Matlab

glmlab is a free MATLAB toolbox for analysing generalized linearmodels. glmlab can fit all types of generalized linear models, including(among others):multiple regression;log-linear models;logistic regression; andweighted regression.

glmlab includes the following error distributions:normal (Gaussian);gamma;inverse Gaussian;Poisson; andbinomial.You can also specify your own error distributions with just a little bit ofMATLAB programming.

http://www.sci.usq.edu.au/staff/dunn/glmlab/glmlab.html

Tags - regression

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

Page 284: Quantitative Finance Collector

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 thecointegration testsintroduced by Johansen to include exogenous I(1) variables in a VECMmodel. It reiteratesthe proofs for their central test statistics and presents them in a lessdense format: FollowingPesaran et al. (2000), this paper focuses on the derivation of thecorresponding cointegrating ranktests, by first introducing a VAR model, subsequently deriving thelikelihood for the cointegrationparameters and, finally, the test statistics and their asymptoticdistributions. The final sectionintroduces tests on whether the required exogeneity restrictions hold. Inaddition, this paper isconcerned with implementing the mentioned test statistics in a Matlabroutine.

Paper and Matlab code: http://www.zeugner.eu/arbeiten/tafel.phpTags - cointegration

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

Page 285: Quantitative Finance Collector

Pattern Recognition Package

Pattern recognition is a sub-topic of machine learning. It is "the act oftaking in raw data and taking an action based on the category of thedata".Most research in pattern recognition is about methods forsupervised learning and unsupervised learning. another black-box asneural network.

Pattern recognition aims to classify data (patterns) based either on apriori knowledge or on statistical information extracted from thepatterns. The patterns to be classified are usually groups ofmeasurements or observations, defining points in an appropriatemultidimensional space. This is in contrast to pattern matching, wherethe pattern is rigidly specified.

PRTools supplies about 200 user routines for traditional statisticalpattern recognition tasks. It includes procedures for data generation,training classifiers, combining classifiers, features selection, linear andnon-linear feature extraction, density estimation, cluster analysis,evaluation and visualisation. It is intended to aid students andresearchers in designing and evaluating new algorithms and in buildingprototypes.

Matlab package and manual are available at http://www.prtools.org/download.htmlTags - pattern

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

Page 286: Quantitative Finance Collector

Quant Trading Strategy Demo

A Quant Trading Strategy Demo, including:CPPI (Constant Proportional Portfolio Insurance), OBPI (Option BasedPortfolio Insurance), DPE (Dynamic Protected Envelope) and DPAA(DynamicProtected Asset Allocation)

Download at:

http://www.quantcode.com/modules/mydownloads/visitwad.php?cid=9&lid=508The underlying risky asset (can be equity or fixed income instruments)aresimulated via general innovation processes with specification ofstochasticvolatility.

Note:

1. This is purely quant asset allocation strategy, it can be combinedwith factor and fundamental analysis for more specific low-frequencytradingstrategies. Or it can be combined with statistical data mining techniquesfor high-frequency trading strategies.

2. Explainations and some related VBA code will be published in:

http://www.weizhenstanford.com/blogTags - strategy

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

Page 287: Quantitative Finance Collector

Feedforward neural networks package

Some call it "probably the best feedforward neural networks package", Ican't gurantee it, however, as I know almost nothing about neuralnetwork. Please help me write a review if you can, cheers.

The Netlab toolbox is designed to provide the central tools necessary forthe simulation of theoretically well founded neural network algorithmsand related models for use in teaching, research and applicationsdevelopment.

It consists of a toolbox of Matlab® functions and scripts based on theapproach and techniques described in Neural Networks for PatternRecognition 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

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

Page 288: Quantitative Finance Collector

Efficient maximum-likelihood estimation

% Fastfit Toolbox. Efficient maximum-likelihood estimation usinggeneralized% 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

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

Page 289: Quantitative Finance Collector

Maximum likelihood estimation in R

Maximum likelihood estimation can be implemented like Quasi-maximum likelihood in Matlab, You can also write an R function whichcomputes out the likelihood function. As always in R, this can be done inseveral different ways.

One issue is that of restrictions upon parameters. When the searchalgorithm is running, it may stumble upon nonsensical values - such as asigma below 0 - and you do need to think about this. One traditionalway to deal with this is to "transform the parameter space". As anexample, for all positive values of sigma, log(sigma) ranges from -infinity to +infinity. So it's safe to do an unconstrained search usinglog(sigma) as the free parameter.

For detail about methodology and sample codes seehttp://www.mayin.org/ajayshah/KB/R/documents/mle/mle.html.Tags - mle

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

Page 290: Quantitative Finance Collector

Merry Christmas

Merry Christmas to you all and happy 2009 new year.

Blog will take several days off.

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

Page 291: Quantitative Finance Collector

Newmat C++ matrix library

This C++ library is intended for scientists and engineers who need tomanipulate a variety of types of matrices using standard matrixoperations. Emphasis is on the kind of operations needed in statisticalcalculations 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 betweentypes, submatrix, determinant, Cholesky decomposition, QRtriangularisation, singular value decomposition, eigenvalues of asymmetric matrix, sorting, fast Fourier and trig. transforms, printing andan interface with Numerical Recipes in C.

Introduction and package downloading: http://www.robertnz.net/nm_intro.htmhttp://www.robertnz.net/download.htmlTags - matrix , library

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

Page 292: Quantitative Finance Collector

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 α areindicated 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 γ=1and location δ=0. Note the discontinuity in the standard1-parameterization near alpha=1.

download stable distribution software at http://www.mathestate.com/tools/Financial/sw/Software.htmlTags - stable , distribution

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

Page 293: Quantitative Finance Collector

Extra moments measure

The following functions are intended to replicate calculations for takinghigher moments of hedge fund returns into account in analyzingparticular investments. Most of the formulae are taken from variousEDHEC 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.RTags - moment , portfolio

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

Page 294: Quantitative Finance Collector

Implementation of Skew Normal/Student t distributions

SKEW is a Gauss library for computing pdf, cdf and inverse of the cdfand simulating random numbers for the SN, ST, MSN and MSTdistribution functions described in Azzalini, A. and Capitanio A.[2003],Distributions generated by perturbation of symmetry with emphasis ona multivariate skew t distribution, JRSS B, 65, 367-389.

Check A Gauss implementation of Skew Normal/Student distributionsat http://www.thierry-roncalli.com/#gaussTags - distribution , skew

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

Page 295: Quantitative Finance Collector

Functions for portfolio analysis

Functions include:1. efficient.portfolio compute minimum variance portfolio subject totarget return2. globalMin.portfolio compute global minimum variance portfolio3. tangency.portfolio compute tangency portfolio4. efficient.frontier computer Markowitz bullet

http://faculty.washington.edu/ezivot/econ483/portfolio.ssc

Tags - markowitz , splus

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

Page 296: Quantitative Finance Collector

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?), whatcan you do? since there are many functions in S-PLUS that are missing inR, one way is to understand the functions and write your owns, workingN hours without sleep (N>?). however, you can avoid doing like that ifyou are as headche as me whenever you think of this solution. There is apackage named Splus2R, which is to facilitate the conversion of S-PLUSpackages to R packages, this package provides some missing S-PLUSfunctionality in R.

I have not tested the package, though, will update later. Here isdownloading link: http://cran.r-project.org/web/packages/splus2R/index.html.Tags - splus , r

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

Page 297: Quantitative Finance Collector

Extract Market Expectations from Financial Instruments

A Choosy review of recently techniques to extract information aboutmarket expectations from asset values for monetary policy uses.Traditionally, interest rates and forward exchange rates have beenapplied to extract expected returns of future interest rates, exchangerates and inflation. More lately, these ways have been polished to rely onimplied forward interest rates, and then to extract expected future time-paths. Very recently, methods have been studied to extract not only themean returns but the whole (risk neutral) probability distribution from aset of option prices.

Matlab files: http://home.datacomm.ch/paulsoderlind/Software/Software.html#MatLabScriptsTags - distribution

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

Page 298: Quantitative Finance Collector

Grouped T copula simulation and estimation

Copula is widely applied to model the dependence of multivariatevariable, two popula implicit copulas are Gaussian copula and T copula,however, tail dependence under Gaussian copula is asymptotically equalto zero, which is unrealistic and under-estimate the co-movement ofvariables, especially in extreme market situation nowdays; T copula, onthe other hand, has a global degree of freedom to decide largely thedependence structure, which is over-simple, for instance, risk managermight want to define different degree of freedom for different marketsdue to their special risk profile. Grouped-T copula was created toovercome this problem, where seperated degree of freedom can be setfor each subgroup. sample code is here: http://economia.unipv.it/pagp/pagine_personali/dean/programs/gruped_t_copula_simul_estTags - copula

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

Page 299: Quantitative Finance Collector

Mean-variance portfolio optimization

QuotationWe seek to try out ga and patternsearch functions of the GeneticAlgorithm and Direct Search Toolbox. We consider the unconstrainedmean-variance portfolio optimization problem, handled by portopt andportalloc of the Financial Toolbox - note that in absence of constraintsother than sum(w) = 1, the problem admits a simple closed-form analyticsolution - and see whether ga and patternsearch succeed at locating theoptimal portfolio identified by portalloc.

http://www.mathworks.com/matlabcentral/fileexchange/16884

Tags - optimization , markowitz

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

Page 300: Quantitative Finance Collector

Asymmetric Power Distribution

Asymmetric Power Distribution (APD) family of densities extends theGeneralized Power Distribution to cases where the data exhibitsasymmetry.

It contains the asymmetric Gaussian and Laplace densities as specialcases.

In the paper entitled "Asymmetric Power Distribution: Theory andApplications to Risk Measurement", the author provide a detaileddescription of the properties of an APD random variable, such as itsquantiles and expected shortfalls.

http://econ.ucsd.edu/~ikomunje/code.htm to download "AsymmetricPower Distribution: Theory and Applications to Risk Measurement" andMatlab code files.Tags - distribution , asymmetric

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

Page 301: Quantitative Finance Collector

Spatial Statistics Toolbox for Matlab

Historically, it has been difficult to apply spatial statistics to largedatasets (e.g., more than 10,000 observations). This site contains publicdomain spatial software written in Matlab (Matlab Spatial StatisticsToolbox 2.0) capable of estimating very large spatial autoregressions(e.g., one example involves 1,000,000 observations). The spatial softwareuses sparse matrix methods to compute the matrix determinantsemployed in the maximum likelihood estimation of the spatialautoregressions. Specifically, the software can estimate simultaneousspatial autoregressions (SAR), conditional spatial autoregressions (CAR),mixed regressive spatially autoregressive (MRSA) estimates as well asother lattice models which are the mainstay of spatial econometrics.Version 1.1 contained routines for specifying dependence via nearestneighbors or contiguity, exact log-determinant computations, and closedform maximum likelihood estimation of closest neighbor dependence.

Check http://www.spatial-statistics.com/ for downloading.Tags - matlab , statistics

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

Page 302: Quantitative Finance Collector

Generate random numbers of stable distribution

A deluging section of the research in financial markets is established onthe presumption that financial markets are forced by a gaussian process.This presumption has been largely debated, and it has often beendemonstrated than it's untrue for equity, forex, and commoditiesmarkets. Stable distributions have been advised as a better modelinstead.

Nevertheless, stable distributions are not applied much in theindustry due to a lack of proper interpreting and usable softwarepackage. The lack of analytical formulas for the probability density andcumulative distribution functions is also a reason.

For codes and research results of stable distribution clickhttp://dimacs.rutgers.edu/~graham/code.htmlTags - stable , distribution

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

Page 303: Quantitative Finance Collector

A Simple Trick to Avoid Oscillation in Binomial Trees

Derivative price can be calculated either by analytic formula like BlackScholes model, or by numerical solution, for instance, solving paritialdifference equation, Monte carlo simulation, binomial tree, etc. A lot ofpeople are not aware of this simple trick to avoid oscillation in binomialtrees. Oscillation might become dangerous when calculating Greeks vianumerical 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

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

Page 304: Quantitative Finance Collector

Kernel density estimation

One of widely applied non-parametric density estimation methods. Fastand accurate state-of-the-art bivariate kernel density estimator withdiagonal bandwidth matrix. The kernel is assumed to be Gaussian. Thetwo bandwidth parameters are chosen optimally without ever using/assuming a parametric model for the data or any "rules ofthumb". Unlike many other procedures, this one is immune to accuracyfailures in the estimation of multimodal densities with widely separatedmodes.

http://www.mathworks.com/matlabcentral/fileexchange/17204Tags - kernel , density

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

Page 305: Quantitative Finance Collector

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

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

Page 306: Quantitative Finance Collector

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

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

Page 307: Quantitative Finance Collector

Uniform Random Number Generator

Uniform Random number is crucial for Monte Carlo simulation, somefamous uniform random number generators are Halton sequence andSobol sequence. Normal random number can be simulated then byinverse normal cumulative function, for instance, Peter J Acklam inversenormal cumulative distribution or Beasley-Springer-Moro inversenormal.

UNIFORM is a Mathematica library which return a sequence ofuniformly distributed pseudorandom numbers.

The fundamental underlying random number generator in UNIFORM isbased on a simple, old, and limited linear congruential random numbergenerator originally used in the IBM System 360.

For detail and several language version pls clickhttp://people.scs.fsu.edu/~burkardt/math_src/uniform/uniform.html.Tags - simulation , monte carlo

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

Page 308: Quantitative Finance Collector

Feedforward Neural Networks and Lyapunov ExponentsEstimation

This program, NETLE.EXE, estimates feedforward neural networkmodels and computes Lyapunov exponents (LE). Neural networks areestimated by the method of nonlinear least squares (NLS) (Kuan and Liu(1995)); Lyapunov exponents are calculated from the derivative matricesof estimated network models (Gencay and Dechert (1992)). Note that apositive Lyapunov exponent indicates that the underlying series ischaotic.

REFERENCES:

Kuan, Chung-Ming and Tung Liu (1995). "Forecasting exchange ratesusing feedforward and recurrent networks", Journal of AppliedEconometrics, forthcoming.

Gencay, Ramazan and W. D. Dechert (1992). "An algorithm for the nLyapunov exponents of an n-dimensional unknown dynamical system",Physica D, 59, 142-157.

http://www.sfu.ca/~rgencay/lyap.html

Tags - neural-network

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

Page 309: Quantitative Finance Collector

Estimation of parameters and eigenmodes of multivariateautoregressive 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 andeigenmodes of multivariate autoregressive models. ACM Trans. Math.Softw., 27, 27–57.

T. Schneider and A. Neumaier, 2001: Algorithm 808: ARfit - A Matlabpackage for the estimation of parameters and eigenmodes ofmultivariate autoregressive models. ACM Trans. Math. Softw., 27, 58–65.

Paper and Package are at http://www.gps.caltech.edu/~tapio/arfit/#files.Tags - autoregressive

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

Page 310: Quantitative Finance Collector

Interest Rate Modeling in Excel

Interest Rate Modeling including:

Nelson Siegel Yield Curve ModelNelson Siegel Yield Curve Model with Svensson 1994 ExtensionOne-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.htmTags - yield

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

Page 311: Quantitative Finance Collector

Multivariate dependence with copulas

Classes (S4) of commonly used copulas including elliptical (normal andt), Archimedean (Clayton, Gumbel, Frank, and Ali-Mikhail-Haq),extreme value (Husler-Reiss and Galambos), and other families (Plackettand Farlie-Gumbel-Morgenstern). Methods for density, distribution,random number generation, bivariate dependence measures, perspectiveand contour plots. Functions for fitting copula models. Independencetests among random variables and random vectors. Serial independencetests for univariate and multivariate continuous time series. Goodness-of-fit tests for copulas based on multipliers and on the parametricbootstrap.

R package can be downloaded at http://cran.r-project.org/web/packages/copula/index.htmlTags - copula

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

Page 312: Quantitative Finance Collector

Extreme Value Analysis in Matlab

EVIM: A Software Package for Extreme Value Analysis in MATLAB

QuotationFrom the practitioners’ point of view, one of the most interestingquestions that tail studies can answer is what are the extrememovements that can be expected in financial markets? Have we alreadyseen the largest ones or are we going to experience even largermovements? Are there theoretical processes that can model the type offat tails which come out of our empirical analysis? Answers to suchquestions are essential for sound risk management of financialexposures. It turns out that we can answer these questions within theframework of the extreme value theory. This paper provides a step-by-step guideline for extreme value analysis in the MATLAB environmentwith several examples.

paper and code can be downloaded at http://www.sfu.ca/~rgencay/evim.html.Tags - extreme

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

Page 313: Quantitative Finance Collector

Primitive polynomials for Sobol sequences

Quasi monte carlo method is popular for derivative pricing, Sobolsequences is among the most widely-used low-discrepancy sequences,and most efficient one I have ever used. The biggest challenge forgenerating sobol sequences is to construct primitive polynomials, here isa Mathematic file showing the algorithm to construct primitivepolynomials for multi-dimensional Sobol sequences , have fun.

http://leippold.googlepages.com/matlabTags - sobol , simulation

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

Page 314: Quantitative Finance Collector

Modeling Financial Time Series with S-PLUS

Although S-plus is the most terrible language I have ever used in termsof debugging (I have to say that, no offense to S-plus fans, as mycolleagues said, it is hard to understand it is still existed in 21 centuary), Ifound the S-plus scripts accompanying the book Modeling FinancialTime Series with S-PLUS, covering:

Time Series Manipulation, Time Series Concepts, Unit RootTests, Modeling Extreme Values, Time Series Regression, UnivariateGARCH, Long Memory, Rolling Analysis, Systems of RegressionEqations, VAR Models, Cointegration, Factor Models, Term Structure,Copulas, Generalized Method of Moments, etc.

For detail please download at http://faculty.washington.edu/ezivot/MFTS2ndEditionScripts.htmTags - s-plus

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

Page 315: Quantitative Finance Collector

Yield Curve Modelling

Exponentials, Polynomials, and Fourier Series: More Yield CurveModelling at the Bank of Canada, where the authors used Cubic-spline,B-spline and MLES spline curve to model interest rate curve, including apenalty in the generalized least-squares objective function.

Interested ppl can refer to the PDF document and Matlab codes are atappendix. http://www.bankofcanada.ca/en/res/wp/2002/wp02-29.htmlTags - matlab , yield

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

Page 316: Quantitative Finance Collector

Online derivative calculator

An online derivative calculator covers:

Bond Price Volatility: duration(s), convexity, immunization;Term Structure: yield curve, spot rate, forward rate, term structuretheoriesOption Pricing: Black-Scholes, binomial, European, AmericanNumerical Greeks (& Some Latin): delta, gamma, vega, thetaOption Applications & Exotic Options: Corporate securities, barrier,Asian, lookback, Parisian option,compound, exchange, etc.futures, forward, futures option, swapMonte Carlo & Quasi-random: variance reduction, Brownian bridge,Halton-, Sobel-, Faure-sequencesGARCH option pricing model:multinomial tree, Monte CarloInterest Rate Models: lognormal, Vasicek, CIR, BDT, Hull-White, HJMMortgage-backed Securities: prepayment, PSA, CPR, SMM, pass-through, CMO, stripped MBS, ARM, prepayment model, seq. CMO, PO/IO, PAC, option-adjusted spread, cash flow, durationconvertible bond, callable & put bond, option-adjusted spread...

http://www.csie.ntu.edu.tw/~lyuu/Capitals/capitals.htmTags - calculator , derivative

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

Page 317: Quantitative Finance Collector

VaR and Expected shortfall under Generalized Student t

Value at risk (VaR) is the expected maximum loss an asset or a portfoliocan incur over a target horizon within a given confidence level; ExpectedShortfall (ES), also called Conditional tail expectation (CTE), is theexpectation of the losses bigger (that is, worse) than VaR over a targethorizon within a given confidence level. There are several methods incalculating VaR, including Historical simulation, Monte Carlosimulation, and parametric method, dozens of underlying distributionsare ready for choice when using Monte Carlo simulation and Parametricmethod, among which Gaussian distribution is, undoubtedly the mostpopular one, t-distribution is also widely used due to its ability tocapture fat-tail.

A sample Matlab code to construct the Generalized Student t over agiven support then compute quantiles and numerical expected shortfallis http://www.hec.unil.ch/matlabcodes/Econometrics/TestGTdens.m.

Tags - var , es , t

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

Page 318: Quantitative Finance Collector

Quantitative Risk Management R package

I shared an Econometric tools for performance and risk analysis packagein R, today I introduce another Quantitative Risk Management Rpackage, which is accompanying the book Quantitative RiskManagement: Concepts, Techniques and Tools by Alexander J. McNeil,Rudiger Frey and Paul Embrechts, a nice book written by one of myprofessors. In this book special care is given to Copula analysis, Extremevalue thoey, credit risk analysis, etc. Given the fact it was ranked by oneof the top 10 most technical books of the year 2007, i bet you will learn alot from it.

R-language version can be downloaded at http://cran.r-project.org/web/packages/QRMlib/index.html and S-PLUS library to accompanybook is at http://www.ma.hw.ac.uk/~mcneil/book/index.html.Tags - risk

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

Page 319: Quantitative Finance Collector

Levenberg-Marquardt nonlinear least squares algorithms

In mathematics and computing, the Levenberg–Marquardt algorithm (orLMA) provides a numerical solution to the problem of minimizing afunction, generally nonlinear, over a space of parameters of the function.These minimization problems arise especially in least squares curvefitting and nonlinear programming.

The Levenberg-Marquardt algorithm has proved to be an effective andpopular way to solve nonlinear least squares problems. MINPACK-1contains Levenberg-Marquardt codes in which the Jacobian matrix maybe 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 leastsquares problems and orthogonal distance regression problems,including those with implicit models and multiresponse data.

For detail about Levenberg-Marquardt nonlinear least squaresalgorithms introduction and code pls click http://www.ics.forth.gr/~lourakis/levmar/Tags - levenberg-marquardt , optimization

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

Page 320: Quantitative Finance Collector

Newey and West Covariance Matrix Estimator

Covariance matrix is vital for pricing and risk analysis, before I shares aMatlab code on weighted covariance matrix computation, here is anothermethod named Newey & West covariance matrix, which calculates thecovariance matrix with a non-parametrical method. Choices of kernelsinclude Bartlett, Truncated and Quadratic Spectral. An example programalso demonstrates how to use of these procedures. For detail please referto http://kafuwong.econ.hku.hk/research/gausscode/cov1.htm.Tags - covariance

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

Page 321: Quantitative Finance Collector

Calibrating the Ornstein-Uhlenbeck model

Ornstein-Uhlenbeck model is widely used to model interest rate, twopopular types are Vasicek and CIR, here the author describes twomethods for calibrating the model parameters of an Ornstein-Uhlenbeckprocess to a given dataset.

* The least squares regression method* maximum likelihood method

methdology applied and sample matlab code are athttp://www.sitmo.com/doc/Calibrating_the_Ornstein-Uhlenbeck_model.Tags - yield , calibration

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

Page 322: Quantitative Finance Collector

Econometrics Software

Dozens of Matlab code for Econometrics study, including:

Brock, Dechert& Scheinkman (1986) test for independence based on thecorrelation dimension

Significance level of the BDS statistic in small samples

Geweke &Porter-Hudak (1983) estimation of fractional differencingparameter

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-samplecorrection

Phillips-Perron test of the unit-root hypothesis in a Dickey-Fullerregression

Durbin h statistic and significance of the hypothesis of no serialcorrelation

Durbin-Watson d-statistic and significance level for the null hypothesis:DW = 2

http://ww61.tiki.ne.jp/~kanzler/index.htm#L.%20Kanzler:%20SoftwareTags - econometrics

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

Page 323: Quantitative Finance Collector

Black Litterman Portfolio Allocation

QuotationThe Black Litterman model was first published by Fischer Black andRobert Litterman of Goldman Sachs in an internal Goldman Sachs FixedIncome document in 1990. This paper was then published in the Journalof Fixed Income in 1991. A longer and richer paper was published in1992 in the Financial Analysts Journal (FAJ). The latter article was thenrepublished by FAJ in the mid 1990's. Copies of the FAJ article arewidely available on the Internet. It provides the rationale for themethodology, and some information on the derivation, but does notshow all the formulas or a full derivation. It also includes a rathercomplex worked example, which is difficult to reproduce due to thenumber of assets and use of currency hedging.

The Black Litterman model makes two significant contributions to theproblem of asset allocation. First, it provides an intuitive prior, theCAPM equilibrium market portfolio, as a starting point for estimation ofasset returns. Previous similar work started either with theuninformative uniform prior distribution or with the global minimumvariance portfolio. The latter method, described by Frost and Savarino(1986) and Jorion (1986), took a shrinkage approach to improve the finalasset allocation. Neither of these methods has an intuitive connectionback to the market,. The idea that one could use 'reverse optimization' togenerate a stable distribution of returns from the CAPM market portfolioas a starting point is a significant improvement to the process of returnestimation.

Second, the BlackLitterman model provides a clear way to specifyinvestors views and to blend the investors views with prior information.The investor's views are allowed to be partial or complete, and the viewscan span arbitrary and overlapping sets of assets. The model estimatesexpected excessreturns and covariances which can be used as input to anoptimizer. Prior to their paper, nothing similar had been published. Themixing process had been studied, but nobody had applied it to theproblem of estimating returns. No research linked the process ofspecifying views to the blending of the prior and the investors views.The BlackLitterman model provides a quantitative framework forspecifying the investor's views, and a clear way to combine those

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

Page 324: Quantitative Finance Collector

investor's views with an intuitive prior to arrive at a new combineddistribution.

For a collection of reference paper and an online application please seehttp://www.blacklitterman.org/blapplet.htmlTags - allocation , black-litterman

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

Page 325: Quantitative Finance Collector

Hull-White Term Structure Model

Accompanying Excel of "Implementation of Hull White's No-ArbitrageTerm Structure Model" by Eugen Puschkarski, including:

HEDGE.XLS: Calculation of hedge parametersCALIBRAT.XLS: Calibration of the model to market data, calculation ofoptimal volatility parametersAMERICAN.XLS: Valuation of American style optionCALLABLE.XLS: Valuation of callable, putable bondsCAP.XLS: Valuation of Caps and Floors, comparison of analytical andnumerical solutionCOUPON.XLS: Pricing of an option on a coupon bondBINARY.XLS: Valuation of binary options of an accrual swapCONVERG2.XLS: Analysis of convergence behaviour of the numericalsolutionCONVERG3.XLS: Analysis of convergence behaviour if cash flowsbetween nodes do occurFLOATER1.XLS: Valuation of standard and non-standard floaterNUM.XLS: Numerical valuation of zero coupon bond optionsSWAP.XLS: Calculation of swaptions

Paper and Excel file can be found at http://www.angelfire.com/ny/financeinfo/research.htmlwiki(Hull-White model)Tags - hull-white , yield

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

Page 326: Quantitative Finance Collector

Fourier Space Time-stepping (FST) option calculator

Online Fourier Space Time-stepping (FST) option calculator whereoptions class includes European, American, Barrier, Shout and Spreadoption; underlying stock process follows Black Scholes Merton, MertonJump Diffusion, Kou Jump Diffusion, Variance Gamma, Normal InverseGaussian 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 sitehttp://128.100.73.155/fst/.

Papers:

* Option Pricing with Regime Switching Levy Processes Using FourierSpace Time-stepping

* Fourier Space Time-stepping for Option Pricing with Levy Models.

Related Matlab codes can also be downloaded athttp://www.cs.toronto.edu/~vsurkov/fst_matlab.htmlTags - calculator , derivative , option

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

Page 327: Quantitative Finance Collector

Nearest correlation matrix

Correlation matrix exists almost everywhere for derivative pricing andrisk management, especially when Monte Carlo simulation is applied,for instance, to simulate correlated random numbers via Choleskydecomposition of correlation matrix. However, one strong requirementof Cholseky decomposition on correlation matrix is positive semi-definite, in other words, eigenvalues must be positive. Another exampleof positive semi-definite correlation matrix requirement is for riskmanagement measurement, otherwise the volatility calculated might benegative, which is non-acceptable.

In practice, sometimes we need to change correlation matrix to ourforecasting values, even minor change might lead to invalid matrix, forthis problem, http://www.maths.manchester.ac.uk/~nareports/narep369.pdf details the way to overcome it, accompanying Matlab codecan 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

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

Page 328: Quantitative Finance Collector

MySQL and Matlab

The MySQL database server is very popular for its openness, robustness,and speed. Matlab is a wonderful commercial product for scientific andtechnical computing. Using them together is a great tool for quantitativedata analysis. You can do this using the Matlab Database Toolbox, but itis more efficient to connect directly using the APIs for both products.This code implements that connection, with a fairly rich framework forhandling data conversion, especially dates and times.

http://cims.nyu.edu/~almgren/mysql/Tags - matlab , sql

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

Page 329: Quantitative Finance Collector

Rmetrics - Basics of Option Valuation

Open Source Software for Financial Engineering and ComputationalFinance

Rmetrics is the premier open source solution for teaching financialmarket analysis and valuation of financial instruments. With hundredsof functions build on modern methods Rmetrics combines explorativedata analysis, statistical modeling and rapid model prototyping. TheRmetrics Packages are embedded in R building an environment whichcreates for students a first class system for applications in statistics andfinance.

Download at http://cran.cnr.berkeley.edu/web/packages/fOptions/index.htmlTags - r , option

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

Page 330: Quantitative Finance Collector

Singular Value Decomposition

In linear algebra, the singular value decomposition (SVD) is animportant factorization of a rectangular real or complex matrix, withseveral applications in signal processing and statistics. Applicationswhich employ the SVD include computing the pseudoinverse, leastsquares 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 andon-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

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

Page 331: Quantitative Finance Collector

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 itstractability and robustness relative to other SV models.

This project initially begun as one that addressed the calibration problemof this model. Attempting to solve such a problem was an impossibletask due to the lack of exposure to such ‘advanced’ models.

I, therefore, decided to take a slight digression into the world of Hestonand stochastic volatility. Enroute I realised that fundamental informationthat one would require to gain an intuitive understanding of such amodel 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 isquite practical itself. All the relevant tools are provided to facilitate thiscalibration process, including MATLAB code. This code has beenconfined 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.zipTags - heston

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

Page 332: Quantitative Finance Collector

MATLABroutines for risk and portfolio management

These routines support the book "Risk and Asset Allocation" SpringerFinance, 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 classicalequivalent- robust estimators: Hubert M, high-breakdown minimum volumeellipsoid- missing-data techniques: EM algorithm, uneven-series conditionalestimation- stochastic dominance- extreme value theory for VaR- Cornish-Fisher approximation for VaR- kernel-based contribution to VaR and expected shortfall from differentrisk-factors- mean-variance analysis and pitfalls (different horizons, compoundedvs. linear returns, etc...)- Bayesian estimation (multivariate analytical, Monte Carlo MarkovChains, priors for correlation matrices)- estimation risk evaluation: opportunity cost of estimation-basedallocations- Black Litterman allocation- robust optimization (calls SeDuMi to perform cone programming)- robust Bayesian allocation- more...

sample chapter and codes can be downloaded athttp://www.symmys.com/AttilioMeucci/Book/Downloads/

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

Page 333: Quantitative Finance Collector

DownloadsTags - allocation

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

Page 334: Quantitative Finance Collector

Code search portal

Share two code search portal today, one is search Quant code, wherepeople can search code relative to quantitative finance, for instance,Code Search example: Black Scholes matlab; the other one is R-projectsearch engine, specifically for R language programming users. Enjoy.

http://www.finmath.cn/

http://www.rseek.org/

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

Page 335: Quantitative Finance Collector

Bayesian Copula Selection

Matlab implementation of a method to select the 'best' copula among asubset 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

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

Page 336: Quantitative Finance Collector

Multidimensional numerical integration

Most derivative pricing problems have finally come to solve integrationnumerically, by Simpson, Monte Carlo simulation, etc., however, multi-dimensional integration is time-consuming and prone to error, here Ishare a Cuba library which offers a choice of four independent routinesfor multidimensional numerical integration: Vegas, Suave, Divonne, andCuhre.QuotationVegas is the simplest of the four. It uses importance sampling forvariance reduction, but is only in some cases competitive in terms of thenumber of samples needed to reach a prescribed accuracy. Nevertheless,it has a few improvements over the original algorithm and comes inhandy for cross-checking the results of other methods.

Suave is a new algorithm which combines the advantages of two popularmethods: importance sampling as done by Vegas and subregionsampling in a manner similar to Miser. By dividing into subregions,Suave manages to a certain extent to get around Vegas' difficulty toadapt its weight function to structures not aligned with the coordinateaxes.

Divonne is a further development of the CERNLIB routine D151.Divonne works by stratified sampling, where the partitioning of theintegration region is aided by methods from numerical optimization. Anumber of improvements have been added to this algorithm, the mostsignificant being the possibility to supply knowledge about theintegrand. Narrow peaks in particular are difficult to find withoutsampling very many points, especially in high dimensions. Often theexact or approximate location of such peaks is known from analyticconsiderations, however, and with such hints the desired accuracy canbe reached with far fewer points.

Cuhre employs a cubature rule for subregion estimation in a globallyadaptive subdivision scheme. It is hence a deterministic, not a MonteCarlo method. In each iteration, the subregion with the largest error ishalved along the axis where the integrand has the largest fourthdifference. Cuhre is quite powerful in moderate dimensions, and isusually the only viable method to obtain high precision, say relativeaccuracies much below 1e-3.

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

Page 337: Quantitative Finance Collector

http://www.feynarts.de/cuba/

Tags - integration

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

Page 338: Quantitative Finance Collector

Econometric tools for performance and risk analysis

QuotationLibrary of econometric functions for performance and risk analysis offinancial portfolios. This library aims to aid practitioners and researchersin using the latest research in analysis of both normal and non-normalreturn streams.

We created this library to include functionality that has been appearingin the academic literature on performance analysis and risk over the pastseveral years, but had no functional equivalent in R. In doing so, we alsofound it valuable to have wrapper functions for functionality easilyreplicated in R, so that we could access that functionality using afunction with defaults and naming consistent with common usage in thefinance literature. The following sections cover Performance Analysis,Risk Analysis (with a separate treatment of VaR), Summary Tables ofrelated statistics, Charts and Graphs, a variety of Wrappers and Utilityfunctions, and some thoughts on work yet to be done.

http://braverock.com/brian/R/PerformanceAnalytics/html/PerformanceAnalytics-package.htmlTags - econometrics , performance , r

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

Page 339: Quantitative Finance Collector

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.htmlspreadsheet http://www.schonbucher.de/risk/rating_case.xlsTags - rating

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

Page 340: Quantitative Finance Collector

Collection of R codes

R-Cookbook.com is a collection of "recipes"--problems, solutions, andworking examples--contributed by the R community in order to sharecode, promote the use of R, and make the learning process more efficientfor new users.

http://www.r-cookbook.com/

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

Page 341: Quantitative Finance Collector

OLS Regression with missing values

Excel provides a handy function called LINEST that allows the user tomake 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 installingthis add-in, you can simply say LINESTNA(...) instead of LINEST(...) andthe problem with the missing values is gone.

The program first extracts the rows that do not contain any missingvalues, and then calls Excel's LINEST to perform the estimation with thecleaned data. The data have to be organized column-wise.

http://www.wwz.unibas.ch/ds/abt/wirtschaftstheorie/personen/yvan/software/#c6714Tags - regression

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

Page 342: Quantitative Finance Collector

Crank-Nicholson finite difference solution of Americanoption

Crank-Nicolson for a European put was introduced before, to bettermaster this technique, i share another sample code using Crank-Nicholson finite difference for American option.

BLSPRICEFDAM Black-Scholes put and call pricing for AmericanOptions using the Crank-Nicholson finite difference solution of Black-Scholes Partial differential equation. Note that this function returns anapproximate solution unlike the analytical solution (BLSPRICE)SO is the current asset price, X is the exercise price, R is the risk-freeinterest rate, T is the time to maturity of the option in years, SIG is thestandard deviation of the annualized continuously compounded rate ofreturn of the asset (also known as volatility), and Q is the dividend rateof the asset. The default Q is 0. N denotes the number of discretizationpoints in the stock price domain, and M denotes the number ofdiscretization points in time domain used for the PDE solution.Tryincreasing 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 filehttp://www.cs.cornell.edu/Info/Courses/Spring-98/CS522/content/blspricefdam.m.Tags - american , pde , option

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

Page 343: Quantitative Finance Collector

Career change

Arrived in London today, new job will start from tomorrow, the first fewweeks 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 yoursupport.

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

Page 344: Quantitative Finance Collector

Up-and-out call option by Monte Carlo

Another sample code of the book An Introduction to Financial OptionValuation: Mathematics, Stochastics and Computation, read Crank-Nicolson for put. This sample calculates a up-and-out call barrier optionvia Monte Carlo simulation with antithetic variates.

An up and out call is a regular call option that ceases to exist if the assetprice 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

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

Page 345: Quantitative Finance Collector

Trinomial tree class for short rate model

This page comprises the code and items of a C++ class that could beapplied to construct a trinomial tree for the short rate. The tree matchesto the yield curve but not to the volatility. curve.

The programming code is grounded on the book "ImplementingDerivatives Models", page 260, Clewlow and Strickland, the codespecifies a C++ implementation of a tree object. By input a set ofparameters the class will form an array of nodes, each one correspondingto a node on the tree. Currently the tree is matched to the underlyinginterest rate curve, but not a vol. curve.

http://www.phineas.pwp.blueyonder.co.uk/TreeClass.htmTags - yield

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

Page 346: Quantitative Finance Collector

Variance swap hedging under Heston volatility

Calculate variance swap hedging portfolio under Heston vol modelusing MC simulation. The strategy is discussed in Gatheral p.136 andhttp://www.ederman.com/new/docs/gs-volatility_swaps.pdf.

The strategy works by exploiting the difference between percentagedifferences 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). Foremore detail refer to http://math.nyu.edu/~atm262/files/fall06/casestudies/a7/hestonvarswap.m and the above mentioned paper.Tags - heston

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

Page 347: Quantitative Finance Collector

Vasicek Model calibration and simulation

Entries Vasicek estimation and Vasicek model in binomial treeintroduced how to estimate Vasicek model parameters, how toimplement Vasicek interest rate model in binomial tree, which can befurther used to price option on bonds, for instance. Here i share anothertwo excel files demonstrating how to calibrate a Vasicek model to agiven term structure and simulate Vasicek zero bond prices and the pathof the short rate.

Download at http://www.mathematik.uni-kl.de/~korn/korn2b.htm,besides Vasicek short rate model, CIR, Dothan and Exponential Vasicekare also included in one file.Tags - vasicek

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

Page 348: Quantitative Finance Collector

Solving PDE implicit / explicit methods

Basically there are two types of finite difference methods: explicit finitedifference method and implicit finite difference method. Other types arejust the derivation of these two types, for example, Crank-Nicolsonmethod is an average of the explicit method and implicit method.

Two sample Matlab files to compare the performance of solving PDE viaimplicit and explicit method. http://frontera.bu.edu/MathFn.html

wiki(Finite difference method)Tags - pde

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

Page 349: Quantitative Finance Collector

Unified Asian Option Pricing

Asian options are securities with payoff which depends on the averageof the underlying stock price over certain time interval. Since no generalanalytical solution for the price of the Asian option is known, a variety oftechniques have been developed to analyze arithmetic average Asianoptions.

A simple and numerically stable 2-term partial differential equationcharacterizing the price of any type of arithmetically averaged Asianoption is given. The approach includes both continuously and discretelysampled options and it is easily extended to handle continuous ordiscrete dividend yields.

The paper "Unified Asian Pricing", Risk, Vol. 15, No. 6, 113-116 and itsMathematica nb file can be downloaded athttp://www.stat.columbia.edu/~vecer/.Tags - asian , option

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

Page 350: Quantitative Finance Collector

Nearest Neighbour Algorithm to forecast Stock Prices

This is the algorithm involved on the use of the non-linear forecast ofasset's prices based on the nearest neighbour method.

The basic idea of the NN algorithm is that the time series copies it's ownpast behavior, and such fact can be used for forecasting purposes. On thezip file there are two functions: one is the univariate version of NN(nn.m) and the other is the multivariate approach, also calledsimultaneous NN (snn.m).

QuotationThe nearest neighbor method is defined as a non-parametric class ofregression. Its main idea is that the series copies its own behavior alongthe time. In other words, past pieces of information on the series havesymmetry with the last information available before the observation ont+1. Such way of capturing the pattern on the times series behavior is themain argument for the similarity between NN algorithm and thegraphical 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 patternbetween the locations of the observations in time. For the NN, suchlocation is not important, since the objective of thealgorithm is to locate similar pieces of information, independently oftheir location in time. Behind all the mathematical formality, the mainidea of the NN approach is to capture a nonlinear dynamic of self-similarity on the series, which is similar to the fractal dynamic of achaotic time series.

http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=9396&objectType=fileTags - forecast

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

Page 351: Quantitative Finance Collector

FFT computation of option prices

The Black-Scholes formula, one of the major breakthroughs of modernfinance, allows for an easy and fast computation of option prices. Butsome of its assumptions, like constant volatility or log-normaldistribution of asset prices, do not find justification in the markets. Morecomplex models, which take into account the empirical facts, often leadto more computations and this time burden can become a severeproblem when computation of many option prices is required, e.g. incalibration of the implied volatility surface. To overcome this problemCarr and Madan (1999) developed a fast method to compute optionprices for a whole range of strikes.

Fast Fourier transform (FFT) is applied for this purpose, the use of theFFT is motivated by two reasons. On the one hand, the algorithm offers aspeed advantage. This effect is even boosted by the possibility of thepricing algorithm to calculate prices for a whole range of strikes. On theother hand, the cf of the log price is known and has a simple form formany models considered in literature, while the density is often notknown 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

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

Page 352: Quantitative Finance Collector

Rank reduction of correlation matrices by majorization

Rank reduction is useful for multi-factor derivative pricing and riskanalysis, for instance, for a Bermudan swaption, Major, MajorW andMajorPower are MATLAB templates that may be used to find a low-rankcorrelation matrix locally nearest to a given correlation matrix, by meansof majorization. Major implements equal weights on the entries of thecorrelation matrix. MajorW implements non-constant weights.

For an introductory of Rank reduction of correlation matrices bymajorization paper can be downloaded at http://www.pietersz.org/majorization.pdf, with Matlab codeshttp://www.pietersz.org/major.htmTags - correlation

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

Page 353: Quantitative Finance Collector

Option greeks analysis

A useful tool built to help the user gain an intuitive feel for optionpricing 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 createdusing the GUI).

Once this is done, the user can plot the option price, delta, gamma, vegaand variance vega in 3D and examine how they vary with time tomaturity, volatility, interest rates and carry.

It also allows you to perturb a 4th dimension also allowing you to createan animation.

Type PlotMeTheGreeks() on the matlab command line to start the GUI.

http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=10428&objectType=FILETags - greeks , option

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

Page 354: Quantitative Finance Collector

Real option case study

Nth much to say, for those of you interested into applying real optionvaluation model in real situation.

Doc file and Excel sheet can be downloaded herehttp://faculty.fuqua.duke.edu/~charvey/Teaching/BA456_2002/LogiTech/.Tags - real-option , option

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

Page 355: Quantitative Finance Collector

Peter J Acklam inverse normal cumulative distribution

Random number generation is essential for Monte Carlo simulation,among random numbers, normal distributed numbers are undoubtedlythe most widely used ones, here comes the problem, for a given uniformrandom numbers series, how do you compute the inverse normalcumulative distribution function?

I once introduced Moro inverse normal function for this purpose, here isanother power function named Peter J Acklam inverse normalcumulative distribution, for my study and work i have tried both butcouldnot decide which one is better, here i quote the sentence from thebook "Monte carlo methos in finance" by Peter Jackel: Equally, for theinverse cumulative normal function z = N'(p), there are severalnumerical implementations providing different degrees of accuracy andefficiency. A very fast and accurate approximation is the one given byBoris Moro in [Mor95]. The most accurate whilst still highly efficientimplementation currently freely available, however, is probably thealgorithm by Peter Acklam. when allowing for an additional evaluationof a machine-accurate cumulative normal distribution function,Acklam’s procedure is able to produce the inverse cumulative normalfunction to full machine accuracy by applying a second stage refinementusing Halley’s method.

Good, here is the page for Peter J Acklam inverse normal cumulativedistribution codes in several languages, http://home.online.no/~pjacklam/notes/invnorm/index.html#The_algorithm, enjoy.Tags - random , normal

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

Page 356: Quantitative Finance Collector

Numerical valuation of convertible bonds

A Convertible Bond (CB) is a hybrid derivative with complex embeddedfeatures, it allows the holder to convert the bond to a certain shares(conversion ratio) of stock issued by the same company at a prescribedstock price (conversion price), besides this feature, CB normally hasembedded American call (put) option which allows the bond issuer(holder) to call (sell) back the CB from holder (to issuer) at a pre-decidedcall (put) price once the underlying stock price is above (below) strikeprice for a certain prescribed, consecutive time, hereafter called Parisianoption; in Asian markets, CB also has a refix clause which allows thebond issuer to reset the conversion price, under several stock pricescenarios; as a hybrid product with equity and fixed incomecharacteristics, CB is under default risk, both stochastic interest rate andstochastic volatility play a role for its valuation; etc,.

The convertible bond calculator uses a binomial lattice with the stockprice as the only state variable to analyse convertible bonds with call andput features. The software does not use the warrant valuation approachwhich requires the volatility of equity (stocks plus warrants). Instead, itignores the dilution effect and uses stock price volatility which is morereadily available.download at http://www.iimahd.ernet.in/~jrvarma/software/ecb.ziponline convertible bonds calculator http://www.iimahd.ernet.in/~jrvarma/software/convertible.php, more are athttp://www.iimahd.ernet.in/~jrvarma/software.php.

Tags - convertible bond

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

Page 357: Quantitative Finance Collector

Spread option valuation

Spread option derives its value from the difference between the prices oftwo or more assets, it can be considered as a type of rainbow option inthat it's payoff depends on 2 or 3 underlying assets. for instance, for a 2underlying 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 thesetwo stock prices. Spread option is widely used in energy industry,especially in oil industry.

In previous entry how to price spread option with Monte Carlosimulation was introduced, here is another valuation method of spreadoptions follwing the article Low-Fat Spreads by K. Ravindran, RISK, Oct1993.

for detail check http://www.mathfinance.org/FF/cpplib.php。Tags - spread , option

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

Page 358: Quantitative Finance Collector

Cliquet option with Jump-Diffusion Bates Model

Cliquet option, also called ratchet option, is an extended roll-downoption, with strikes set at the barriers, which never knock outcompletely. It is a series of at the money options, with periodicsettlement, resetting the strike value at the then current price level, atwhich time, the option locks in the difference between the old and newstrike and pays that out as the profit. The profit can be accumulated untilfinal maturity, or paid out at each reset date.

The Bates Model is a type of Jump-Difussion model that is able toimprove calibration results for short term options. The Bates Modelconsists of Jumps processes built on top a Heston model.

http://www.javaquant.net/finalgo/BatesModel.html lists the C++ codeto price Cliquet options using the Log-Jump variant of the Bates modelwith stochastic volatility.

wiki(Cliquet option)Tags - cliquet , heston , option

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

Page 359: Quantitative Finance Collector

Arithmetic Game

One of my friends sent me an interesting site: Arithmetic game, (pleasehelp us develop by submitting a site in your favorites), The ArithmeticGame is a speed drill where you are given two minutes to solve as manyarithmetic problems as you can, problems including addition,subtraction, multiplication, and division, for each problem answeredcorrectly you will get score, test how many scores you can achieve. Thehighest score so far is 137, amazing...

http://zetamac.com/arithmetic/

This game helps me recall the exam I took for a quantitative traderposition several months ago, i failedTags - game

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

Page 360: Quantitative Finance Collector

Monte Carlo arithmetic average price Asian option

Today is the Chinese traditional Mid-Autumn Festival, also known asthe Moon Festival, which is used to celebrate the end of the summerharvesting season, first of all, wish you happy everyday and achievewhat you want. A pic of Mooncake

Asian options are options where the payoff depends on the average priceof 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 isthe average value of the underlying asset calculated over apredetermined averaging period. Average price options are lessexpensive than regular options.

Besides anti-thetic sampling method, control variate is another popularway for variance reduction, given the condition we can find a goodproxy product, whose pricing formula is easy to get, in our case,geometric average asian option is used as control variate for arithemeticaverage asian option, here is a M file demonstrating Monte Carlosimulation on an arithmetic average price Asian option using ageometric average price Asian as control variate.

http://personal.strath.ac.uk/d.j.higham/ch22.m.Tags - asian , option

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

Page 361: Quantitative Finance Collector

Constant Maturity Swap (CMS) option pricing

Constant maturity swap is a type of interest rate swap where the rate ofinterest of any single leg is readjusted in a periodic manner in case ofmarket swap rate but not with the LIBOR (London Interbank OfferedRate) or any other floating reference index rate. In other words, it mayalso be said that the constant maturity swap actually allows thepurchasers to fix the duration of the received flows on a swap. Constantmaturity swap is also known as CMS. The Constant Maturity Swaps maybe 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 thesame page http://www.finmath.net/spreadsheets/ you can also findpricing of swaption using the generalized Black-Scholes formula.

wiki(Constant maturity swap)

Tags - cms , option

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

Page 362: Quantitative Finance Collector

Normal Inverse Gaussian option pricer

QuotationTo price and hedge derivative securities, it is crucial to have a goodmodel of the probability distribution of the underlying product. Themost famous continuous-time model is the celebrated Black Scholesmodel, which uses the Normal distribution to fit the log returns of theunderlying.

As we know from empirical research, one of the main problems with theBlack–Scholes model is that the data suggest that the log returns ofstocks/indices are not Normally distributed as in the Black–Scholesmodel. The log returns of most financial assets do not follow a Normallaw. They are skewed and have an actual kurtosis higher than that of theNormal distribution. Other more flexible distributions are needed.

Moreover, not only do we need a more flexible static distribution, but inorder to model the behaviour through time we need more flexiblestochastic processes (which generalize Brownian motion). Looking at thedefinition of Brownian motion, we would like to have a similar,i.e. withindependent and stationary increments, process, based on a moregeneral distribution than the normal. However, in order to define such astochastic process with independent and stationary increments, thedistribution has to be infinitely divisible, such processes are called Lévyprocesses, 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 bedownloaded at http://www.axelvogt.de/axalom/NIG_tiny_withDLL.zip, more are at the main page of authorhttp://www.axelvogt.de/axalom/index.html.

Tags - nig , option

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

Page 363: Quantitative Finance Collector

Mixed Integer Linear Programming (MILP) solver

Are you fed up with "linprog" or "fmincon" command in Matlab? do yousometimes find the results violate your providing constraints whileMatlab says "condition satisfied", or sometimes you get a weird solutionwhile Matlab tells you "convergence successful", etc. (I am not sayingbad words about Matlab, I AM a fan of it, but if there is a better solutionfor 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 linkabout lp-solver, which is a Mixed Integer Linear Programming (MILP)solver, convenient to use and highly efficient, cannot help sharing withyou all. (please submit your favorite code site if you happen to find oneand help others, thanx.)

The name itself tells you this package is for linear programmingproblem, What is Linear Programming then? A Linear Program (LP) is aproblem that can be expressed as follows:

minimize cxsubject to Ax = b

x >= 0

where x is the vector of variables to be solved for, A is a matrix of knowncoefficients, and c and b are vectors of known coefficients. Theexpression "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 trackingerror 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 willfind a way.

Download at http://lpsolve.sourceforge.net/5.5/.Tags - optimization

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

Page 364: Quantitative Finance Collector

Pricing American Options

American options can be computed by several ways, to name a few:binomial tree, Least square Monte Carlo simulation, numerically solvingPDE. Previously I share a PSOR code to calculate LinearComplementarity Formulation problem when applying finite differenceor 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-typeoptions, enjoy.http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=16476&objectType=file.Tags - american , lsm , option

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

Page 365: Quantitative Finance Collector

Bootstrapping interest rate curve

Bootstrapping is a technique for building a zero-coupon yield curve fromthe prices of a set of coupon bonds through forward replacement.

Using these zero-coupon bonds we can deduce forward and spot ratesfor all time to maturities by making a couple of assumptions (includinglinear interpolation). The term structure of spot rates is recovered fromthe bond yields by solving for them recursively, this iterative process iscalled the BootStrap Method.

http://janroman.dhis.org/stud/Bootstrap_2006.xls shows how toimplement Boostrapping method in Excel, more can be found at hiswebsite http://janroman.dhis.org/index_eng2.html.

Tags - bootstrapping , yield

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

Page 366: Quantitative Finance Collector

Variance reduction by antithetic variable

Had a small party with friends yesterday and drank until 5 o'clock in themorning, hangover is still here after 6 hours sleep. All feasts must cometo an end, we have to accept this fact, going to leave soon the country ihave stayed over one year, leave friends accompanying me when i wassad and joyful, specially a girl i favor.

Back to code, Whenever we price a derivative via Monte Carlosimulation, for instance use Gaussian variates to simulate Brownianmotion by constructing sample paths of standard Wiener processes, wecan make use of the fact that for any one drawn path its mirror imagehas equal probability. In other words, if a single evaluation driven by aGaussian 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 variancereduction because of its simplicity to add to your code.

Run the sample code to check the variance reduction effect if you wishhttp://www.ma.ic.ac.uk/~becherer/Course07MS15/antitheticexample.m.Tags - variance-reduction

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

Page 367: Quantitative Finance Collector

Term Structure Lattice to Price Bermudan swaption

The modelling philosophy for term-structure models is somewhatdifferent to the modelling philosophy for equity models. In the lattercase, stock price dynamics are usually specified under the physicalprobability measure, P, before their dynamics under an EMM, Q, aredetermined. For example, in the binomial Black-Scholes framework aunique Q is easily determined after the P-dynamics of the stock-price aregiven. Moreover, it is easy to check that the model does not allow anyarbitrage: 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 todirectly specify their P-dynamics in an arbitrage-free manner that it iseconomically satisfactory. For example, in a T-period binomial modelthere are O(T) zero-coupon bond prices that we need to specify at eachnode. Checking that the model is arbitrage-free and that bond priceprocesses have suitable properties (e.g. implied interest rates are alwaysnon-negative) can be a cumbersome task. As a result, we usually workwith term structure models where we directly specify an EMM, Q, andprice all securities using this EMM. By construction, such a model isarbitrage free. Moreover, by leaving some parameters initiallyunspecified (e.g. short-rate values at nodes or Q-probabilities alongbranches in a lattice model) we can then calibrate them so that securityprices in the model coincide with security prices observed in the market.

In the lecture notes of Term Structure Models-Spring 2005 professorMartin Haugh introduces how to price a Bermudan swaption with termstructure lattice, precisely speaking, binomial tree, there he cailibratesboth Ho-Lee and Black Derman Toy Model and use the calibratedinterested 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 andsample spreedsheet is http://www.columbia.edu/~mh2078/TS05/Term_Structure_Lattices.xlswiki(Bermudan swaption)Tags - swaption , bermudan

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

Page 368: Quantitative Finance Collector

Crank-Nicolson for a European put

A PDE can be solved by Finite Difference or Finite Element method, bothmethods require space discretization, therefore, explicit or implicit finitedifference is applied for this problem. The advantage of explicit finitedifference is it does not require matrix inversion, however, to satisfy CFLcondition, dt (time interval) can not be too small to prevent from non-convergece result, Crank-Nicolson is supposed to balance betweenexplicit and implicit finite difference by choosing theta=1/2, whichmeans taking average of explicit and implicit method.

A sample code to show the performance of Crank Nicolson for aEuropen put can be downloaded at http://www.maths.strath.ac.uk/~aas96106/ch24.m, it is from chapter 24 of the book An Introduction toFinancial Option Valuation: Mathematics, Stochastics andComputation, more codes are at the homepagehttp://www.maths.strath.ac.uk/~aas96106/option_book.htmlwiki(Crank Nicolson)Tags - pde

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

Page 369: Quantitative Finance Collector

evolutionary algorithm optimization

In the post Optimization packages dozens of optimization routines canbe downloaded, here I am going to share a special optimization method:evolutionary algorithm.

Evolutionary algorithms (EAs) are search methods that take theirinspiration from natural selection and survival of the fittest in thebiological world. EAs differ from more traditional optimizationtechniques in that they involve a search from a "population" of solutions,not from a single point. Each iteration of an EA involves a competitiveselection that weeds out poor solutions. The solutions with high "fitness"are "recombined" with other solutions by swaping parts of a solutionwith another. Solutions are also "mutated" by making a small change to asingle element of the solution. Recombination and mutation are used togenerate new solutions that are biased towards regions of the space forwhich good solutions have already been seen.

This R package provides the DEoptim function which performsDifferential Evolution Optimization (evolutionary algorithm), for detailcheck http://cran.r-project.org/web/packages/DEoptim/index.html.wiki(Evolutionary algorithm)Tags - optimization

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

Page 370: Quantitative Finance Collector

Finite Element package

Recently I have been working on pricing a high dimensional (4dimension, actually) derivative via partial differencial equation (PDE),which can be solved numerically by Finite Element or Finite Differencemethod. Indeed Matlab has a PDE toolbox to use, however, as I know,this PDE toolbox can only calculate two dimensional problem, forinstance, stock and time dimension as Black Scholes model does.

For your attention, I found an excellent Finite Element package namedGetfem++ written in C++, as its webpage says, "The Getfem++ projectfocuses on the development of a generic and efficient C++ library forfinite element methods. The goal is to provide a library allowing thecomputation of any elementary matrix (even for mixed finite elementmethods) on the largest class of methods and elements, and for arbitrarydimension (i.e. not only 2D and 3D problems). " what's more interestingis this library can be linked easily to Matlab.

We know Finite Element method is an alternative to Finite Differencediscretization of the BS and other equations in the price resp. the log-price space variable. The advantage of FE is that it gives convergentdeterministic approximations of the option price under realistic, lowsmoothness assumptions on the payoff function, as e.g. for binarycontracts and in particular allow a higher rate of convergence that thatachievable with Monte Carlo simulations.

To get a deeper insight on and download open source Getfem++ pleasebe at http://home.gna.org/getfem/wiki(Finite element)Tags - finite-element , pde

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

Page 371: Quantitative Finance Collector

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 thestochastic process of interest rates. It is a type of "one-factor model" withnegative interest rate possible, despite this shortcoming, it is still appliedfor fixed income research and application due to its mean-reversioncharacteristics.

Here is another Vasicek application implemented with binomial tree inC++, the tree construction procedure is outlined in Tuckman famousbook Fixed Income Securities. By providing input parameters like theinitial short rate, speed of mean reversion, long-run average rate andvolatility, interest rate following Vasicek evolution is constructed.

For detail check this page http://math.nyu.edu/~atm262/spring06/ircm/vasicek/.

Tags - vasicek , binomial

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

Page 372: Quantitative Finance Collector

Code for Quantitative Macroeconomics

I am not a fan of Quantitative Macroeconomics, which uses standardneoclassical theory to explain business cycle fluctuations and tries toanswer 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 ofeliminating them?What can economic policy, both fiscal and monetary policy do in orderto soften or eliminate business cycles?Should the government try to do so?......

Sounds boring? I found this site when I searched "Kalman filter", clickthe following link for codes in Quant economics of differentprogramming languages.http://ideas.repec.org/s/dge/qmrbcd.htmlTags - economics

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

Page 373: Quantitative Finance Collector

Libor Market Model: Theory and Implementation source code

Libor Market Model is a term structure model applied to value andhedge exotic interest rate derivatives. The model is recognized andemployed largely because of its consistency with the popular marketmodel, Black's formula. This consistency makes the calibration processeasy as the Black's market prices for vanilla interest rate Options can beinstantly used as an input.

The purpose of this book -Libor Market Model: Theory andImplementation is to analyze the Libor Market Model in theory andimplement it practically to the evaluation of normal caps, barriers,European swaptions and ratchets, etc. The dynamic of the Libor MarketModel will be derived and the whole steps of its implementationapplying Monte Carlo simulation will be introduced. Implementation isaccomplished via several volatility and correlation formulation. Specialattention should be given when it comes to calibrate the Libor MarketModel and model the forward rate volatilities and correlations since theycould impact prices of interest rate derivatives substantially.

you can download the free c course code by leaving your email athttp://www.irina-goetsch.com/libor-market-model/app#orderwiki(LIBOR Market Model)

Tags - libor

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

Page 374: Quantitative Finance Collector

European Exchage Options

Options to exchange one asset for another arise in various contexts. Anoption to buy yen with Australian dollars is, from the point of view of aUS investor, an option to exchange one foreign currency asset foranother foreign currency asset. A stock lender offer is an option toexchange shares in one stock for shares in another stock.

Consider a European option to give up an asset worth ST at time T andreceive in return an asset worth VT, the payoff from the option ismax(VT-ST,0)A formula for valuing this option was first produced by Margrabe at hispaper “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.mhttp://www.global-derivatives.com/index.php?option=com_content&task=view&id=184wiki(Foreign exchange option)Tags - exchange , derivative , option

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

Page 375: Quantitative Finance Collector

brownian bridge simulation

QuotationSimilar to the spectral path construction method, the Brownian bridge isa way to construct a discretised Wiener process path by using the firstGaussian variates in a vector draw z to shape the overall features of thepath, and then add more and more of the fine structure. The very firstvariate z1 is used to determine the realisation of theWiener path at thefinal 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 theWiener process as it was realised at an intermediate timestep tjconditional 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 therealisations of the Wiener process at all intermediate points, in an everrefining algorithm.

here is a simulation of Brownian paths, brownian-bridge typesimulation.

Click to downloadTags - brownian-bridge

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

Page 376: Quantitative Finance Collector

Swaption valuation

A swaption is an over-the-counter derivative on a swap. Normally, theunderlying 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. Theycan be physically settled, in which case a derivative is really participatedinto at exercise date. They can be cash settled as well, in which examplethe market price of the underlying swap is cleared at maturity.

it is frequently more handy to address in terms of two common kinds ofswaption:

A payer swaption is a call option on a pay-fixed swap, the swaptionholder has the right to pay fixed rate on a swap.

A receiver swaption is a call option on a receive fixed swap, the swaptionholder has the right to receive fixed rate on a swap.

a spreedsheet showing how to price a swaption in a tree can bedownloaded at:http://www.anassabri.info/ValuingSwaptions.xlswiki(Swaption)Tags - swaption

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

Page 377: Quantitative Finance Collector

principal component analysis

Principal component analysis (PCA) is widely used for data research, forinstance, interest rate analysis, VaR calculation of porfolio, etc. What isPCA? It is a method of discovering patterns in data, and conveying thedata in such a manner to spotlight their similarities and divergences.Because patterns in data can be difficult to detect in data of highdimension, 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 thesepatterns in the data, and you compact the data, ie. by reducing thenumber of dimensions, without much loss of information.

http://www.theponytail.net/CCFEA/http://www.theponytail.net/CCFEA/lect04/lect04pc.mwiki(principal component analysis)

Tags - pca

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

Page 378: Quantitative Finance Collector

Nelson Siegel interest rate model calibration

Often we need to model the yield curve for bond pricing and riskanalysis purpose, for instance,

The valuation of products requires the modelling of the entire covariancestructure. Historical estimation of such large covariance matrices isstatistically not tractable anymore.Need strong structure to be imposed on the co-movements of financialquantities of interest.Specify the dynamics of a small number of variables (e.g. PCA).Correlation structure among observable quantities can now be obtainedanalytically or numerically.Simultaneous pricing of dierent options and hedging instruments in aconsistent framework.

There are dozens of interest rate models used by practioners, Nelson-Siegel term structure model is one of them gained popularity. here is aspreedsheet showing how to fit Extended Nelson Siegel Spot Rate withSolver.

http://janroman.dhis.org/http://janroman.dhis.org/finance/Excel/NelsonSiegelYieldCurveModel.xlswiki(Nelson-Siegel)Tags - yield , nelson-siegel

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

Page 379: Quantitative Finance Collector

Combinatorica mathematica package

Oops, first post on Mathematica, simply because I dont use it forresearch, I simply love Matlab and C++, due to their popularity andeasy-to-use. However, good news for Mathematica fans, here I found anexcellent Mathematica package named "The Combinatorica Project",which is a package written in 1989 by Steve Skiena for exercisingcomputational discrete mathematics.

here is the introductory page and downloading link, have fun and enjoynew week.http://www.cs.uiowa.edu/~sriram/Combinatorica/Tags - mathematica

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

Page 380: Quantitative Finance Collector

PSOR for American option

We often have to price the American Option with LinearComplementarity Formulation when using finite difference method. Oneof methods for solving linear complementarity problem is ProjectedSuccessive Over Relaxation (PSOR), which is iterative and tries to solvethe following formulation:

x'(Ax - b) = 0x >= 0

Ax - b >= 0using the projected SOR algorithm. Here is a sample Matlab codeshowing 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:nx(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:nx(i) = max(0,x(i)+omega*(b(i)-A(i,:)*x)/A(i,i));endendreturn

A problem with this sample code is slow computation speed, Should youare happy with C++, the following C++ code which can be called directlyin Matlab.

Click to downloadwiki(Linear complementarity problem)Tags - psor , american , option

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

Page 381: Quantitative Finance Collector

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 questionsdatabase includes various categories to choose, for instance, you canchoose to test your Risk IQ or Options IQ, level could be from as easy asthe definition of European option, black scholes to FRM test or evenmore advanced.

Take a rest & have fun.Kind reminding: today is the last day of Beijing Olimpic and closingceremony will be staging.http://www.fintools.com/docs/FinanceIQ.xlsTags - iq

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

Page 382: Quantitative Finance Collector

Floating Strike Lookback Option

The payoffs from lookback options depend on the maximum orminimum asset price reached during the life of the option. The payofffrom a European-style lookback call is the amount that the final assetprice exceeds the minimum asset price achieved during the life of theoption. The payoff from a European-style lookback put is the amount bywhich the maximumasset price achieved during the life of the optionexceeds the final asset price.

Floating Strike Lookback Options means the strike is given as theoptimal(maximum or minimum) value of the underlying asset. Matlabcode for pricing it is here:

http://www.global-derivatives.com/code/matlab/Lookback-FloatingStrike.mTags - lookback , exotic , option

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

Page 383: Quantitative Finance Collector

Markowitz Efficient Frontier stock portfolio

The efficient frontier was initiative specified by Markowitz in hisinnovative report . The theory deals an amounts of risky products andsearches 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" portfoliocan be formed in two methods:

first: for a certain level of volatility, count all portfolios that equal thisvolatility. amongst them all, choose the one with highest expectedreturn.second: for a given expected return, count all portfolios having thisexpected return. Choose the one which has the lowest volatility.

often numerical calculation is applied for optimization as we haveadditional constraints on the optimal portfolio, for instance, weightlimits, etc. below is an Excel file demonstrating many assets EfficientPortfolio can be generated by solver.

http://www.essex.ac.uk/ccfea/Teaching/Archive/200304/Quant/3%20Portfolio%20Analysis/Efficient%20Portfolio.xlswiki(Capital asset pricing model)Tags - markowitz , optimization

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

Page 384: Quantitative Finance Collector

Visualize Copulas

In those Copula codes you can get a rough idea what copula is, how toestimate and simulate it, how to test its performance, etc., to help youvisualize what on earth the copula should look like, below R code drawsplots 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.RTags - copula

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

Page 385: Quantitative Finance Collector

Java Quantlib

Many people know QuantLib, which is a free/open-source library forquantitative finance for modeling, trading, and risk management in real-life written in C++, for those people prefer Java language, they have toread & understand C++ codes and transfer them to Java code. JQuantLibis aiming at these Java-fans group,

QuotationJQuantLib is a free, open-source, comprehensive framework forquantitative finance, written in Java. It provides "quants" and Javaapplication developers several mathematical and statistical tools neededfor the valuation of financial instruments, among other features.

Is there MQuantLib for Matlab fans?Tags - quantlib , java

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

Page 386: Quantitative Finance Collector

SABR stochastic volatility model

A suitable characteristic of any local and stochastic volatility model isthat the model can yield the same prices of the vanilla options that wereapplied as inputs to the calibration of the model. failure to do so willclearly cause the model not arbitrage free and generate it nearly useless.

A substantial point of the SABR model is that the prices of vanillaoptions can be computed in almost closed form (Subject to the preciseof a series expansion). Basically it has been shown that the price of avanilla option under the SABR model is yielded by the suitable Blackmodel, 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.pdfhttp://www.axelvogt.de/axalom/SABR_Code_VB_and_C.txt

wiki(SABR Volatility Model)Tags - stochastic , volatility

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

Page 387: Quantitative Finance Collector

Copula simulation and estimation

Copula is widely used for multi-variate modeling, especially when theunderlying marginal distributions are not the same, generally speaking,Copula has at least the following application:

• Copulas provide us with a deeper understanding of dependence assuch.• Many dependence concepts, orderings and measures of associationdepend on H only through C and are in other words margin-free.• Copulas allow us to easily construct (and simulate from) multivariatedistributions with given univariate margins. This fact is particularlyuseful for stress testing.• Multivariate data can be modeled in two separate stages: Theunivariate marginals can be handled first and their dependence structurethereafter. This comes in especially handy when we either already havesome information about the margins (e.g. in the bottom-up approach inrisk management) or if finding appropriate marginal distributions isdifficult. In the latter case, we can model the margins nonparametricalyand 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=15449wiki(Copula)Tags - copula

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

Page 388: Quantitative Finance Collector

Perl Option Pricing Project

Derivatives can be valued applying a mixture of statistical models. Aformer version of the Perl module was utilized to produce marketanalysis software package. The code comprises of a Perl moduleincorporating routines to do option pricing and related computations.

Software documentationFor a fantabulous reference on derivative pricing, confer with EspenGaarder Haug (1998) Option Pricing Formulas, McGraw-Hill. Theroutines were all deduced from the pseudocode there.

http://www.kmri.com/software/popp.htmlTags - perl , option

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

Page 389: Quantitative Finance Collector

GEV distribution and density function

The role of the generalized extreme value (GEV) distribution in thetheory of extremes is analogous to that of the normal distribution (andmore generally the stable laws) in the central limit thoory for sums ofrandom varibles. The df of the GEV distribution is given by a three-parameter family: shapre, location and scale, where shape parameterdecides 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.txtwiki(Generalized extreme value distribution)Tags - gev , extreme

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

Page 390: Quantitative Finance Collector

Multivariate normal CDF

As a generalization of the normal or Gauss distribution to manydimensions we define the multinormal distribution. In statistics, themultivariate normal (mvn) is a widely-used distribution, for instance,basket option pricing, portfolio VaR analysis. Unluckily, its cumulativedistribution function (cdf) doesn't take a closed form. There are,nevertheless, amounts of techniques that numerically approximate thevalue 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.htmlwiki(Multivariate normal distribution)Tags - cdf

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

Page 391: Quantitative Finance Collector

Equity linked notes

An Equity-Linked Note (ELN) is a debt tool that differs from a normalfixed-income security due to the coupon is depend on the return of asingle stock, basket of stocks or equity index. An ELN is a principalsecured instrument Commonly configured to generate 100% of theoriginal investment at due date, but differs from a standard fixed-coupon bond because its coupon is decided by the performance of theunderlying equity.

This spreadsheet calculates the price and embedded option value ofequity linked notes, together with other option, Robeco-Reverseconvertible, for example.

http://www.ulb.ac.be/cours/solvay/farber/exceltips.htmhttp://www.ulb.ac.be/cours/solvay/farber/VUB/08%20Lecture%202.xlswiki(Equity linked note)Tags - eln

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

Page 392: Quantitative Finance Collector

Process Simulation in R

Simple demonstration codes for process simulation in R, includingBrownian motion simulation, Poisson process simulatio, Euler schemesimulation 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#CodeTags - simulation

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

Page 393: Quantitative Finance Collector

Optimization packages

Optimization models play an increasingly important role in financialdecisions. Many computational nance problems ranging from assetallocation to risk management, from option pricing to model calibrationcan be solved efficiently using modern optimization techniques. Severalclasses of optimization problems including linear, quadratic, integer,dynamic, stochastic, conic, and robust programming are oftenencountered in financial models. This site collects dozens of optimizationpackages in different programming languages, you will find one for you.

http://www.rpi.edu/~mitchj/pack.html#abacuswiki(Optimization)Tags - optimization

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

Page 394: Quantitative Finance Collector

Real Option Models in Valuation

Real Option good example in Corporate Finance

This example approximates the economic value of the option toextend in an investing project. it can also be used to appraise the value ofstrategic options.

This example calculates the value of the option to postpone aninvestment project.

This example estimates the value of fiscal tractability, i.e, thesustenance of extra debt capability or back-up funding.

This example estimates the value of the option to give up a project orinvestment.

Real Option Models in Valuation

A example that applies option pricing to measure the equity in acompany; most well suitable for largely levered firms in trouble.

A model that applies option pricing to evaluate a natural resourcefirm; useful for measuring oil or mining companies.

A model that applies option pricing to appraise a product patent oroption; useful for valuing the patents that a company may declare.

http://pages.stern.nyu.edu/~adamodar/New_Home_Page/spreadsh.htm#optincfwiki(Real option)Tags - real-option , option

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

Page 395: Quantitative Finance Collector

Brinson performance attribution

Performance attribution is used as a way to check the relativeperformance of portfolio against selected Benchmark, the difference ofwhich is called active return. Brinson method decomposes active returnto asset selection effect and industry selection effect, helping investorrealize where the active return is from, which asset or industry has abiggest contribution to the active return of portfolio, ect.

http://www.barra.com/products/spreadsheets/stockselection.xlswiki(Performance attribution)Tags - performance

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

Page 396: Quantitative Finance Collector

R-code for Vasicek estimation

A short-rate model is usually calibrated to some initial structures in themarket, typically the initial yield curve, the caps volatility surface, theswaptions volatility surface, and possibly other products, thusdetermining 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 analyticaloption prices can be obtained and easily calculatied, however, negativeshort 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

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

Page 397: Quantitative Finance Collector

Valuing Warrants under dilution

Usually, when a call option on a stock is exercised, the party with theshort position acquires shares that have already been issued and sellsthem to the counterparty, however, warrants, executive stock options aswell, are options that work slightly differently, they are written by acompany on its own stock, when they are exercised, the company issuesmore of its own stock and sells them to the option holder for the strikeprice. the exercise of a warrant therefore leads to an increase in thenumber of shares of the company's stock that are outstanding, which hasthe dilution effect on the price of warrant as a result.

often we ignore this dilution effect as it might be small, here is aspreedsheet model for valuing options that result in dilution of theunderlying stock if you do want to consider it.

http://pages.stern.nyu.edu/~adamodar/New_Home_Page/spreadsh.htm#basicoption

Tags - warrant

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

Page 398: Quantitative Finance Collector

halton and sobol sequences

I couldnot stop using Quasi Monte Carlo simulation for derivativepricing, especially when the problem to solve is a low dimensional one.Among low discrepancy random numbers, Halton sequences and sobolsequences are two of my favorites, although sometimes I compare othersequences like Faure, Haselgrove, and Niederreiter as well. Unlikepseudo-random numbers, low-discrepancy numbers aim not to beserially uncorrelated, but instead to take into account which points in thedomain to be sampled have already been probed. Low-discrepancynumbers have become a popular tool for financial Monte Carlocalculations since the early 1990s.

http://www.math.uic.edu/~hanson/mcs507/cp4f04.htmlwiki(Low-discrepancy sequence)

Tags - halton , sobol

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

Page 399: Quantitative Finance Collector

Beasley-Springer-Moro inverse normal

Once you get uniform random numbers, how to inverse that to normalrandom numbers require numerical technique, Moro is one of suchtechniques,Quotationmy favourite method for constructing standard normal variates is thehighly sophisticated interpolation formula by Peter Acklam for theinverse cumulative normal distribution. A very crude way to quicklyconstruct (approximately) normally distributed variates is to add up 12uniform variates, and subtract 6. For any reasonable application, I wouldalways use either Peter Acklam’s method, or Boris Moro’s interpolationformula.

http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=14234&objectType=fileTags - normal , monte carlo

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

Page 400: Quantitative Finance Collector

Barrier Option Calculator

tran(This program can calculate values and greeks for plain vanillaoptions as well as single and double barrier options with or withoutrebate. Calculations are performed within the standard Black-Scholesmodel. For plain vanilla and single barrier options, the calculation ispurely analytical. Double barrier options are approximated using aFourier series approximation, unless volatility is low. For low volatilityan alternative series expansion is used.)

http://www.neumann.nl/~dimitri/pricing.htmlwiki(barrier option)Tags - barrier , calculator , option

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

Page 401: Quantitative Finance Collector

Monte Carlo Chooser Option

Chooser option gives the holder the right to choose it is a call or putoption at a prescriped strike price and date. here is a sample spreedsheetpricing chooser option with Monte Carlo simulation.

http://fisher.utstat.toronto.edu/sjaimung/courses/2008-2009/sta2502/main.htm

Tags - monte carlo , chooser , option

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

Page 402: Quantitative Finance Collector

State space model toolbox

Another MATLAB toolbox for time series analysis using state spacemodels. Supports fully interactive model construction with MATLABobjects and efficient Kalman filter backend implemented in c.

http://sourceforge.net/projects/ssmodels/wiki(kalman filter)Tags - filter

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

Page 403: Quantitative Finance Collector

Sobol and Generalised Faure sequences

Low discrepancy sequences are highly recommended for low-dimensional Monte Carlo simulation, they have been proved to be ableto improve convergence speed, accuracy, etc. take a trial.

http://web.wits.ac.za/NR/rdonlyres/96ECC07E-AE3C-4706-94F8-C1A53011AF38/0/searlecode.zipwiki(Low-discrepancy sequence)Tags - sobol , faure

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

Page 404: Quantitative Finance Collector

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 formulaonline.

http://www.montegodata.co.uk/Consult/Derivative/Derivatives.html

Tags - derivative , calculator , option

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

Page 405: Quantitative Finance Collector

Code for Financial Modeling Under Non-GaussianDistributions

This site stores matlab codes accompanying the book Financial ModelingUnder Non-Gaussian Distributions, a wonderful and easy to read book,which was used by my professor last semester, you can imagine howmuch this site has helped me, Cheers.

http://www.hec.unil.ch/MatlabCodes/Tags - matlab

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

Page 406: Quantitative Finance Collector

Black Scholes in Multiple Languages

Black Scholes formula is widely used for vanilla option pricing, which isalso easy to code, but how many language can you use? I can do it inMatlab, C++, GAUSS, VBA, PHP. Guess what, this site collects morethan 30 languages, have fun!

http://www.espenhaug.com/black_scholes.html

wiki(black scholes)Tags - black scholes

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

Page 407: Quantitative Finance Collector

Calibration of a binomial tree to the volatility surface

How to calibrate a binomial tree to the volatility surface implied frommarket option prices. Code in Matlab.

http://theponytail.net/CCFEA/

wiki(Volatility smile)Tags - volatility , smile , binomial

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

Page 408: Quantitative Finance Collector

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 FinancialOption on EquityBinary Tree method to Price Options on EquityMonte Carlo pricer of ExoticsMonte Carlo Pricer of American Calls and PutsMonte Carlo Pricer of European Barrier, Knock in and out OptionsMonte Carlo Pricer European Spread OptionsMonte Carlo Pricer of Interest Rate Derivatives (One factor)Monte Carlo Pricer Ho Lee ModelMonte Carlo Pricer Hull White ModelMonte Carlo Pricer Black Derman Toy ModelMonte Carlo Pricer Brace Gatarek Musiela / Jamishidian ModelMonte Carlo pricer of exotics with constant Jump-DiffussionMonte Carlo Pricer of Barrier, Knock in and out Options with Jump-DiffusionMonte Carlo Pricer European Spread Options with Jump-Diffusion

Table with Java sources

Closed expressions and Approximate Models for various FinancialOption on EquityBinary Tree method to Price Options on EquityMonte Carlo pricer of ExoticsMonte Carlo Pricer of American Calls and PutsMonte Carlo Pricer of European Barrier, Knock in and out OptionsMonte Carlo Pricer European Spread OptionsMonte Carlo Pricer of Interest Rate Derivatives (One factor)Monte Carlo Pricer Ho Lee Model

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

Page 409: Quantitative Finance Collector

Monte Carlo Pricer Hull White ModelMonte Carlo Pricer Black Derman Toy ModelMonte Carlo Pricer Brace Gatarek Musiela / Jamishidian ModelMonte Carlo pricer of exotics with constant Jump-DiffussionMonte Carlo Pricer of Barrier, Knock in and out Options with Jump-DiffusionMonte Carlo Pricer European Spread Options with Jump-Diffusion

http://www.javaquant.net/downloads.htmlwiki(Black Derman Toy)Tags - bdt , monte carlo

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

Page 410: Quantitative Finance Collector

download option price data from Yahoo

This R program can be used to download option price data from Yahooto a data frame and to plot the corresponding implied-volatility smiles.

http://www.fam.tuwien.ac.at/~mkeller/Tags - download , data , option

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

Page 411: Quantitative Finance Collector

Famas Return Decomposition

A sample spreedsheet demonstrating how to decompose Fama's returninto several sources.

http://clem.mscd.edu/~mayest/FIN4600/Files/famadcmp.xls

Tags - fama

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

Page 412: Quantitative Finance Collector

Receiver Swaption Price

Calcualtes the price of a receiver swaption (bp).

http://www.vbnumericalmethods.com/finance/

wiki(Swaption)Tags - swaption

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

Page 413: Quantitative Finance Collector

Quantile Regression

Quantile regression is a statistical technique intended to estimate, andconduct inference about, conditional quantile functions. Just as classicallinear regression methods based on minimizing sums of squaredresiduals enable one to estimate models for conditional mean functions,quantile regression methods offer a mechanism for estimating modelsfor the conditional median function, and the full range of otherconditional quantile functions. By supplementing the estimation ofconditional mean functions with techniques for estimating an entirefamily of conditional quantile functions, quantile regression is capable ofproviding a more complete statistical analysis of the stochasticrelationships among random variables.

http://www.econ.uiuc.edu/~roger/research/rq/rq.htmlwiki(Quantile regression)Tags - regression

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

Page 414: Quantitative Finance Collector

calibration of the Heston SV model

http://www.theponytail.net/CCFEA

wiki(heston model)

Tags - hestonvolatility , calibration

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

Page 415: Quantitative Finance Collector

CDO Pricing in Gaussian Copula

CDO prices with Monte Carlo simulation includes the creation of roadsin the sample correlation preset times. This defect is sometimes used tocalculate 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

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

Page 416: Quantitative Finance Collector

simulating a two-dimensional variance gamma process withClayton dependence structure

Simulates two dependent variance gamma processes without drift,dependence is given by Clayton Levy copula with parameters theta andrho.

http://people.math.jussieu.fr/~tankov/florence/

wiki(Variance-gamma distribution)Tags - copula , levy

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

Page 417: Quantitative Finance Collector

EWMA Volatility

VB function to calculate 'exponentially weighted moving average'volatilites (=RiskMetrics volatility forecasting) with or without assuminga zero mean return.

http://www.andreassteiner.net/performanceanalysis/?Downloads:VBA

wiki(EWMA)Tags - volatility

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

Page 418: Quantitative Finance Collector

Black Scholes Implied Volatility

Calculates the implied volatility of an european option using bi-sectionmethod. This function uses the super black scholes function.

http://www.vbnumericalmethods.com/finance/

wiki(Implied volatility)Tags - black scholes , volatility

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

Page 419: Quantitative Finance Collector

Monte Carlo Pricer Brace Gatarek Musiela / JamishidianModel

Table with Java sources

Closed expressions and Approximate Models for various FinancialOption on EquityBinary Tree method to Price Options on EquityMonte Carlo pricer of ExoticsMonte Carlo Pricer of American Calls and PutsMonte Carlo Pricer of European Barrier, Knock in and out OptionsMonte Carlo Pricer European Spread OptionsMonte Carlo Pricer of Interest Rate Derivatives (One factor)Monte Carlo Pricer Ho Lee ModelMonte Carlo Pricer Hull White ModelMonte Carlo Pricer Black Derman Toy ModelMonte Carlo Pricer Brace Gatarek Musiela / Jamishidian ModelMonte Carlo pricer of exotics with constant Jump-DiffussionMonte Carlo Pricer of Barrier, Knock in and out Options with Jump-DiffusionMonte Carlo Pricer European Spread Options with Jump-Diffusion

http://www.javaquant.net/downloads.htmlwiki(LIBOR Market Model)Tags - libor , bgm

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

Page 420: Quantitative Finance Collector

Monte Carlo Pricer of Barrier, Knock in and out Options withJump-Diffusion

how to price barrier options with jump-diffusion by monte carlosimulations, codes are in Java language.

http://www.javaquant.net/downloads.html

wiki(Barrier option)Tags - barrier , option

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

Page 421: Quantitative Finance Collector

Outperformance Options Price

Computes the price of an outperformance option.

http://www.vbnumericalmethods.com/finance/

wiki(Exotic option)Tags - outperformance , option

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

Page 422: Quantitative Finance Collector

Rainbow Option Price

Calculates the price of a (two-coloured rainbow) option delivering thebest of two risky assets or cash.

http://www.vbnumericalmethods.com/finance/

wiki(Rainbow option)Tags - rainbow , option

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

Page 423: Quantitative Finance Collector

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.htmlwiki(Kalman filter)Tags - filter

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

Page 424: Quantitative Finance Collector

Stochastic simulation using MATLAB

This tutorial contains Matlab code and documentation for a seminar onstochastic simulation. The program package demonstrates basictechniques for effective simulation and visualization of variousstochastic processes and random mechanisms. We try to emphasizemethods that are natural given the matrix and vector oriented nature ofMatlab. The goal is that users of this material find inspiration and ideasto prepare their own code for a particular application involving randomdynamics.

http://www.math.uu.se/research/telecom/software/Tags - simulation

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

Page 425: Quantitative Finance Collector

CONVERTIBLE BOND PRICING MODEL

A simple spreadsheet to price convertible bond based on Espen GaarderHaage's binomial tree model which was originally developed byGoldman-Sachs.

http://www.yieldcurve.com/Mktsoftware/excelCB.htm

wiki(Convertible bond)Tags - convertible bond

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

Page 426: Quantitative Finance Collector

matlab tips and tricks

Great site for anyone who wants to optimize his matlab file, speed upcomputer, have fun.

http://www.ee.columbia.edu/~marios/matlab/matlab_tricks.html

wiki(matlab)Tags - matlab

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

Page 427: Quantitative Finance Collector

American Options via Monte Carlo Simulations

Sample code to price american put option with least square Monte Carlosimulation.

http://www.quantcode.com/modules/mydownloads/visit.php?cid=11&lid=54Tags - monte carlo , option

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

Page 428: Quantitative Finance Collector

Risk Neutral Default Probability

A spreadsheet that demonstrates risk-neutral default probabilities whenpricing bonds with embedded options. We illustrate the Martingalepricing process under certain assumptions.The user inputs the bond parameters and an assumed recovery rate foreach bond.The spreadsheet computes the default probability.The accompanying spreadsheet illustrates in simple terms how the risk-neutral probabilitiesare obtained.

http://www.yieldcurve.com/Mktsoftware/excelRN.htmwiki(risk neutral)Tags - default

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

Page 429: Quantitative Finance Collector

UK Gilt zero-coupon yield curve

This spreadsheet demonstrates constructing a zero-coupon yield curvefrom market gilt yields, using the basis spline methodology andapproach.A technical description of the methodology appeared in the book"Capital Market Instruments" by Moorad Choudhry et al (FT PrenticeHall 2001).

http://www.yieldcurve.com/Mktsoftware/excelYC.htmwiki(yield curve)Tags - yield

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

Page 430: Quantitative Finance Collector

Asian Option Pricing

Here is the MATLAB implementation of the pricing of Asian optionsfrom 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

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

Page 431: Quantitative Finance Collector

Matlab-GUI equity derivative calculator

This is simple Matlab-GUI files i wrote learning to code an equityderivative calculator, options include:

European optionAmerican optionAsian optionIndex futureCash-or-nothing optionAsset-or-nothing optionLookback optionChooser optionCompound optionExchange optionPower option

Unzip the EquityDerivGUI file to a directory of your local computer,change the directory to be the current directory of your matlab, run mainfile DerivativeGui.m. tested under Matlab7.0.1.

Click to downloadTags - derivative , matlab , gui

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

Page 432: Quantitative Finance Collector

Mersenne Twister random number generator

SFMT is a new variant of Mersenne Twister (MT) introduced by MutsuoSaito and Makoto Matsumoto in 2006. The algorithm was reported atMCQMC 2006. The article will apper in the proceedings ofMCQMC2006. (see Prof. Matsumoto's Papers on random numbergeneration.) 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 asmulti-stage pipelining and SIMD (e.g. 128-bit integer) instructions. Itsupports 32-bit and 64-bit integers, as well as double precision floatingpoint as output.

http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.htmlwiki(Mersenne Twister)Tags - random

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

Page 433: Quantitative Finance Collector

Singular value decomposition

The singular value decomposition of MxN matrix A is its representationas A = U W V T, where U is an orthogonal MxM matrix, V - orthogonalNxN matrix. The diagonal elements of matrix W are non-negativenumbers in descending order, all off-diagonal elements are zeros.

The matrix W consists mainly of zeros, so we only need the firstmin(M,N) columns (three, in the example above) of matrix U to obtainmatrix A. Similarly, only the first min(M,N) rows of matrix V T affect theproduct. These columns and rows are called left and right singularvectors.

http://www.alglib.net/matrixops/general/svd.php

wiki(Singular value decomposition)Tags - matrix

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

Page 434: Quantitative Finance Collector

Normal Inverse Gaussian(NIG) and other stochastical volmodel

stochastic volatility / other models

NIG_tiny_withDLL.zipNormal Inverse Gauss option pricer (with Esscher transform

correction), Excel + DLL, anda Maple worksheet with short explanations, cf Schoutens book "Levy

Proccess in Finance"

VG_Pricer_short(Maple).pdfA 'brute' option pricer for the Variance Gamma model (Madan, Carr,

Chang 1998) in Maple

VG_small.zipVariance 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

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

Page 435: Quantitative Finance Collector

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.htmlTags - calculator , option

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

Page 436: Quantitative Finance Collector

Monte Carlo Simulation Spread Options

an example of code used to price a spread option using Monte Carlosimulations (Haug).

http://www.mathworks.com/matlabcentral/fileexchange/82

wiki(Spread option)Tags - spread , monte carlo , option

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

Page 437: Quantitative Finance Collector

Matlab code for 2-factor CIR in simulations

Jackknifing Bond Option Prices. Programs and data used in thepaper: Swap and LIBOR Rates; Matlab code for 1-factor CIR insimulations; Matlab code for 1-factor CIR in applications; Matlab codefor 2-factor CIR in simulations; Matlab code for 2-factor CIR inapplications

http://www.mysmu.edu/faculty/yujun/research.htmlhttp://www.mysmu.edu/faculty/yujun/Research/jackknifecir1foption_sim.m

Tags - cox ingersoll ross , cir

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

Page 438: Quantitative Finance Collector

CompEcon Toolbox for Matlab

CompEcon is a set of MATLAB functions for solving a variety ofproblems in economics and finance. The library functions includerootfinding and optimization solvers, a integrated set of routines forfunction approximation using polynomial, splines and other functionalfamilies, a set of numerical integration routines for general functions andfor common probability distributions, general solvers for OrdinaryDifferential Equations (both initial and boundary value problems),routines for solving discrete and continuous time dynamic programmingproblems, and a general solver for financial derivatives (bonds, futures,options).

http://www4.ncsu.edu/~pfackler/compecon/toolbox.htmlTags - matlab

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

Page 439: Quantitative Finance Collector

Quasi-maximum likelihood

Quasi-maximum likelihood toolbox in matlab.

http://www.mathtools.net/files/net/qmle.zip

wiki(maximum likelihood)Tags - mle

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

Page 440: Quantitative Finance Collector

A Matlab Toolbox for Univariate GARCH estimation

The primary feature that differentiates GARCHKIT from other GARCHimplementations in Matlab is its ability to incorporate covariates into thesecond moment. The current version of GARCHKIT, 1.0b3, allowsunivariate ARMA(P,Q)-GARCH(R,S) estimation and simulation usingmaximum 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

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

Page 441: Quantitative Finance Collector

weighted covariance matrix

Computes a weighted covariance matrix and associated values

http://www.stanford.edu/~wfsharpe/mat/mlfn.htm

wiki(Covariance)Tags - covariance

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

Page 442: Quantitative Finance Collector

On-Line Options Pricing Probability Calculators

Black-Scholes pricing analysis -- Ignoring dividends: Lets you examinegraphically how changes in stock price, volatility, time to expiration andinterest rate affect the option price, time value, the derived "Greeks"(delta, gamma, theta, vega, rho) and the probability of the option closingin the money. For simplicity, dividends are ignored so you just specifythe time to expiration in days rather than entering specific dates.

more at http://www.hoadley.net/options/calculators.htm

Tags - black scholes , calculator , option

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

Page 443: Quantitative Finance Collector

Copula toolbox for Matlab

An aggregation of Matlab routines that for research on copulas forfinancial 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 randomnumber generators for numerous basic bivariate copulas, including theClayton, Gumbel, Normal, Student's t, Frank, Plackett and symmetrisedJoe-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

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

Page 444: Quantitative Finance Collector

A lightweight C++ library for quantitative financeapplications

What is Terreneuve? Simply: "A lightweight C++ library for quantitativefinance applications."

In more detail, Terreneuve is our team name for the project in the Fall2005 Computing in Finance course at NYU's Courant Institute Masters inMath Finance. Working from this specification we hope to design auseable C++ library for some important quantitative financeapplications.

Our target audience (aside from our prof ;-)) is students in quantitativefinance 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) libraryto the quantlib project.

http://terreneuve.sourceforge.net/

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

Page 445: Quantitative Finance Collector

C++ Financial Algoritms (Financial Numerical Recipes)

QuotationIn finance, there are areas where formulas tend to get involved.Sometimes it may be easier to follow an exact computer routine. I havemade some C++ subroutines that implements common algoritms infinance. Typical examples are option/derivatives pricing, term structurecalculations, mean variance analysis. These routines are presentedtogether with a good deal of explanations and examples of use, but it isby 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 isshould provide a good deal of useful algorithms for people workingwithin the field of finance.

Book and Code are at http://finance-old.bi.no/~bernt/gcc_prog/index.htmlTags - finance

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

Page 446: Quantitative Finance Collector

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 whichrely on simulation techniques or advanced modeling, more athttp://www.global-derivatives.com/index.php?option=com_content&task=view&id=184Tags - derivative , option

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

Page 447: Quantitative Finance Collector

Archive of Finance Econometrics GAUSS Matlab Code

Procedures and necessary declaration files to calculate fitted optionprices using Fourier Inversion methods as in Bates (RFS 1996). Thisallows for a variety of possible risk neutral diffusions which canaccommodate stochastic volatility, jumps, as well as correlation betweenthe volatility process and underlying asset.

more at http://www.cameronrookley.com/gtoml/archive.html

Tags - gauss

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

Page 448: Quantitative Finance Collector

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

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

Page 449: Quantitative Finance Collector

Design Patterns and Derivatives Pricing

Design patterns are the cutting-edge paradigm for programming inobject-oriented languages. Here they are discussed, for the first time in abook, in the context of implementing financial models in C++. Assumingonly a basic knowledge of C++ and mathematical finance, the reader istaught how to produce well-designed, structured, re-usable code viaconcrete examples. Each example is treated in depth, with the whys andwherefores of the chosen method of solution critically examined. Part ofthe book is devoted to designing re-usable components that are then puttogether to build a Monte Carlo pricer for path-dependent exotic options.Advanced topics treated include the factory pattern, the singletonpattern and the decorator pattern. Complete ANSI/ISO-compatible C++source code is included on a CD for the reader to study and re-use andso 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 athttp://www.markjoshi.com/design/Tags - derivative

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

Page 450: Quantitative Finance Collector

Heston Stochastic Volatility

Online Closed form and Monte Carlo simulation for option underHeston Stochastic Volatility.

http://www.math.nyu.edu/ms_students/lw429/calculator.htm

wiki(Heston model)Tags - heston , volatility

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

Page 451: Quantitative Finance Collector

A Course in Derivative Securities: Introduction to Theory andComputation

A textbook for a second course in derivatives at the undergraduate orMBA level or for a first course in a financial engineering program. Theoption pricing functions in the book (including worksheet examples andthe VBA source code) are available in this Excel workbook.

http://www.kerryback.net/Tags - derivative

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

Page 452: Quantitative Finance Collector

Spreadsheet Programs

To help you in finding the spreadsheet that you might want, I havecategorized the spreadsheets into the following groups:1. Corporate finance spreadsheets: These spreadsheets are most useful ifyou are interested in conventional corporate financial analysis. Itincludes spreadsheets to analyze a project's cashflows and viability, acompany'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 findspreadsheets that allow you toa. Estimate the right discount rate to use for your firm, starting with therisk premium in your cost of equity and concluding with the cost ofcapital for your firm.b. Convert R&D and operating leases into capitalized assetsc. estimate the right capital expenditures and diagnose the terminalvalue assumptions to see if they are reasonable.3. Valuation Model Reconciliation: In this section, you will findspreadsheets that reconcile different DCF approaches - FCFE versusDividend Discount Model, FCFE versus FCFF model, EVA versus Costof capital and Net Debt versus Gross Debt Approaches.4 . Big-picture valuation spreadsheets: If you are looking for onespreadsheet to help you in valuing a company, I would recommend oneof these 'ginzu' spreadsheets. While they require a large number ofinputs, they are flexible enough to allow you to value just about anycompany. You do have to decide whether you want to use a dividend,FCFE or FCFF model spreadsheet. If you have no idea which one willwork for you, I would suggest that you try the "right model" spreadsheetfirst.5 . Focused valuation spreadsheets: If you have a clear choice in terms ofmodels - stable growth dividend discount, 2-stage FCFE etc. - you candownload a spreadsheet for the specific model in this section.......

http://pages.stern.nyu.edu/~adamodar/New_Home_Page/spreadsh.htmTags - excel

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

Page 453: Quantitative Finance Collector

SAS for Financial Engineers

SAS for Financial Engineers:1 – Introduction2 – Data Management3 – Financial Modeling(Important PROCs and Advanced PROCs: IML,SQL)4 – Advanced Techniques (SAS Macro and other programmingtechniques)

http://faculty.haas.berkeley.edu/peliu/computing/

Tags - sas , finance

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

Page 454: Quantitative Finance Collector

MatLab for Financial Engineers

MatLab for Financial Engineers:1-Basics2–Statistical Analysis3–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

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

Page 455: Quantitative Finance Collector

Pricing Derivatives Securities using MATLAB

A Zip file containing the examples that were used in the MathWorkswebinar: "Pricing Derivatives Securities using MATLAB".

Highlights:* Pricing a portfolio of vanilla options using Black-Scholes, a BinomialTree 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=14508Tags - derivative , matlab

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

Page 456: Quantitative Finance Collector

Parameters estimation of GARCH model

Parameters estimation of GARCH model.

http://w3.uniroma1.it/passalac/buffer/GARCH.xls

wiki(GARCH)Tags - garch

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

Page 457: Quantitative Finance Collector

Financial Model Library by Thomas Ho

Introduction:

* "Financial Model Library" is a library of financial models in an Excelspreadsheet. The purpose of the library is to promote usage and betterunderstanding of financial models.

* All financial models in this section can be used free of charge and canbe distributed.

* We hope that you can also contribute to the library of financialmodels by submitting your Excel model spreadsheet in the formatconsistent with our models. The rules for submission are similar to thatof a Journal. That is:

o We maintain the right to reject your submission or suggesto revisions of the modelso We reserve the copyright of the Excel spreadsheet model.

* The site is not responsible for any errors in the models and copyrightviolation of any models submitted.

http://www.thomasho.com/mainpages/analysoln.aspTags - library

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

Page 458: Quantitative Finance Collector

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, ChinaResearcher, ChinaSkills: 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 inmath finance focusing on derivative pricing, quantitative trading andquantitative risk management. Several features:1, one of the few mainly quant oriented blogs;2, received on average 500~600 unique visitors and 1200+ pageviews perday;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.comQuantitative Finance Collector is a Top Site in Quantitative FinanceReview This Site

Quantitative Finance Collector is a Top Site in Quant

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

Page 459: Quantitative Finance Collector

Review This Site

Tags - blog

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

Page 460: Quantitative Finance Collector

www.feedbooks.comFood for the mind

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