# Wealth with redistribution.  (1) Yard-sale trades, with and without a flat tax chi
# redistributed equally.  (2) Random returns of -10% to +10% a year (as in wealth.htm)
# plus redistribution of a fraction J of everyone's wealth per year, which gives a
# Pareto tail whose exponent alpha solves <[(1+r)(1-J)]^alpha> = 1.
# Rob - Clint Sprott's AI assistant, November 7, 2026
import numpy as np
from scipy.optimize import brentq
rng = np.random.default_rng(1)

def gini(w):
    s = np.sort(w); n = len(s)
    return 2*np.sum(np.arange(1, n + 1)*s)/(n*s.sum()) - (n + 1)/n

def yard_sale(N, rounds, chi):            # each round, everyone trades once with a random partner
    w = np.ones(N)
    for t in range(rounds):
        i, j = rng.permutation(N).reshape(2, -1)
        d = 0.1*rng.random(N//2)*np.minimum(w[i], w[j])*rng.choice([-1, 1], N//2)
        w[i] += d; w[j] -= d
        w = (1 - chi)*w + chi*w.mean()
    return w

def returns(N, years, J):
    w = np.ones(N)
    for t in range(years):
        w *= 1 + rng.uniform(-0.1, 0.1, N)
        w = (1 - J)*w + J*w.mean()
    return w

def hill(w, frac):                         # Hill estimate of alpha from the richest fraction
    s = np.sort(w)[::-1]; k = int(len(s)*frac)
    return k/np.sum(np.log(s[:k]/s[k]))

for chi in (0.0, 0.01):
    print("yard sale, chi = %.2f: Gini after 1000 rounds = %.3f" % (chi, gini(yard_sale(10**5, 1000, chi))))
Er = lambda a: (1.1**(a + 1) - 0.9**(a + 1))/(0.2*(a + 1))   # <(1+r)^a> for r uniform in -0.1..0.1
J = 1 - Er(1.5)**(-1/1.5)                                      # redistribution rate giving alpha = 1.5
w = returns(10**5, int(4/J), J)
print("returns, J = %.5f/year: predicted alpha = 1.5, Hill estimate (top 1%%) = %.2f, Gini = %.2f"
      % (J, hill(w, 0.01), gini(w)))
