Chapter 11 Mathematica For Economists
Chapter 11 Mathematica For Economists
MATHEMATICA
HAL R. VARIAN*
FOR ECONOMISTS
Contents
1. 2. 3. 4.
5. 6. 7.
490 490 490 491 491 492 493 493 495 496 496 496 496 498 499 499
502 504
8. Summary References
505 505
*I would like to thank David Belsley and Bob Parks for comment on earlier drafts. This work was supported by NSF grant SES-9223130.
Handbook of Computational Economics, Volume 1, Edited by H.M. Amman, D.A. Kendrick and J. Rust ~) 1996 Elsevier Science B. V. All rights reserved.
490
H.R. Varian
1. Introduction
Mathematica is a computer program that can help you do mathematics. You can use it to do symbolic, numeric and graphical analysis. Mathematica is sold by Wolfram Research, Inc and runs on a variety of computers including MS-Windows, Macintosh, and Unix platforms. The cost of Mathematica depends on the version and the platform; it ranges from about $200 for a student version to several thousand for a multiple-user workstation version. You can contact Wolfram Research, Inc. by sending e-mail to i n f o @ w r i , corn, or calling them at 217-398-0700.
2. Design of Mathematica
There are two parts to the Mathematica program: the kernel and the front end. The kernel is the basic computational engine and is more-or-less platform independent; the front-end is slightly different for each platform. These two programs can be run separately: the front end can run on a lowly Macintosh while the kernel executes on a remote workstation or a supercomputer. This allows you to do your computations on whatever size computer you choose and still work in exactly the same user environment. Wolfram Research has developed a set of protocols known as MathLink that allow the Mathematica kernel to communicate with other programs running on a given machine. This feature allows the user to combine functionality of various programs in a convenient way. For example, you can manipulate numbers in a spreadsheet and then send them to Mathematica for further processing. Or you can process Mathematica output in TEN or some other formatting system. You can also send parts of Mathematica computations off to a special-purpose computer package such as I M S L or S. Various packages are available from third party suppliers that make this kind of inter-process communication very easy to implement. You load packages into Mathematica using < < as in the following examples.
In[l]:=
491
the Notebook can be typeset. Several books have been produced using this technique. In fact, this article has been produced using this system.
4. Programming
Mathematica contains a complete programming language that can be used to automate various kinds of computations. Thejanguage is based on the philosophy of "functional programming". This means that the fundamental operation in the language is the application of a function. Adherents of functional programming argue that it is a very efficient way to program. Functional programming allows you to build up small pieces of a program, interactively debug them, and string them together to achieve a desired end. Other functional languages are APL and Lisp. People who have used these languages will find Mathematica programming to be quite congenial. Mathematica also has tools for procedural programming, which is the style of programming used in Fortran, Pascal and C. However, these tools - DO loops, WHILE loops, and the like - are normally not the best way to program in Mathematica. One advocate has gone so far as to proclaim "If you .aren't programming functionally, you're programming disfunctionally!"
4.1. An example
The operation of the Mathematica programming language is best illustrated by an example. Suppose that you want to compute the square root of 3 using Newton's method. The difference equation that you want to iterate is:
Xt+ 1 = 2
3;t -}-
In order to write a program to calculate this expression using C or Fortran you would need to declare the variables, construct a DO or a for loop, and output the results. In Mathematica you simply declare the function:
In[l]:= newton[x_] := N [ I / 2 (x + 3/x)]
The expression on the left is the function declaration, x_ defines the dummy variable that will be the argument to the function, and N[ ] indicates that you want the expression inside the bracket to be converted to a real number. Once the function has been defined, you then apply the built-in function Ne s t L s t to calculate the first 5 terms starting from x = 1:
492 tn[2]:=
Out[2]= NestList {i., 2., [newton, 1.0,5 ] 1.75, 1.73214, 1.73205, 1.73205]
H.R. Varian
If you want to iterate until the result no longer changes, simply use the FixedPoint function.
In[3]:= Out[3]= FixedPoint 1. 7 3 2 0 5 [newton, 1.0 ]
4.2. Defining functions Mathematica contains a number of functions that operate on lists of objects. You can also write your own functions. For example, Mathematica contains a derivative
function that will calculate the symbolic derivative of an expression:
In[l]:: Out[l]= n x
D[x^n,x]
-1 + n
Here the # symbol is a placeholder that will take on the values in the list x. The definition of G r a d "maps" the D[ f , #] over the list x = { x l , x 2 } to produce a new list {D [ f , x l ] , D [ f , x 2 ] }. The definition of Hessian applies G r a d to Grad. Here are some examples.
In[3]:= Out[3]: {a xl Grad[xl^a x2^b, b x2 , b xl {xl,x2}] a x2 -i + b }
-i + a
In[4]:= Out[4]:
MatrixForm[Hessian[xl^a -2 (-i + a) -i a b xl a xl + a x2 -i + a x2 + b b
x2^b,
{xl,x2)] ] -i + a x2 a -2 x2 + b -I + b
a b xl
(-i + b)
b xl
Similarly the following definition will produce the first-order conditions for optimizing a function:
In[5]:= FOC[f ,x ] :: M a p [ ( D [ f , # ] - - 0 ) & , x ]
In[6]:= Out[6]:
FOC[xl^a
x2^b, {xl,x2}] b x2 == 0, b xl a x2 -i + b == 0]
i + a {a x l
493
4.3. Programming constructs Mathematica contains a number of programming constructs for iterating, branching,
etc. However, in general it is best to avoid iteration and indices if possible. Often there is a built in function that will do some particular sort of manipulation of a list of values. For example, recently I had a list of price vectors, (pt) and associated consumption bundles (z t) for t = 1 , . . . , T. I wanted to calculate the matrix (pS;ct) tbr -L,s = 1 , . . . , T for some revealed preference calculations. This is simple to do using iteration and indices of course, but that is quite inelegant. After a short search through the Mathematica book and a bit of experimentation I came up with the following solution that uses Mathematica's generalized inner product function.
In[l]:= vNatrix[p_,x_] := I n n e r [ T i m e s , p , T r a n s p o s e [ x ] , P l u s ]
To verify that this works, define some vectors and apply the function:
In[2]:=
In[3]:= Out[3]=
M a t r i x F o r m [vMatrix [p, x] ] pll xll + p12 x12 p21 xll +' p22 x12 p31 xll + p32 x12 pll x21 + p12 x22 p21 x21 + p22 x22 p31 x21 + p32 x22 pll x31 + p12 x32 p21 x31 + p22 x32 p31 x31 + p32 x32
This example illustrates a nice point about Mathematica programming: if you know the formula for what you want, you can apply your function to symbolic values to see if it produces the right thing. Once it does, you can switch to numbers.
b2.
An easy way to do this is to take a log transform to construct the linear system all log :cl + al2 log z2 = log bl, a21 log Zl + a22 log z2 = log b2.
494
Mathematica
H.R. Varian
won't do this kind of transformation automatically, nor should it: this particular transformation is only valid for positive real numbers. On the other hand, it would be nice to automate this sort of thing. Here's how to do this in M a t h e m a t i c a . First we define the rules that translate the pattern may b = c into a log x + b log y = log c and the reverse transformation. (The semicolon at the end of the expression inhibits the output which, in this dase, is uninteresting.)
In[l]::
In[2]:: C l e a r [x]
^b
::
c_
->
a Log[x]
In[3]:=
+ c_*Log[d_])/e_)
ln[5]::
Out[5]:
logEqns:eqns/.logRules {all a12 Log[xl] Log[xl] + a21 + a22 Log[x2] Log[x2] :: =: Log[bl], Log[b2]}
In[6]:= Out[6]=
ans=Simplify[Solve[logEqns,
{Log[xl],Log[x2]}]]
{{Log[xl]
->
-(a22 Log[bl]) + a21 Log[b2] ............................ , a12 a21 - all a22 -(a12 Log[bl]) + all Log[b2] ............................ }} -(a12 a21) + all a22
Log[x2]
->
In[7]:= Out[7]:
ans/.eRules b2/(a12 a21 - all a22) a21 -> . . . . . . . . . . . . . . . . . . . . . . . . . , a22/(a12 a21 - all a22) bl b2/(-(a12 a 2 1 ) + a l l a22) all -> . . . . . . . . . . . . . . . . . . . . . . . . . . . . }} a12/(-(a12 a21) + a l l a22) bl
{{xl
x2
495
This particular set of rules is pretty minimal. A really useful set of rules for doing and undoing log transforms should be more sophisticated. Nevertheless, this example illustrates some of the power of the pattern matching capabilities.
4.5. Expressions
In Mathematica everything is an expression: a head followed by a list of items. A generic list, for example, is represented by the expression LL s t [ a , b , c ] . ']'he sum of 3 objects is represented by P l u s [ a , b , c ] . An assignment expression that says "map a to b" is represented by R u l e [ a , b ] , and so on. This uniform representation means that all objects can be operated upon in the same way. Consider for example the operator Map [ f , e x p ]. This will distribute the function f over the elements in the expression e x p . So
In[1]:=
M a p [ f , L i s t [a,b, c]] Map[f,Plus[a,b,c] ] M a p [f , R u l e [a, b] ] {f[a], f[a] f [a] f[b], f[c]) + f[c]
Functions can be defined "on the fly" by using the construction called a pure function. The function f [ x ] = x ^ 2 can be written in "pure" form as #^2& or
Function [x, x^2 ]. Map [#^2&, {a,b,c}]
In[2]:=
Out[2]=
2
)
{a , b , c
+ y^3
Mathematica will try the first form first; if that doesn't work it will try the second. If nothing fits, Mathematica just returns what you typed in. In[4]:= f [a]
f[a,b] f [a,b,c]
Out[4]=
Out[4]-:
2 i5t
3
a + b
Out[4]=
f [a, b, c]
This allows you to define functions that can accept different forms of arguments~
496
H.R. Varian
5. Packages Sets of Mathematica commands can be collected together into Packages. These are plain ASCII files that can be input into other Mathematica programs to do specific calculations. The Mathematica distribution comes with a number of Packages designed for specific sorts of calculations such as combinatorics, linear algebra, statistics, and so on. Many authors have produced Packages and Notebooks that for various uses that they have made available to other users through articles, books and on-line systems.
6. MathSource Wolfram Research maintains a repository of contributed Mathematica materials that are available via e-mail and ftp. This repository is known as MathSource. The easiest way to start using MathSource is to send e-mail to m a t h s o u r c e @ w r i , corn that contains the message h e l p i n t r o . MathSource will return some documents that explain how to retrieve files.
7. Applications in economics
In the following sections I describe some applications of Mathematica in economics. Obviously the list is not complete, but I hope to give the reader some idea of potential uses. Many further examples can be found in Varian (1993).
xl)
+ f[xl,
Next we calculate the first order conditions for profit maximization and-the Hessian using the functions that we have defined earlier.
In[2]:= focs=FOC [profit, {xl,x2} ]
Out[2]=
{-wl + f
(1, O)
[xl, x2] :: O, -w2 + f
(0,1)
[xl, x2] == O]
497
Out[3]=
(2, O)
[xl, x2], (i,i) {f [xl, x2], f
( i , 1)
[xl, x2]}, (0,2) f [xl, x 2 ] } }
Note Mathematica's notation for derivatives: f(i,j) is the ith derivative of argument 1 and the jth derivative of argument 2. Next we totally differentiate the first-order conditions.
In[4]:= totalDerivative
{-Dt[wl] + Dt[x2]
= Dt [foes]
Out[4]=
f
( 1,1 )
[xl, x2] +
(2,0)
Dt[xl] f [xl, x2] == 0,
(0,2)
-DE[w2] + Dt[x2] (I,I) mt[xl] f [xl, X2] =: 0} f [xl, x2] +
Note that Mathematica uses the notation of D t [ x l ] for the differential element d z I . N o w we simply solve the system of equations and substitute out for the determinate of the Hessian:
In[5]:= S i m p l i f y [ S o l v e [ t o t a l D e r i v a t i v e , {Dr [xl] , Dt [x2 ] } ] ] /. {Det [Hess] - > d H e s s }
Out[5]=
{{Dt[xl]
(0,2)
(1, l )
D t [x2 ] -> (i,i) (2,0) -(Dt[wl] f [xl, x2]) + mt[w2] f [xl, x2] ................................................ }} dHess
dz 1 =
dHess
fll dw2 + f21 dwl
dx 2 =
dHess
These conditions contain all of the normal comparative statics conclusions about cost minimization.
498
H.R. Varian
For certain classes of u(c) it is possible to find closed-form solutions for V~(w). Solving the Bellman recursion numerically or symbolically is simple using Mathematica. For example, here is how you would write the Bellman equation for the case of log utility and a five-period time horizon:
In[l]:= V[w , 5 ] :: Log[w]
(w-c)*R,t+l]/.Solve[D[Log[c] ( w - c ) * R , t + l ] , c ] = = 0 , c ] [ [i] ] ] V [ w _ , t_] := M o d u l e [{c}, Log[c] + alpha*V[ + alpha*V[
The first definition gives the boundary condition. The second definition gives the recursion. The M o d u l e construction declares c to be a local variable. Subsequently, we have the recursive definition of the value function; the notation a / . b means "substitute b into a". In this case b contains the optimal solution and a is the objective function. Calculating V(w, 2), for example, gives us:
In[2]:=
Out[2]=
Simplify [V [w, 2 ] ]
alpha
2 alpha
3 alpha
499
Solve[D[Log[c]
+ alpha*V[(w-c)*r,3],c]==0,c] w
}
[[i]]
...........................
Nash[ { { {2, i}, {0,0} }, { {0,0), {1,2} ] } ] {{{0, i}, {0, i}},
2 {{-, 3 1 -}, 3 1 {-, 3 2 -}}, 3
{{i,
0},
{I,
0)})
7.4.1. Symbolic expressions Mathematica can simplify various statistical calculations. As an example, let us define
a Normal distribution:
In[l]:= N o r m a l D i s t n [x ,m_, s_] _-E x p [ - ( ( x - m ) / s ) ^2 / 2]/ (s Sqrt[2*Pi] )
Consider the problem of choosing a forecast y so as to minimize some expected loss involving x and y. The L I N E X loss function [see Varian (1975) and Zellner (1986)] has the form:
In[2]:= LinexLoss[a_,x_,y_] := Exp[a*(y-x)] - a*(y-x)
We are interested in the expected loss. The easy way to calculate this is to recognize that the first term is just the moment generating function for the Normal distribution. But if we don't recognize this, we can easily calculate the expected loss between - o c and + o o using Mathematica:
500 ln[31:=
Exloec t e d L o s s 1 = T o g e t h e r [P o w e r E x p a n d Integrate [LinexLoss [a,x,y] * NormalDistn [x,m, s} , {x, - I n f i n i t y , 2 (a (2 E (-2 m + a s + 2 y))/2 + 2 am2 ay[ Infinity} ]]]
H.R. Varian
Out[3]:
2 (a (-2 m + a s + 2 y))/2
m (a - --) s 2 s E r f [. . . . . . . . . . ] S q r t [2 ]
2 (a (-2 m + a s + 2 y))/2
/ 2
In Mathematica notation,
Erf[z] : ~
lf0
e -t
2dr.
I.
Expec tedLos s 3 :ExpandAl i [E x p e c t e d L o s s l ]
Out[4]=
-(a m) + (a
2
s
2
) /2 + a y
+ a m -
a y
Finally
we
PowerExpand
In[5]::
solve for the loss-minimizing estimate and use to put it into a simple form.
::0,y] [ [i] ]
Simplify
and
ans=Solve[D[ExpectedLoss3,y]
Out[5]:
a m Log[E - a
2
s
2
a Sqrt[E a
2
s
2
]]
{y -> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
[n[6]::
Simplify
[P o w e r E x p a n d
2 a s
[ans ] ]
Out[6]:
{y - > m . . . . .
2
501
The loss minimizing estimator is the mean, biased downwards by an amount that depends on the variance of the distribution.
Out[2]:
In[3]:=
Out[3]:
N o w I generate a sample of 25 random numbers; the semicolon tells Mathematica not to print them out.
In[4]:= theSample:Table [Random [] , {25}] ;
Here I resample from the list lO times and compute the mean of each resample.
In[5]:= Out[5]= bootList=Table [Mean [Resample [theSample] ] , {i0}] {0.529655, 0.547182, 0.473363, 0.387835, 0.62481, 0.586473, 0.543386, 0.633631}
0.464449,
0.593265,
We can write a function that will take a sample and a statistic and apply this statistic to resampled draws from the original sample. (The M e d i a n is defined in
Statistics 'DescriptiveStatistics.) ,stat_]
bootlt[sample_,n
:= Table[stat[Resample[sample]],{n}]
bootIt[theSample,10,Median] {0.520299, 0.520299, 0.482829, 0.398446, 0.398446, 0.392464, 0.526447, 0.445672, 0.482829, 0.526447}
7.4.3. Data analysis Mathematica comes with a number of standard statistical routines. Belsely (1992)
has provided a number of additional routines for classical econometric calculations.
502
H.R. Varian
Ley and Steel (1993) have provided routines for Bayesian calculations. Stine (1992) describes some methods for time series analysis. It is also easy to write your own routines. For example, I recently used Mathematica to calculate "efficiency indices". Suppose that you have a set of factor prices, factor choices, and output levels for n firms denoted by (wi, x~, Yi). The efficiency index of firm i is given by ei : min W i X j Yj)Y{ WiXi
Here we look at each firm that produces at least as much output as firm / to see if it's production plan would cost less than firm i's plan assuming both firms faced factor prices wi. Furthermore, I wanted to keep track of all the elements over which the minimization was taken so I could see how many firms appeared to be more efficient than the firm in question. This is not a difficult calculation, but there is no ready-made package to do it. In Mathematica all I had to do was to write:
In[l]:=
efficOf[i_,j_,wt_,xt_]
:=
(wt[[j]].xt[[i]])/(wt[[j]].xt[[j]]
eff[ws ,xs_,y_] := Map [Union, Table[If[y[[i]] <= y[[j]],Min[efficOf[j,i,ws,xs],l],l], {i,l,Length[y] }, {j,l,Length[y] }] ] In[2]:=
In[3]:=
The first expression simply calculates the cost ratio The second expression compiles a list of all the efficiencies that are less than 1 for each firm. The third expression actually does the calculations, and the fourth expression calculates the minimum efficiency. Once I had these efficiencies it was easy to look at a histogram, see how they changed when different inputs were used, and so on. Because the calculations were so flexible it was much easier to experiment than it would be if I had used a Fortran or C program to do this.
7.5. Graphics
One of the most useful things that Mathematica can do is to produce plots. Here are a few economics graphs.
503
80
60
\\\
20 40 60 80 i00
40
20
ln[2]::
Out[21=
In[3]:=
Out[3]: In[4]:=
Out[4]=
x2 {xl -> . . . . . . . . } 2
504 In[5]:=
rl:ParametricPlot[{(100-x2)/2,x2),{x2,0,50), DisplayFunction->Identity] r2:ParametricPlot[{xl, (100-xl)/2),(xl,0,50), DisplayFunction->Identity]
H.R. Varian
Finally we combine the plots to produce the picture of the Cournot equilibrium:
In[6]:= Show [{prl, pr2, rl, r2 }, DisplayFunction->$DisplayFunction]
50
40
30
20
i0
0 0
Out[6]=
-Graphics-
i0
20
30
40
7.6. Teaching
I have used Mathematica to prepare problem sets for both graduate and undergraduate courses. It makes it easy to get the graphs right and to make sure that the calculations come out in round and/or realistic numbers. Lately I have realized that it is silly to compose problems on Mathematica and have the students do them by hand: they should have access to the same kinds of tools the professor has access to. In the near future I hope to have some self-contained economic exercises and examples available in Mathematica. I have prepared a set of Notebooks that go through some of the calculations used in my textbook Microeconomic Analysis. These are available via MathSource as items 0202-419. I have also experimented with a number of undergraduate exercises. Since many universities are now introducing students to Mathematica and other symbolic algebra systems in calculus courses, it should be easy to use these tools in more advanced undergraduate economics courses.
505
8. Summary
I have found M a t h e m a t i c a to be very useful for prototyping, debugging, and executing many sorts of computations and calculations of interest to economists. Its strong point is that it does many different things well. It has a user-friendly front end and a sophisticated and flexible programming language; these features make it very handy for quick analysis of small-scale problems. However, it is probably not an ideal platform for large-scale computations that are going to be repeated many times, or for manipulation of large data sets. Standard statistical packages such as SAS or SPSS, or general purpose programming languages such as C or Fortran, are probably better suited for such tasks.
References
Belsely, D. (1993) 'Econometrics.m: A package for doing econometrics in Mathematica', in: H. Varian, ed., Economic and financial modeling with Mathematiea. New York: Springer. Dickhaut, J. and Kaplan, T. (1993) 'A program for finding Nash equilibria', in: H. Varian, ed., Economic and financial modeling with Mathematica. New York: Springer. Ley, E. and Steel, M.EJ. (1993) 'Bayesian econometrics: Conjugate analysis and rejection sampling', in: H. Varian, ed., Economic and financial modeling with Mathematica. New York: Springer. Stine, R.A. (1993) 'Time series models and Mathematica', in: H. Varian, ed., Economic and fnancial modeling with Mathematica. New York: Springer. Varian, H. (1974) 'A Bayesian approach to real estate assessment', in: S.E. Fienberg and A. Zellner, eds, Studies in Bayesian econometrics and statistics. Amsterdam: North-Holland. Varian, H., ed., (1993) Economic and financial modeling with Mathematica. New York: Springer. Wolfram, S. (1991) Mathematica. Reading, MA: Addison-Wesley. Zellner, A. (1986) 'Bayesian estimation and prediction using asymmetric loss functions', Journal ~[ the American Statistical Association, 81:446451.