A package in Mathematica serves two purposes. First of all, it hides from the user the code he does not need or whish to know. Secondly, it is a more powerful tool than Block or Module for protecting names of functions or symbols from conflicting with one another. In this course we shall use only the most basic package writing skills. To write complicated packages it is advisable to read a more specialized text, for example "Programming in Mathematica" by Roman Maeder.

The most important thing to understand about Mathematica packages is the concept of a Context. Every symbol in Mathematica belongs to a some context. Built in functions usually belong to the context "System". You can find out what the context of a symbol is by entering:

Context[Sin]

Every symbol has a full name which includes the context. For example, the full name of Sin is

System`Sin[Pi]

Of course this is inconvenient so if the context is known to Mathematica you can omit it when using the names of symbols in a given context. Hence you only need to evaluate

Sin[Pi]

Now let's define our own symbol f. We shall make it a function as follows:

f[x_] := x^2

Context[f]

This means that we can write

Global`f[2]

But because Mathematica always knows the context Global we can use the function f without the name of the context.

f[2]

When we ask Mathematica for information about the symbol f it will tell us its context:

?f

Let us know make Mathematica forget everything about f:

Remove[f]

We shall now define a new context, called dog`  and define f in this context. Note that context names always end with `.

Begin["dog`"]

We can check what the current context is:

Context[]

Now define f:

f[x_] := x^3

Check that it works

f[3]

Now let's leave the context dog.

End[]

Context[]

Now let's check what Mathematica knows about f:

?f

Nothing. However, it knows about:

?dog`f

We can start a different context called "cat" and define another f unction, which we also call f, but in the context cat`:

Begin["cat`"]

Context[]

f[x_] := x^4

f[3]

End[]

In the context Global` neither f is visible:

f[2]

We have to refer to them by their full names:

dog`f[2]

cat`f[2]

Now, we will come to the basic idea of a package. Note that we are now in the context Global`. Let's first simply evaluate the symbol f:

f

That is already enough for Mathematica to include f in the context Global`

?f

O.K. Now we define a new context, horse`, which however is this time is a "subcontext" of the context "dog".

Begin["`horse`"]

Note the ` at the beginning of the context name. It tells Mathematica that it is a subcontext of the context Global`. We shall now define two functions, f and g in the context "Global`horse`":

f[x_] = x + 1; g[x_] := x + 2

Of course, inside horse` both f and g are visible:

{f[2], g[2]}

Let's see what happens outside:

End[]

{f[2], g[2]}

f is visible but g is not. In other words, f is "public" but g is "private", belonging to the context. Of course in Mathematica it is difficult to really "hide" things, you can reach g using:

`horse`g[2]

So this is the basic idea of what happens inside a package. Symbols which you want to be visible to the user are introduced before starting a private context, while the ones one's you want to keep private are introduced only inside such a context. Let us have a quick look at a simple package defining just two functions. This package is a part of the BlackScholes package which you will find in the folder "Packages" in the folder Finance, and which we shall use a lot from now on. Let  me explain step by step the meaning of all the commands.

\(BeginPackage["Finance`BlackScholes`"]

 (*Usage\ Information*) 


\)
\(BlackScholesCall::usage = "BlackScholesCall[price, strike, vol, riskfree, divyield, expiry] 
returns the Black-Scholes value of a vanilla European Call."
\)
\(BlackScholesPut::usage = "BlackScholesPut[price, strike, vol, riskfree, divyield, expiry] 
returns the Black-Scholes value of a vanilla European Put."



 (*END\ OF\ USAGE\ INFORMATION*) 
\)
Begin["`Private`"]

Norm[z_?NumberQ] := 
        N[0.5 + 0.5 Erf[z/Sqrt[2]]];

Norm[x_] := (1 + Erf[x/Sqrt[2]])/
          2;

dtwo[s_, v_, k_, t_, r_, 
          q_] := (Log[s/k] + (r - q) t)/(v Sqrt[t]) - 
          1/2 v Sqrt[t];

done[s_, v_, k_, t_, r_, 
          q_] := (Log[s/k] + (r - q) t)/(v Sqrt[t]) + 
          1/2 v Sqrt[t];

\(\(BlackScholesCall[s_, k_, v_, r_, q_, t_] := 
        s\ Exp[\(-q\)*t]\ Norm[done[s, v, k, t, r, q]] - 
          k*Exp[\(-r\)*t]\ Norm[
              dtwo[s, v, k, t, r, q]];\)
\)
\(\(BlackScholesPut[s_, k_, v_, r_, q_, t_] := 
        k*Exp[\(-r\)*t]\ Norm[\(-dtwo[s, v, k, t, r, q]\)] - 
          s\ Exp[\(-q\)*
                t]\ Norm[\(-done[s, v, k, t, r, 
                  q]\)];\)

\)
\(End[]
\)
EndPackage[]

The first line:

BeginPackage["Finance`BlackScholes`"]

This begins the package BlackScholes.m (names of packages always end in .m). Notice the word Finance`  before he context  BlackScholes`. This simultaneously creates a context called Finance`BlackScholes`  and tells mathematica that the package BlackScholes.m is in a folder called Finance. If you want to the package to be in a different folder, for example, OptionPricing, you should start with

BeginPackage["OptionPricing`BlackScholes`"]

The next line:

\(\(\(BlackScholesCall::usage = "BlackScholesCall[price, strike, vol, riskfree, divyield, expiry] 
returns the Black-Scholes value of a vanilla European Call."\)\(
\)
    \)\)

performs a dual function. First of all it introduces the name BlackScholesCall in the current context so that it will be publicly accessible once the package is loaded. The second function is that it creates "usage information". If we evaluate the above command once:

BlackScholesCall::usage = "BlackScholesCall[price, strike, vol, \
riskfree, divyield, expiry] 
returns the Black-Scholes value of a vanilla European Call."

we can now use

?BlackScholesCall

to obtain information about the function BlackScholesCall.

Begin["`Private`"]

begins a new sub-context called Private`. Any function that did not have a usage message outside this context will remain inaccessible (unless its full name is used). For example the functions:Norm, dtwo, done are all private. However the functions BlackScholesCall and BlackScholesPut will be public, because a usage message was created  outside the Private` subcontext.

If you look at our package OptionPricingWithTrees you will see that  it begins with

\(BeginPackage["Finance`OptionPricingWithTrees`", "DiscreteMath`Combinatorica`", "Geometry`Rotations`"]\)

This not only  sets up the context Finance`OptionPricingWithTrees`  but also automatically loads two packages, DiscreteMath`Combinatorica` and Geometry`Rotations` which are needed by OptionPricingWithTrees.

Finally, how to write a package? There are two basic ways. The BlackScholes.m package shows one example, and the OptionPricingWithTrees the second. In the first case you can write the package with any text editor (not Mathematica). You must make sure that the name of the package ends with extension .m. Most packages tend to be written in this way. You must put such packages in one of the subfolders of the AddOns folder (I thank Applications is the best place) or in a subfolder like Finance. 
The second method, which I prefer, is the one used in OptionPricingWithTrees. Note that in fact there are two files: OptionPricingWithTrees.nb and OptionPricingWithTrees.m The first is a notebook and the second is a package. It is only necessary to write the notebook, the package is generated automatically. What you have to do is to write all your code in a notebook, as usual, but make sure that all the input cells are "initialization cells". To make an input cell an "initialization cell" you select its "bracket" and then form the Cell Properties submenu of the Cell menu you choose "Initialization Cell". You should make all your input cells initialization cells. Not that you can select all input cells just by clicking on the bracket of only one of them while holding down the Alt key. Once you have done that, save your notebook in the same place where you want the package to be created, for example in the Finance folder. When you do that a package with extension .m should be created automatically. Whenever you make changes to the notebook and save the package should be automatically updated. I find this the most convenient way to create packages.

There is one more, very similar,  way to create a package using mathematica rather than an external editor. Again you write a notebook, make sure that all the input cells are Initialization cells, but at the end you do not save the notebook. Instead you use the "Save As Special" submenu of the File menu and choose "Package Format". This will create a package with extension .m without an accompanying notebook with extension .nb. However, this approach is not so convenient if you want later to make changes to your package.

After packages have been saved in one of the subfolders of the Folder AddOns (we shall always put them in Finance in Applications) You can load them with

<< Finance`OptionPricingWithTrees`

<< Finance`BlackScholes`

or

Needs["Finance`OptionPricingWithTrees`"]

Needs["Finance`BlackScholes`"]

The second form has an advantage in that it does not try to read in functions that have already been read but most people seem to prefer the first form because of its shorter form.

As an exercise, try writing a short package yourself containing some simple functions. Also, please download the BlackScholes package and put it in your Finance folder. You can find out the names of all the symbols in the BlackScholes package with the command:

?Finance`BlackScholes`*

Or

Names["Finance`BlackScholes`*"]

You can check what each individual function does with:

?BlackScholesPutImpVol