jstac/quant-econ — pull request #8 by spencerlyon2 (2014-06-28 04:39:31+00:00)
Title: BUG: numpy broadcasting error in asset pricing

There was a bug in the asset pricing code.

In the `__init__` function for the `AssetPrices` class we were making the state space `s` be an n by 1 array.

When we tried to compute `P_tilde` and `P_check`, `s` being a two-dimensional array caused the broadcasting to be wrong.

We need to be computing `P_tilde[i, j] = P[i, j] * s[j]**(1 - gamma)`, but with a 2-dimensional s we were actually computing `P_tilde[i, j] = P[i, j] * s[i]**(1 - gamma)`.

Just keeping s as a one-dimensional input fixes the problem.

---

As an example (I did this for my own benefit to make sure I wasn't crazy), consider the following output I got from an ipython session:

```
In [9]: s
Out[9]: array([ 1.05 , 1.025, 1. , 0.975, 0.95 ])

In [10]: P
Out[10]:
array([[ 0.95 , 0.0125, 0.0125, 0.0125, 0.0125],
[ 0.0125, 0.95 , 0.0125, 0.0125, 0.0125],
[ 0.0125, 0.0125, 0.95 , 0.0125, 0.0125],
[ 0.0125, 0.0125, 0.0125, 0.95 , 0.0125],
[ 0.0125, 0.0125, 0.0125, 0.0125, 0.95 ]])

In [11]: P * s
Out[11]:
array([[ 0.9975 , 0.0128125, 0.0125 , 0.0121875, 0.011875 ],
[ 0.013125 , 0.97375 , 0.0125 , 0.0121875, 0.011875 ],
[ 0.013125 , 0.0128125, 0.95 , 0.0121875, 0.011875 ],
[ 0.013125 , 0.0128125, 0.0125 , 0.92625 , 0.011875 ],
[ 0.013125 , 0.0128125, 0.0125 , 0.0121875, 0.9025 ]])

In [12]: P * np.reshape(s, (5, 1))
Out[12]:
array([[ 0.9975 , 0.013125 , 0.013125 , 0.013125 , 0.013125 ],
[ 0.0128125, 0.97375 , 0.0128125, 0.0128125, 0.0128125],
[ 0.0125 , 0.0125 , 0.95 , 0.0125 , 0.0125 ],
[ 0.0121875, 0.0121875, 0.0121875, 0.92625 , 0.0121875],
[ 0.011875 , 0.011875 , 0.011875 , 0.011875 , 0.9025 ]])
```

Notice that the 3rd element of `s` is `1.0`. This means that if we are trying to calculate `P[i, j] * s[j]` we should have that the 3rd column of the result equal to the third column of `P`. We see that this is true when `s` is left as a 1-dimensional array, but when it moves to 2-d we instead see that the entire 3rd **row** is left unchanged.