# Learning Finance with Mathematica

## Background

My math background is strong by CS standards, probably normal by mathematica standards. (i.e. familiarity with real analysis, linear algebra, managed to read the proof of the prime number theorem :-) )

The goal here is NOT to start a hedge fund of sorts; it's mainly to pick up the basics of financial / stock market background (but it's much more fun when I'm playing with real data / writing programs rather than just reading a textbook.)

I want to play around with learning the basics of finance (and writing some serious code in Mathematica).

Ideally, I want to "learn by doing" -- i.e. rather than just read textbook formulas, I would like to:

• play with real world stock data

• implement the various definitions / algorithms / functions and see how they work

Looking around, the best I have found is this book:

Computational Financial Mathematics using MATHEMATICA®: Optimal Trading in Stocks and Options

Seems like the most highly recommended

However, since I'm clueless, I would like to get some feedback (and suggestions for other resources to use for learning.)

Thanks!

-
Just a warning: book recomendations are a tuchy subject on the SE family of sites. See here. There was however already a book recommendation on mma.se that didn't get closed here, so perhaps this are a bit more relaxed here:) – Ajasja Jul 13 '12 at 8:22
@Ajasja: Is there a way I can modify the syntax of my post to avoid it being closed? – user1602 Jul 13 '12 at 9:06
I would just wait and see if somebody has a problem with this Q. Personally I'm not against book recommendations, since good books don't change that much in Mathematica world. – Ajasja Jul 13 '12 at 9:12
I recommend MathEstate.com, just brilliant. Its authors know Mathematica very well and have more original insights into finance than anything you'll find in conventional financial engineering. As for books its hard to find anything on financial engineering that doesn't start and end with unfounded assumptions whether the authors know Mathematica or not. So I think you should stick with basics. Taleb's "Dynamic Hedging" - comprehensive, his best book by far. Mandelbrot's, "(Mis)behavior of Markets" A. Brown's "Poker Face of Wall Street" & "Red Blooded Risk". Thorp's "Beat the Market". – Jagra Jul 13 '12 at 12:59
Just a follow up, How could I forget, John Kelly's seminal 1956 paper "A New Interpretation of Information Rate" indispensable, and amazing how so few in financial engineering have ever heard of it. Thorp, who invented Black Scholes long before the Black and Scholes did and developed Delta hedging, arguably the 1st quantitative approach relied heavily on Kelly as do PIMCO, Brown, and most frequentist oriented quantitative strategies. – Jagra Jul 13 '12 at 13:57
show 8 more comments

I own a copy of Modelling Financial Derivatives with Mathematica by William Shaw. I think it was a ground-breaking book for its time. However, here are some issues you should be aware of:

• It was published in 1998 and is based on Mathematica version 3. We are now at 8, anticipating 9. Much of the graphics code he uses is now obsolete (eg GraphicsGraphics).
• Much of the functionality he builds in the book is now built-in to Mathematica itself. See the list of functions here.

Chapter 3 is a nice intro to the mathematical preliminaries of derivatives, but there will be better ones in more recent introductory texts that are not specific to Mathematica.

My general concern about both Shaw's book and the subsequent Mathematica implementations of these pricing algorithms is that they are, in the end as far as I can tell, based on an assumption of Gaussian noise in the differential equation defining the pricing equation. This is still the standard approach in many workplaces, but especially since the crisis, the deviation of reality from Gaussian-based models has generated some disquiet in the profession. (This has been directed more at Gaussian copulas than the underlying Black-Scholes model, but it is possible that the industry is going to start moving off in another direction away from the standard methods encapsulated in the Mathematica functionality.) I am not close enough to the recent literature on financial engineering specifically to know exactly how this is playing out yet.

I do not own the book by Stojanovic you referenced in your question but looking at the contents pages online, I do not see anything there that is not now included directly in Mathematica with version 8. Again, this book came out in 2002, so it predates Mathematica's finance functionality as well as its dynamic functionality (Manipulate and friends). And again, it is all based on Black-Scholes and Gaussian noise and doesn't go beyond that to include consideration of fat-tailed innovations. (NB: this is something that Mathestate.com, mentioned in comments, gets right - there is lots of discussion of Levy-stable and other heavy-tailed distributions. So perhaps you are better off starting there than with a book.)

I think you will be better off getting a recent book on financial engineering and pricing, and practice implementing things in Mathematica from there, bearing in mind how much is already built in. I particularly admire Janet M Tavakoli on structured finance.

To summarise, I don't think there is currently a good book on financial engineering that addresses Mathematica's current functionality, but I would be delighted to be proven wrong. Perhaps this is a market niche for someone.

One place you might want to consider for thoughts and ideas is the "Cutting Edge" column in Risk magazine. That stuff is pretty advanced, but it gives you a sense of where practitioners, rather than academics, are going. Also have a look at the sister SE for Quantitative Finance, but note that software questions are offtopic there, at least last time I looked.

-
Is Gaussian still assumed? A lot of the papers I've read in quantitative finance use either Student-t or Cauchy or power-law distributions — basically, anything that has a fat tail and these were all from between 2000-now – rm -rf Jul 13 '12 at 23:54
@R.M they are assumed in the two books referenced - certainly Shaw and as far as I can tell, Stojanovic. My impression (and I am not working in an investment bank) is that many shops still just go with the Gaussian. The VaR built into Basel II pretty much assumes it too. – Verbeia Jul 14 '12 at 0:01
Heh, everybody loves Gaussian... until it goes wrong :) – rm -rf Jul 14 '12 at 0:13
Fyi, also check the piece in Wired on the failure of Li's copula-based correlation model - called something like "The formula that brought down Wall Street" (hyperbolic title of course - no single model is to blame and models don't make decision, fund managers do). – alancalvitti Oct 12 '12 at 2:51
Fyi, also recommend the nontechnical books by Taleb, especially Fooled by Randomness – alancalvitti Oct 12 '12 at 2:52
show 3 more comments

Here are some links I collected in my answer to the post Where can I find examples of good Mathematica programming practice?. The first link exposes quite well the new functionalities of Mathematica in this field.

Finance (some CUDA examples also)

I agree with Verbeia when she recommends to learn by doing, this is a path I followed and it still pays off. The step by step discovery style of programming in a notebook where you can mix instructions, intermediate results and graphics (plus all the built-in functions like Interpolate or NExpectation) makes it easier to develop new stuff compared to other languages. When you see that something works you copy all important instructions and pack them in a function.

-

I just wrote a book on financial engineering that uses Mathematica heavily. The publisher (World Scientific) says it should be available for purchase within a week or two. I have taught risk management and asset pricing and derivatives with these materials for the past few years at NYU-Poly. The point of the book is precisely to do lots of projects, the learn-by-doing approach you want. Here's more info: http://financialhacking.com

-
 What assumptions does your book make -- Gaussian noise? – murray Oct 8 '12 at 14:33

Most of the financial modeling/Mathematica books I've seen are intended to (1) provide theorical insights and Mathematica based tools to price "exotic" derivatives, and/or (2) to show how to use Mathematica to develop derivative trading strategies. Very helpful for experienced quants. Not the best way to learn about investing.

Successful investing requires the skillful combination of five aspects of finance. You should know how: 1) financial markets work, 2) different financial instruments are priced, 3) assets can be combined in a portfolio to meet a particular investment objective, 4) risk is measured and and managed, and 5) investment success is measured and monitored. Each of these five areas require practical knowledge and also involve important theoretical questions. (In spite of the fact that two Nobel prices have been awarded for work in categories 2 and 3, research is ongoing in each of the five areas). Mathematica is a useful tool for the student and practitioner in each area.

Although Mathematica has sophisticated functions for valuing various instruments, if you want to learn about finance, it's better to write your own financial functions so you know how pricing works.

## 1. PRICING FINANCIAL INSTRUMENTS (What's it worth?)

Bonds are a great place to start learning about finance. The price of a treasury bond is just the sum of the present values of each of its coupon payments and its principal at maturity. Moreover, this "sum of the present value of future cashflows," introduces a foundational concept of finance called the law of one price. The law of one prices says everything that has the same future cash flows MUST have the same price (or the differences will be arbitraged away). Therefore, any package of financial instruments that has the same future cashflows as a certain bond must have the same price as that bond.

Mathematica makes it relatively easy to learn about bond pricing and the surprisingly many and more subtle related concepts of duration, curvature, yield to maturity, etc.

### 1a. Fixed Income Securities

The present value of a future cash payment is equal to:

presentValue = cashPayment/(1 + annualInterestRate)^(timeInYearsToPayment)


This means that, if you know the face value, coupon payments, and time to maturity of a bond that won't default (you can be sure the payment will really happen), you can calculate it's price in any environment (meaning when bonds are trading at any particular yield). For example:

Treasury Bonds (which, in theory, will never default)

The price of a US Treasury bond is:

So, Treasury bonds are really mathematical entities. And you can learn about them with Mathematica by making and playing with models. For example, bond prices are a simple but interesting function of yield:

This price-yield curve is the essential element of bond pricing. The curve itself a function of bond maturity, coupon, coupon frequency, and yield. Its slope (called bond duration) is a measure of the bond's sensitivity to interest rate changes, and since the curve isn't flat, duration is also a function of interest rates (curvature). This gets complicated, but bonds are managed in terms of duration and curvature.

The Yield Curve

Bonds are actually priced from a yield curve, either the Treasury yield curve, or one based on treasuries but adjusted with yields appropriate to a specific bond. Two yield curves are shown below. The blue curve corresponds to Treasury yields on Dec, 17, 2012. The present value of each coupon payment and of the bond's value at maturity is based on the interest rate for that payment's maturity taken from the current yield curve.

Note how different they are. The same bond would have a very different price when priced against those two curves. Let's calculate the price of a bond relative to the blue curve. The values use for the yield curve are based on a standard set of Treasuries with maturities of one month, three months, six months, one year, etc. We need a interpolation function to get the interest rate for any maturity. Let's assume a 10 year bond with a 4% coupon paid once a year. The price for a 100$bond is 120.69%. The bond has a price of 109.12$ against the higher yield curve. As shown in the price-yield curve above, bond prices fall when yields rise. The yield curve changes over time. Let's use Wolfram|Alpha to compare the yield curves for October 15, 2012 and October 15, 2005. What would happen to our bond's price under those changes?

Wolfram|Alpha Bond Queries
Bond Price
Duration
Modified Duration
Yield to Maturity

Mathematica Functions
FinancialBond

Corporate Bonds (where default is possible)

...

Demonstrations
Credit Risk
Transition Matrix

Yield Curves with Mathematica 6.0

Callable Bonds (where future payments are contingent)

Pass-through Bonds (packages of various interest paying securities)

Miscellaneous Notes & Links

## 1b. Stocks

I'm going to replace this with a Mathematica centric discussion soon. I'm gathering my thoughts a the moment...

(The classical approach to valuing stocks is to use a dividend discount model. The underlying idea is that the present value of a stock is equal to the sum of the present values of it's future dividends. This approach, along with various implementation issues is discussed throughly by Aswath Damodaran, a professor at NYU. There are lots of issues: how do you estimate the size of the uncertain future cashflows, how much should they be "discounted", and more recently, does this approach give the proper importance to sentiment. For example, John Cochrane, the past President of the American Financial Institution and a professor at the University of Chicago, has argued that "price-dividend ratios correspond to discount-rate variations instead of variations in expected cash flows." He present evidence taken from many asset classes to support the generality of this claim. He suggest that the emphasis on future cash flows is misdirected. This fits into the broad category of behavioral investment theory.

Continuing in this theme, Philip Maymin (above) is the founding editor of Algorithmic Finance, the current issue of which contains an article, which claims that "The sentiment indicator we introduce gives a way to actually quantify the impact of human biases and sentiments directly on the markets instead of simply postulating effects which is often done in the field of Behavioral Finance. There are really a lot of open issues in what might seem to be a plain vanilla topic as stock pricing, and it is worth learning about them. I've left out the Capital Asset Pricing Model, Arbitrage Pricing, and other subjects that are exciting, controversial, and fun to learn about.)

Demonstrations
Expected Returns
Return Distributions

Wolfram Videos
Financial Statistics (How to, using stock prices from W|A - Good)

Related Internet Sites
Math Estate: Stock Investment Tools

## 1c. Derivatives

Forwards and Futures

Options

Swaps

Real Estate

Commodities

Value at Risk

## 6. Miscellaneous Items

-
@GeorgeWolfe The Why` is critical to this whole enterprise. Someone with a strong Statistics, Econometrics and programming background will not go very far if they don't understand the Finance and Economics behind the models. Your road-map is absolutely essential to keep OP's project from being DOA. Presumably some of those MMA for Fin-engineering books will provide some of this perspective but I am not optimistic about the quality. – Amatya Oct 9 '12 at 0:51

It depends on how deep you want to go into the details of financial engineering (Multi Factor Models, Complicated Deal Types, ...) - if you intend to work with these things check out the Mathematica based solutions here

http://www.unrisk.com/index.php/products

Also some white papers on the underlying mathematical methods are available there

-