Skip to content

Instantly share code, notes, and snippets.

@evanthebouncy
Created December 1, 2024 18:18
Show Gist options
  • Save evanthebouncy/1072e5cc7406ebd9e72340e718eaa384 to your computer and use it in GitHub Desktop.
Save evanthebouncy/1072e5cc7406ebd9e72340e718eaa384 to your computer and use it in GitHub Desktop.
path to ruin, of Nassim Nicholas Taleb's school of thought. martingale and non-ergodic thing
import numpy as np
import matplotlib.pyplot as plt
# roll out of a particular game, start at position n, and roll a coin of some prob to move up or down.
# if it reaches 0, you lose
def simulate_game_log_space(start_n, coin_prob):
trajectory = []
n = start_n
for i in range(1000):
trajectory.append(n)
if n == 0:
return trajectory
n = n + np.random.choice([-1, 1], p=[1-coin_prob, coin_prob])
return trajectory
def simulate_game_conservative(start_n, coin_prob):
trajectory = []
n = start_n
for i in range(1000):
trajectory.append(n)
if n <= 0:
return trajectory
# do a conservative strategy
n = n + np.random.choice([-0.1, 0.1], p=[1-coin_prob, coin_prob])
return trajectory
if __name__ == '__main__':
print ("Running the simulation, probability of win is 0.51, starting at 10")
print ("you lose if you reach 0")
print ("the original strategy, toss coin, if win, move up by 1, if lose, move down by 1. this is to simulate the game in log space, where move up by one is like a 2x, and down is like a 0.5x")
results = []
for i in range(100):
start_n = 10
coin_prob = 0.51
results.append(simulate_game_log_space(start_n, coin_prob))
# visualize all the trajectories in the same plot
for trajectory in results:
plt.plot(trajectory)
plt.show()
plt.close()
# visualize the histogram of the final positions
final_positions = [trajectory[-1] for trajectory in results]
plt.hist(final_positions, bins=range(11))
plt.show()
# print the number of times the game was lost
print (f'Number of times the game was lost: {sum([trajectory[-1] == 0 for trajectory in results])}')
print ("the conservative strategy, toss coin, if win, move up by 0.1, if lose, move down by 0.1. so instead of doing 2x and 0.5, we're doing roughly 1.07x and 0.93x")
# visualize the histogram of the final positions using a conservative strategy
results_conservative = []
for i in range(1000):
start_n = 10
coin_prob = 0.51
results_conservative.append(simulate_game_conservative(start_n, coin_prob))
# visualize all the trajectories in the same plot
for trajectory in results_conservative:
plt.plot(trajectory)
plt.show()
plt.close()
final_positions_conservative = [trajectory[-1] for trajectory in results_conservative]
plt.hist(final_positions_conservative, bins=range(11))
plt.show()
print (f'Number of times the game was lost with conservative strategy: {sum([trajectory[-1] <= 0 for trajectory in results_conservative])}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment