# How do I discount a stream of cash?

A plant that earns every year is worth less in today's money the later the cash arrives. NPV accumulates a stream at a discount rate. The script earns 100 a year for 20 years at 5%.

```python
from nagasim import build as nb

# A plant earns 100 a year from year 0. NPV(stream, rate, init, factor) accumulates that stream
# discounted at 5% a year, on the model's step grid.
m = nb.Model(time_limit=20, time_unit="years", sd={"dt": 0.05, "method": "euler"})
m.add_auxiliary(name="Cash", expr="STEP(100, 0)")
m.add_auxiliary(name="Value", expr='NPV(AUX("Cash"), 0.05, 0, 1)')
m.add_level(name="Total", initial=0)
m.add_flow(name="earning", to="Total", rate='AUX("Cash")')

series = m.run(seed=1)["timeseries"].pivot(index="Time", columns="Series", values="Value")
view = series[["level/Total", "aux/Value"]]
view.columns = ["Cash banked", "Present value"]
print(view.reindex([5, 10, 20], method="nearest").round(0).astype(int).rename_axis("Year").to_string())
exact = 100 * (1 - 2.718281828 ** (-0.05 * 20)) / 0.05
print(f"exact continuous discounting over 20 years: {exact:.0f}")

```

Save it as `recipe-discounted-cash.py` and run it with `python`. The script seeds itself, so the numbers below are the same on your machine.

```text
      Cash banked  Present value
Year                            
5             500            447
10           1000            791
20           2000           1268
exact continuous discounting over 20 years: 1264

```

## How it works

1. `NPV(stream, rate, init, factor)` adds up the stream discounted at `rate`, on the model's step grid; it needs `simulation.sd`.
2. After 20 years the cash banked is 2,000 and its present value is 1,268, against 1,264 from the exact formula.
3. A smaller `dt` closes the small gap, because the sum is taken a step at a time.

## Elements used

- Functions: [`NPV`](../../reference/functions/system-dynamics.md#npv), [`STEP`](../../reference/functions/system-dynamics.md#step).
- Model-file sections: [`auxiliaries`](../../reference/model-file/auxiliaries.md), [`levels`](../../reference/model-file/levels.md), [`flows`](../../reference/model-file/flows.md).
- Python: [`Model`](../../reference/api/Model.md).

Back to all [recipes](index.md).
