Как запустить функцию одновременно с графиком? (Фондовое моделирование) - PullRequest
0 голосов
/ 06 февраля 2020

В настоящее время я делаю симулятор для акций, используя генератор случайных чисел. Мне нужны предложения по следующим 2 аспектам (первый имеет более важное значение):

  1. Игрок может покупать и продавать акции в любое время во время симуляции. (хорошей идеей было бы реализовать кнопки для этой функции, но я не уверен, как включить это в график, который использует matplotlib)
  2. Создание лучшего алгоритма для симуляции, который имитирует колебания цен фактических акций и товаров .

Код:

'''
import libaries
'''
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import random
import sys

from matplotlib.axes._axes import _log as matplotlib_axes_logger
matplotlib_axes_logger.setLevel('ERROR') # remove error for rgb values

'''
settings
'''
interest_rate = 0.10
budget = 1000
stock_bought = 0
stock_price = 100
time = 0
up_down = 0

'''
main
'''
while True:
    try:
        print("Write number of stocks you're going to buy below. \nPrice of stock: $" + str(stock_price) + "/stock. \nBudget: $" + str(budget) + ". \nInterest rate: 10%")
        player_input = input("> ").lower()
        print("-----------------------------------------------------------------------------")

        if stock_price * float(player_input) >= 0 and stock_price * float(player_input) <= budget:
            budget = budget - stock_price * float(player_input)
            stock_bought = stock_bought + float(player_input)
            initial_price = float(stock_price)
            print("Budget remaining: $" + str(budget) + "\nStocks bought: " + str(stock_bought))
            print("-----------------------------------------------------------------------------")
            pass
        elif stock_price * float(player_input) > budget:
            print("You have bought stocks which exceeded your budget. Please try again.")
            continue
        else:
            print("Invalid value. Please try again.")
            continue
    except ValueError:
        print("Invalid value. Please try again.")
        continue


    while True:
        try:
            print("How long do you want to turn on the stock market for (in minutes)?")
            minute = 6 * int(input("> ").lower())
            print("-----------------------------------------------------------------------------")
            break
        except ValueError:
            print("Invalid value. Please try again.")
            continue

    for i in range(minute): # 1 hour time-frame
        number = random.randint(1, 5)
        stock_change = 0

        if stock_price < 75 and up_down >= 30:
            if number == 1 or number == 2:
                stock_change = 0 - float(random.randint(1, 1000)/100)
                up_down = up_down - 2
            elif number == 3 or number == 4 or number == 5:
                stock_change = 0 + float(random.randint(1, 500)/100)
                up_down = up_down + 1
            else:
                stock_change = 0
        elif stock_price > 125 and up_down <= -30:
            if number == 1 or number == 2 or number == 3:
                stock_change = 0 - float(random.randint(1, 500)/100)
                up_down = up_down - 1
            elif number == 4 or number == 5:
                stock_change = 0 + float(random.randint(1, 1000)/100)
                up_down = up_down + 2
            else:
                stock_change = 0
        elif stock_price <= 0:
            if number == 1 or number == 2:
                stock_change = 0 - float(random.randint(1, 200)/100)
                up_down = up_down - 1
            elif number == 3 or number == 4 or number == 5:
                stock_change = 0 + float(random.randint(1, 300)/100)
                up_down = up_down + 1
            else:
                stock_change = 0
        elif stock_price >= 200:
            if number == 1 or number == 2 or number == 3:
                stock_change = 0 - float(random.randint(1, 300)/100)
                up_down = up_down - 1
            elif number == 4 or number == 5:
                stock_change = 0 + float(random.randint(1, 200)/100)
                up_down = up_down + 1
            else:
                stock_change = 0
        else:
            if number == 1:
                stock_change = 0 - float(random.randint(1, 1500)/100)
                up_down = up_down - 3
            elif number == 5:
                stock_change = 0 + float(random.randint(1, 1500)/100)
                up_down = up_down + 3
            else:
                stock_change = 0

        stock_price = stock_price + stock_change
        time = i/6 # 1i = 1 minute, i/6 = 10 seconds

        if stock_price > 125:
            color = (0, (1000 - stock_price) / 1000, 0)
        elif stock_price < 75:
            color = ((925 + stock_price) / 1000, 0, 0)
        elif stock_price == 0:
            color = (0.925, 0, 0) # 925/1000
        else:
            color = "blue"

        plt.scatter(time, stock_price, c = color, s = 5)
        plt.pause(0.05)

    plt.show()

    while True:
        try:
            print("How many stocks do you want to sell now? \nYou have " + str(stock_bought) + " stocks remaining to be sold. \nPrice of stock: $" + str(stock_price) + "/stock. \nType \"stop\" to stop the simulation.")
            stock_sold = input("> ").lower()
            print("-----------------------------------------------------------------------------")

            if stock_sold == "stop":
                print("Budget remaining: $" + str(budget) + "\nStocks remaining: " + str(stock_bought))
                sys.exit()
            elif float(stock_sold) <= stock_bought and float(stock_sold) > 0:
                stock_bought = stock_bought - float(stock_sold)
                difference = stock_price - initial_price
                if difference >= 0:
                    budget = budget + float(float(stock_sold) * stock_price) - float(difference * interest_rate)
                else:
                    budget = budget + float(float(stock_sold) * stock_price)
                break
            elif float(stock_sold) == 0:
                break
            elif float(stock_sold) > stock_bought:
                print("You tried to sell more stocks than you have. Please try again.")
                continue
            else:
                print("Invalid value. Please try again.")
                continue
        except ValueError:
            print("Invalid value. Please try again.")
            continue


    up_down = 0
    print("Budget remaining: $" + str(budget) + "\nStocks remaining: " + str(stock_bought))
    print("-----------------------------------------------------------------------------")
    continue

Заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...