0% found this document useful (0 votes)
7 views7 pages

APCSP Create Task Program Code

This document outlines a stock trading simulation game where users can buy and sell stocks from a predefined list. It includes functions for managing stock prices, user input validation, and tracking purchase history. The game allows users to start with a set amount of money and make decisions over a specified number of quarters.

Uploaded by

800025241
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

APCSP Create Task Program Code

This document outlines a stock trading simulation game where users can buy and sell stocks from a predefined list. It includes functions for managing stock prices, user input validation, and tracking purchase history. The game allows users to start with a set amount of money and make decisions over a specified number of quarters.

Uploaded by

800025241
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

import random

list_of_stockprices = [[100.00], [5000.00], [40.00], [25.00], [15.00]]


listofranges = [[0.97, 1.055], [0.965, 1.035], [0.968, 1.037], [0.98, 1.02], [0.95,
1.1]]
stocknamelist = ["Appel", "S&D 300", "Destern Wigital", "MacDanolds", "Athevan Ships"]
money = 10000.00
def is_integer(checkvalue):
if "." in checkvalue:
print("That is not an integer!")
return 0
try:
int(checkvalue)
except:
print("That is not a number!")
return 0
else:
checkvalue = int(checkvalue)
return 1
# Used the try-except block some code from
https://www.w3schools.com/python/python_try_except.asp

def easyreadmoney(price):
stringprice = str(round(price,2))
appendafterperiod = ""
periodtime = 0
for i in range(len(stringprice)):
if stringprice[i] == ".":
periodtime = 1
if periodtime == 1:
appendafterperiod = (stringprice[i:])
stringprice = stringprice[:i]
break
counter = 0
if len(appendafterperiod) == 2:
appendafterperiod = appendafterperiod + "0"
elif len(appendafterperiod) > 3:
appendafterperiod = str(round(int(appendafterperiod[1:]), 2))
for i in range(len(stringprice), 0, -1):
if counter%3 == 0 and counter != 0:
stringprice = stringprice[:i]+ "," + stringprice[i:]
counter += 1
stringprice = stringprice+(appendafterperiod)
return stringprice

purchase_history = []
def buy_stock(stocknumber, quarterly_val, account_balance):
quarterly_val -= 1
numberbought = input("How many shares (whole number) of
"+stocknamelist[stocknumber]+" would you like to buy?\n")
if is_integer(numberbought) == 1:
if numberbought == "0":
print("You cannot buy zero shares!")
return 0
numberbought = int(numberbought)
stocklist = list_of_stockprices[stocknumber]
pricebought = stocklist[quarterly_val]*numberbought
if pricebought <= account_balance:
print("Buying "+ str(numberbought)+" shares of " +
stocknamelist[stocknumber]+" costs $"+str(easyreadmoney(pricebought))+". Your account
balance will drop from $"+str(easyreadmoney(account_balance))+" to
$"+str(easyreadmoney(account_balance-pricebought))+"." )
confirmbuy = input("Type Y if you would like to buy this. If not, enter
anything else to cancel.\n" )
if confirmbuy == "Y" or confirmbuy == "y":
account_balance -= pricebought
print("You now have $"+str(easyreadmoney(account_balance))+" in your
account.")
purchase_history.append([stocknumber, stocklist[quarterly_val],
numberbought, stocklist[quarterly_val]*numberbought, quarterly_val])
else:
print("Purchase canceled.")
else:
print("You don't have enough money to buy that! Your balance would be
negative $"+(easyreadmoney((account_balance-pricebought)*-1))+".")
return(account_balance)

def numberofshares(stocknumber):
totalshares = 0
for i in purchase_history:
if i[0] == stocknumber:
totalshares += i[2]
return totalshares

def sell_stock(stocknumber, quarterly_val, account_balance):


okaysell = 0
quarterly_val -= 1
getmoneyback = 0
while okaysell == 0:
sharesell = input("How many shares would you like to sell? Type an integer.
\n")
if is_integer(sharesell) == 1:
if int(sharesell) == 0:
print("You cannot sell zero shares!")
return(0)
if int(sharesell) > numberofshares(stocknumber):
print("You have only invested "+ str(numberofshares(stocknumber))+"
shares in "+str(stocknamelist[int(stocknumber)])+".")
else:
okaysell = 1
totalsold = 0
removelist = []
moneyearned = 0.00
for purchase in purchase_history:
if purchase[0] == stocknumber:
specificstocklist = list_of_stockprices[stocknumber]
for i in range(purchase[2]):
moneyearned += (specificstocklist[quarterly_val] - purchase[1])
getmoneyback += specificstocklist[quarterly_val]
purchase[2] -= 1
purchase[3] -= purchase[1]
totalsold += 1
if purchase[2] == 0:
removelist.append(purchase)
if totalsold == int(sharesell):
break
for removepurchase in purchase_history:
if removepurchase in removelist:
purchase_history.remove(removepurchase)
if moneyearned > 0:
print("You earned $"+(easyreadmoney(moneyearned))+".")
else:
print("You lost $"+(easyreadmoney(moneyearned*-1))+".")
return (getmoneyback)

def stockboughtinfo(stocknumber):
numberofpurchases = 0
for purchase in purchase_history:
if purchase[0] == stocknumber:
print("You bought "+str(purchase[2])+" shares in quarter " +
str(purchase[4])+ " for $"+str(purchase[1])+" per share, for a total of
"+str(purchase[3])+".")
else:
numberofpurchases += 1
if numberofpurchases == len(purchase_history):
print("You have not bought any shares of "+stocknamelist[stocknumber]+".")
return(1)
return

def setstockprices(stock, percent, stockrange):


end_value = percent*stock[0]
stock.append(end_value)
balance_var = 0
fluctuation_list = []
percent_list = []
upperlimit = quarter-2
for i in range(quarter):
fluctuation_list.append(random.randint(1, upperlimit))
upperlimit = upperlimit - fluctuation_list[i]
if upperlimit < 1:
break
pickwhichfirst = random.randint(0, 1)
pick_list = [stockrange[0]-0.01, 1, 1, stockrange[1]+0.01]
while len(fluctuation_list) != 0:
for i in range(fluctuation_list[0]):
percent_list.append(random.uniform(pick_list[pickwhichfirst*2],
pick_list[pickwhichfirst+2]))
fluctuation_list.pop(0)
if len(fluctuation_list) == 0:
break
pickwhichfirst = (pickwhichfirst+1)%2
for k in range(fluctuation_list[0]):
percent_list.append(random.uniform(1, stockrange[1]))
fluctuation_list.pop(0)
for i in range(len(percent_list)):
stock.insert(i+1, stock[i]*percent_list[i])
for i in range(len(stock)):
stock[i] = (round(stock[i], 2))
stock.insert(i, stock[i])
stock.pop(i+1)
return
print("Welcome to our stock game! You will have options to buy or sell five different
stocks. Try to make as much money as possible!")
response = 0
reslist = [1, 2, 3]

while response not in reslist:


print("Select one amount of buying power you want.")
print("(1) A lot of buying power - $100,000")
print("(2) A medium amount of buying power - $10,000")
print("(3) A little buying power - $1,000")
response = input("\n")
if is_integer(response) == 1:
if int(response) in reslist:
response = int(response)
if response == 1:
money = 100000
elif response == 2:
money = 10000
else:
money = 1000

checkquarters = 0
while checkquarters == 0:
quarter = input("How many quarters (each quarter has the option to buy or sell
stocks) should there be? Select an integer from 3 to 30: \n")
checkquarters = is_integer(quarter)
if checkquarters == 1:
if int(quarter) < 3 or int(quarter) > 30:
checkquarters = 0
print("Out of range!")
quarter = int(quarter)

for i in range(len(list_of_stockprices)):
specific_change_range = listofranges[i]
setstockprices(list_of_stockprices[i],
random.uniform(specific_change_range[0]+0.05, specific_change_range[1]+0.07),
[specific_change_range[0], specific_change_range[1]])

for j in range(1, quarter+1):


print("\nIt is quarter "+str(j)+" out of "+str(quarter)+" quarters.")
if len(purchase_history) != 0:
doneselling = 0
want_to_sell = input("Would you like to sell any stocks? Type Y for yes and
anything else for no. \n")
while doneselling == 0:
if (want_to_sell == "y" or want_to_sell == "Y"):
print("Which stock would you like to sell? (Enter the number only)")
listofstocksbought = []
for i in purchase_history:
if i[0] not in listofstocksbought:
listofstocksbought.append(i[0])
listofstocksbought.sort()
for k in (listofstocksbought):
print("("+str(k+1)+") " + str(stocknamelist[k])+", current price:
$"+str((list_of_stockprices[k])[j-1])+", amount: "+str(numberofshares(k))+" shares")
print("(6) Exit")
sellstocknum = input("\n")
passvar = 0
while passvar == 0:
passvar = is_integer(sellstocknum)
if passvar != 1:
sellstocknum = input("Which stock would you like to sell?
(Enter the number only) \n")
if sellstocknum == "6":
doneselling = 1
break
if int(sellstocknum) > 6 or int(sellstocknum) < 1:
print("Out of range!")
elif sellstocknum == "6":
doneselling = 1
break
elif (int(sellstocknum)-1) not in listofstocksbought:
print("You haven't bought that stock!")
else:
amountearned = sell_stock(int(sellstocknum)-1, j, money)
money += round(amountearned, 2)
print("Your current balance is $"+(str(easyreadmoney(money)+".")))
else:
doneselling = 1
if len(purchase_history) == 0:
break
elif j != 1:
print("You don't have any stocks in your purchase history.")
if j != quarter:
which_stock = input("Would you like to buy stocks this quarter? You have $" +
str(easyreadmoney(money))+". Enter Y for yes and anything else for no. \n")
stillbuying = 0
if which_stock == "Y" or which_stock == "y":
stillbuying = 1
while stillbuying == 1:
notastock = 0
print("Which stock would you like to buy? (Enter the number only)")
print("(1) Appel, price: $"+str((list_of_stockprices[0])[j-1]))
print("(2) S&D 300, price: $"+str((list_of_stockprices[1])[j-1]))
print("(3) Destern Wigital, price: $"+str((list_of_stockprices[2])[j-1]))
print("(4) MacDanolds, price: $"+str((list_of_stockprices[3])[j-1]))
print("(5) AthevanShips, price: $"+str((list_of_stockprices[4])[j-1]))
print("(6) Exit")
stocknum = input("\n")
passvar = 0
while passvar == 0:
passvar = is_integer(stocknum)
if passvar != 1:
stocknum = input("Which stock would you like to buy? (Enter the number
only) \n")
if stocknum == "6":
stillbuying = 0
passvar = 1
break
if int(stocknum) > 6 or int(stocknum) < 0:
print("Out of range!")
notastock = 1
if stocknum != "6" and notastock == 0 and stillbuying == 1:
stocknum = int(stocknum)
stocknum -= 1
temp_stocklist = list_of_stockprices[stocknum]
print("You currently have " + str(easyreadmoney(numberofshares(stocknum)))
+" shares of "+str(stocknamelist[stocknum])+" and $" + str(easyreadmoney(money))+" in
your account.")
money = buy_stock(stocknum, j, money)
nowstockprices = []
for stockquarter in list_of_stockprices:
nowstockprices.append(stockquarter[j-1])
if money < int(min(nowstockprices)):
stillbuying = 0
break
still = input("Would you still like to buy stocks? Type Y for yes and
anything else for no. \n")
stillbuying = 0
if still == "Y" or still == "y":
stillbuying = 1
print("\n \nThe stock simulation has ended. Thanks for playing! \n")
for pastpurchase in purchase_history:
specificstockprice = list_of_stockprices[pastpurchase[0]]
money += specificstockprice[quarter-1] * pastpurchase[2]
if money >= 10000:
print("Great job! You earned $"+str(easyreadmoney(money-10000))+"!")
else:
print("Try harder next time! You lost
$"+str((easyreadmoney((money-10000)*-1))+"."))
print("Your total balance is $"+str(easyreadmoney(money)))

You might also like