Created
December 22, 2020 22:20
-
-
Save jtiai/a519fb4998deba0ceff742fb253fd538 to your computer and use it in GitHub Desktop.
Commodity price simulator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Commodity price simulator | |
# | |
# pip install pygame | |
# pip install matplotlib | |
import random | |
import pygame | |
import matplotlib | |
matplotlib.use("Agg") | |
from matplotlib import pyplot | |
from matplotlib.backends import backend_agg | |
# Important constants | |
PRICE = 100.0 | |
LOW, HIGH = 75, 140 | |
mu = 0.0 | |
sigma = 2.0 | |
# most monitors are 96 dpi so calculate size in inches | |
fig = pyplot.figure(figsize=[1024 / 96, 768 / 96], dpi=96) | |
ax = fig.add_subplot(111) | |
canvas = backend_agg.FigureCanvasAgg(fig) | |
def plot_data(data): | |
ax.cla() | |
ax.plot(data, color="black") | |
ax.set_ylim(75, 140) | |
canvas.draw() | |
renderer = canvas.get_renderer() | |
raw_data = renderer.tostring_rgb() | |
size = canvas.get_width_height() | |
return pygame.image.fromstring(raw_data, size, "RGB") | |
screen = pygame.display.set_mode((1024, 768)) | |
clock = pygame.time.Clock() | |
nums = [] | |
price = PRICE | |
target_period = random.randint(5, 15) | |
delta_price = random.gauss(mu, sigma) / target_period | |
for i in range(500): | |
price += delta_price | |
target_period -= 1 | |
if not target_period: | |
target_period = random.randint(5, 15) | |
delta_price = random.gauss(mu, sigma) / target_period | |
if price < LOW: | |
delta_price *= -1.0 | |
price += delta_price | |
if price > HIGH: | |
delta_price *= -1.0 | |
price += delta_price | |
nums.append(price) | |
# Warm up clock | |
for _ in range(10): | |
clock.tick(60) | |
update_clock = 0.25 | |
running = True | |
while running: | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT: | |
running = False | |
dt = clock.tick(60) / 1000.0 | |
update_clock -= dt | |
if update_clock <= 0.0: | |
update_clock = 0.25 | |
price += delta_price | |
target_period -= 1 | |
if not target_period: | |
target_period = random.randint(5, 15) | |
delta_price = random.gauss(mu, sigma) / target_period | |
if price < LOW: | |
delta_price *= -1.0 | |
price += delta_price | |
if price > HIGH: | |
delta_price *= -1.0 | |
price += delta_price | |
nums.pop(0) | |
nums.append(price) | |
screen.fill((0, 0, 0)) | |
screen.blit(plot_data(nums), (0, 0)) | |
pygame.display.flip() | |
# Be nice... | |
pygame.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment