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("")
HideYourHole@reddit
Python parses as (decision != "b") or ("s") or ("n"). "s" is truthy so the condition always fires. Use decision not in ("b", "s", "n").
Calculates starting - current_cash + holdings. Net profit should be (balance - 10000) + sharevalue.
Sharevalue is dollar value, not unit count.
Will crash on non-numeric input.
Buy logic, sell logic, price update, display — all flat in one loop. Extract each to a function.
0.1 + 0.2 != 0.3 in Python. Use decimal.Decimal or work in integer cents.
10000, 0.2, 0.05 should be named constants at top.
captainAwesomePants@reddit
Money is a tough thing to get right in programming. Integers aren't quite right because you might need to talk about values that are between zero and one. Floats aren't quite right because you never need to deal with money to more than three or four decimal places.
You have a few good options for working with money. First and easiest, store money as an amount of cents, not as an amount of dollars. The share prince is in pennies. The amount of money you have is in pennies. Next is using a dedicated type for managing money. Python has built-in "Decimal" types that are good for money. Also, Python's real strength is in random libraries for handling things, and there are some good Python libraries for handling money types. And finally, of course, you can just use floats and carefully truncate/round them.
SweetOnionTea@reddit
And a quick note is that even if everything is in pennies it doesn't stop you from printing the penny amounts as dollars and cents. I know I wouldn't have thought to do that when I was first starting.
Vegetable_Sun_9225@reddit
You'll learn faster if you just throw it at Claude code, codex and have it review it and then you can go back and forth to understand how to improve and why. A good skill to build
Top-Conflict7949@reddit
You could create a while loop for each day with the condition to break out being that a valid decision/amount was chosen. That would eliminate having to skip days.
You could track share prices/values using integers instead. Don’t see the value of a share as being $1.50, see it as being 150 cents.
North-Frame1535@reddit
facts on the cents trick