# QuantFinanceToGo, module 16: Monte Carlo Simulation. Project starter: a report.
# Runs on its own with Python 3 and numpy. Every path in it is simulated.
# The lesson lists the next steps to grow this file into your own project.
import math
import numpy as np

rng = np.random.default_rng(1)                          # fixed seed
start, years, paths = 10000, 30, 10000
mu, sigma = 0.08, 0.20                                  # assumed, per year
log_ret = rng.normal(mu - sigma ** 2 / 2, sigma, (paths, years))
value = start * np.exp(log_ret.cumsum(axis=1))          # one row per path


def horizon_report(t):
    final = value[:, t - 1]
    low, mid, high = np.percentile(final, [10, 50, 90])
    se_mean = final.std(ddof=1) / math.sqrt(paths)
    loss = (final < start).mean()
    print(f"{t:>5} {low:>9,.0f} {mid:>9,.0f} {high:>10,.0f} {loss:>7.2%}"
          f" {final.mean():>10,.0f} {se_mean:>7,.0f}")

print(f"Monte Carlo report: ${start:,}, {paths:,} paths, average {mu:.0%} "
      f"and volatility {sigma:.0%} a year")
print(f"{'years':>5} {'10th':>9} {'median':>9} {'90th':>10} {'loss':>7}"
      f" {'average':>10} {'SE':>7}")
for t in (1, 5, 10, 20, 30):
    horizon_report(t)
