Code Review - Small Stock Buying Game

Posted by tahk-ki@reddit | learnprogramming | View on Reddit | 6 comments

Hello! I'm extremely new to coding, and have been using resources such as Mimo to learn the basics. I've written a rock paper scissors game, and this has been my second attempt at a small game. The idea is having a balance of $10000, and buying/selling a share at varying prices. My biggest hurdle has been navigating floats and integers, as well as using a random function to change the share price. In its current state the share price can only go up, not down, as my other attempts have led to problems with rounding.

I was also wondering how to resubmit the buy/sell question in the case that the input doesn't fit. Currently I just have it skipping to the next day.

Let me know what clever ways this can be shortened or simplified into less lines that I've missed, or a solution to either the problem of simulating changes in share price, or asking the buy/sell question again after falling into an "Invalid amount".

Thanks!

import random
day = 1
balance = float(10000)
shareprice = float(10)
unitsheld = 0
sharevalue = float(shareprice * unitsheld)
maxunits = int(balance*0.2 / shareprice)
print(shareprice)


while True:
    print(f"Day {day}")
    print(f"Balance: ${balance}")
    print(f"Shares held: ${sharevalue}")
    print(f"Share price: ${shareprice}")
    decision = input("Buy, sell, or not? b/s/n: ")
    if decision == "b":
        unitsbought = int(input(f"How many units would you like to buy? Maximum {maxunits}: "))
        if unitsbought > maxunits or unitsbought < 0:
            print("Invalid amount. Skipping to the next day") 
            unitsbought = 0
            # unsure how to avoid skipping to the next day
        else:
            unitsheld += unitsbought
            balance -= unitsbought*shareprice
            print(f"Units held: {unitsheld}")
    elif decision == "s":
        unitssold = int(input(f"How many units would you like to sell? Maximum {unitsheld}: "))
        if unitssold > unitsheld or unitssold < 0:
            print("Invalid amount. Skipping to the next day")
            unitssold = 0
        else:
            unitsheld -= unitssold
            balance += round((unitssold*shareprice),2)
            print(f"Units held: {unitsheld}")
    elif decision == "n":
        print("Skipping to the next day")
    elif decision != "b" or "s" or "n":
        print("Invalid answer. Skipping to the next day")
    shareprice += round(random.uniform(0, 0.05*shareprice),2)
    # shareprice += round(random.uniform(0, 0.05*shareprice) - random.uniform(0, 0.05*shareprice),2)
    # problems with rounding
    print(f"New shareprice: {shareprice}")
    valuechange = 10000 - balance + sharevalue 
    # unused variable. potentially calculating % profit or share price changes
    sharevalue = round((shareprice * unitsheld),2)
    maxunits = int(balance*0.2 / shareprice)
    day += 1
    print("")