Python stock portfolio program - python

I'm not sure if I needed to post all of this but I thought I would include it all just in case. The assignment that I'm working on uses 3 dictionaries and functions to allow the user to add stocks, recommend a sale, and exit I'm currently having a problem with my GetSale or recommend sale function. The GetSale function should find the maximum expected value of selling a stock. The expected sale value of a stock is the current profit minus the future value of the stock:
Expected Sale value = ( ( Current Price - Buy Price ) - Risk * CurrentPrice ) * Shares
The GetSale function should calculate this value for each stock in the portfolio, and return the stock symbol with the highest expected sale value. When I call the GetSale function with option 2 under the Main function I always get "Highest selling stock is with a 0 profit margin." even after entering in different stocks. Is my GetSale function coded so that is what it returns and its not even checking the dictionary I'm new to this so not exactly sure where I went wrong.
Names = {}
Prices = {}
Exposure = {}
def AddName(StockNames, StockPrices, StockExposure):
TheStockName = input("Input stock name. ")
Prompt = "Input the stock symbol for " + TheStockName
Symbol = input(Prompt)
StockNames[Symbol] = TheStockName
StockPrices[Symbol] = None
StockExposure[Symbol] = None
return StockNames
def AddPrices(StockPrices):
while True:
Symbol = input("Input stock symbol for the stock and add price next. ")
if Symbol in Prices:
Prompt = input("Current buying price of " + Symbol + ": ")
BuyPrice = float(Prompt)
Prompt = input("Current selling price of " + Symbol + ": ")
SellPrice = float(Prompt)
StockPrices[Symbol] = [BuyPrice, SellPrice]
return StockPrices
else:
print("This stock does not exist.")
def AddExposure(StockExposure):
while True:
Symbol = input("Input stock symbol for the stock and add exposure next. ")
if Symbol in Exposure:
Prompt = input("Current number of " + Symbol + " stocks that have been purchased? ")
SharesOwned = float(Prompt)
Prompt = input("Current risk factor of " + Symbol + " share ownership? ")
RiskFactor = float(Prompt)
StockExposure[Symbol] = [SharesOwned, RiskFactor]
return StockExposure
else:
print("This stock does not exist.")
def AddStock():
AddName(Names, Prices, Exposure)
AddPrices(Prices)
AddExposure(Exposure)
def GetSale(Names, Prices, Exposure):
HighestStock = 0
HighestStockName = ''
for Stock in Names:
TotalProfit = ((Prices[Stock][1] - Prices[Stock][0]) - Exposure[Stock][1] * Prices[Stock] [0]) * Exposure[Stock][0]
if (TotalProfit > HighestStock):
HighestStock = TotalProfit
HighestStockName = Stock
print("Highest selling stock is", HighestStockName, "with a ", HighestStock, "profit margin.")
def Main():
keepGoing = True
while keepGoing:
print("Menu")
print("1: Add a stock")
print("2: Find the highest sale price")
print("3: Exit")
userResponseString = input("Input selection (1, 2 or 3): ")
try:
userInput = int(userResponseString)
except:
print("Invalid input.")
userChoice = 0
if (userInput == 1):
AddStock()
elif (userInput == 2):
GetSale(Names, Prices, Exposure)
else:
(userInput == 3)
print("Ending stock program.")
keepGoing = False
Main()

Related

how i can solve : can't multiply sequence by non-int of type 'float' (python)

i'm just newbie for python , can anyone help me this code, im stuck for a week for this problem
here my code:
price = {
"Espresso": 5.80,
"Americano": 6.90,
}
currency = "$"
print ("welcome coffee machine!\t")
name = input ("can i get your name?\n")
print ("what do you like to order mr/ms " + name + "\n" )
menu = ("Espresso, Americano")
print (menu)
menu = (input())
quantity = input("How many " + menu + " would you like?\n")
quantity = str(input())
#im stuck at here! T_T
if menu == "Espresso" :
price = 5.80
total = quantity * price
quantity.append(quantity)
price.append(price)
print(total)
elif menu == "Americano":
price = 6.90
total = quantity * price
quantity.append(quantity)
price.append(price)
print(total)
else:
menu()
#invoice receipt
print("Thank you for order " + name + ", please wait your " + menu + " at counter\n")
hopefully someone/somebody can help me to solve this problem T_T
You are getting error because of this line:
quantity = str(input())
price = 5.80
total = quantity * price
You are multiplying string with float.
TypeError: can't multiply sequence by non-int of type 'float'
thank you for you help, i found my answer
here the correct code:
menu = "Espresso, Americano"
print (menu)
order = input()
#changed the quantity variable to an integer so that it can be used in mathematical operations!
quantity = int(input("How many " + order + " would you like?\n"))
#added a total variable and called the calculate_total function to calculate the total
# price based on the quantity and price of the order.
def calculate_total(quantity, price):
total = quantity * price
return total
total = calculate_total(quantity, price[order])

Calculate the total of tickets and give a discount to student. There is a problem with function of the calculation the total and loops

Ticket sales. Calculate the total, based on the number of half price and full price tickets. If the user is a student, give a 50 cent discount for each ticket. Ask user to input number of child tickets, number of adult tickets, and if the person is a student (y/n). Keep asking until user enters a 0 and a 0
FULL_PRICE = 10.00
HALF_PRICE = FULL_PRICE % 2
giveDiscount = True
def calculatePrice(nHalfPriceTix, nFullPriceTix, giveDiscount):
if giveDiscount:
total = (nHalfPriceTix * HALF_PRICE) + (nFullPriceTix * FULL_PRICE) - .5
else:
total = (nHalfPriceTix * HALF_PRICE) + (nFullPriceTix * FULL_PRICE)
return total
while True:
print()
nChildTickets = input('How many child tickets do you want? ')
nChildTickets = int(nChildTickets)
nAdultTickets = input('How many adult tickets do you want? ')
nAdultTickets = int(nAdultTickets)
if (nChildTickets == 0) or (nAdultTickets == 0):
break
yesOrNo = input('Are you a student (y/n)? ')
if yesOrNo.lower() == 'y':
isStudent = True
else:
isStudent = False
thisTotal = calculatePrice(nChildTickets, nAdultTickets)
print('Your total is $' + thisTotal)
print()
totalSales = totalSales + thisTotal
print('Total of all sales $', totalSales)
Also to add on, this:
print('Your total is $' + thisTotal)
should be:
print('Your total is $' + str(thisTotal))
since the '+' operator in print() can only accept strings(not a float).
Or you could change the + to a ,.
calculatePrice function requires 3 arguments and got only two:
thisTotal = calculatePrice(nChildTickets, nAdultTickets)
so i think for that to work you need to pass isStudent because you didnt use it
thisTotal = calculatePrice(nChildTickets, nAdultTickets,isStudent)

Return multiple values in a function

I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]

overlapping variable doesn't change variable

I can't even explain. Here is my code
foods = {12345670 : 'orange(s)',
87654325 : 'pineapple(s)'}
loop = 10
while loop == 10:
full_list = input("Type: ")
if full_list == 'end':
break
amount = int(input("Amount: "))
subtotal = 0
item = int(full_list)
if item in foods:
print("That would be {} {}".format(amount, foods[item]))
if full_list == '12345670':
price = (0.50 * amount)
print("Added Orange(s)")
print("Added "+str(price))
subtotal = subtotal + price
if full_list == '87654325':
price = (1.00 * amount)
subtotal = subtotal + price
print("Added Pineapple(s)")
print("Added "+str(price))
print("Your subtotal is " +str(subtotal))
I'm trying to get my subtotal to change accordingly to what the user purchases, I haven't finished making my list of purchasable items and so I don't want to change the name of the variable every time. What is the problem here? Why doesn't the variable subtotal change?
foods = {12345670 : 'orange(s)',
87654325 : 'pineapple(s)'}
loop = 10
subtotal = 0 # <------ moved it outside of the while loop
while loop == 10:
full_list = input("Type: ")
if full_list == 'end':
break
amount = int(input("Amount: "))
item = int(full_list)
if item in foods:
print("That would be {} {}".format(amount, foods[item]))
if full_list == '12345670':
price = (0.50 * amount)
print("Added Orange(s)")
print("Added "+str(price))
subtotal = subtotal + price
if full_list == '87654325': #should be an elif not an if
price = (1.00 * amount)
subtotal = subtotal + price
print("Added Pineapple(s)")
print("Added "+str(price))
print("Your subtotal is " +str(subtotal))
Every time you looped you restarted the total cost to 0 and it only kept the latest price. Move it outside of the while loop where I commented and you should be fine. Also use elif if you want to chain similar if statements together.
You have the following
if full_list == '12345670'
But it will never enter this if statement because your input type is an integer not a string. Do this without the single quotes instead:
if full_list == 12345670

AttributeError: 'str' object has no attribute (function)

I'm trying to write an object-oriented program that allows me to enter and store monthly income and bills, and view all data as needed. I can successfully store an object, but when I try to use my view_all function, I get this error:
in view_all print(item.get_month())
AttributeError: 'str' object has no attribute 'get_month'
If you could help me track down this problem I'd be grateful!
# Create a month class
class Month:
# Use __init__ method to initialize the attributes
def __init__(self, month, income, tds, pnm, zia, water):
self.__month = month
self.__income = income
self.__tds = tds
self.__pnm = pnm
self.__zia = zia
self.__water = water
# The set methods accept arguments:
def set_month(self, month):
self.__month = month
def set_income(self, income):
self.__income = income
def set_tds(self, tds):
self.__tds = tds
def set_pnm(self, pnm):
self.__pnm = pnm
def set_zia(self, zia):
self.__zia = zia
def set_water(self, water):
self.__water = water
# The get methods return the data:
def get_month(self):
return self.__month
def get_income(self):
return self.__income
def get_tds(self):
return self.__tds
def get_pnm(self):
return self.__pnm
def get_zia(self):
return self.__zia
def get_water(self):
return self.__water
# The __str__ method return's the object's state as a string
def __str__(self):
return "Month: " + self.__month + \
"\nIncome: " + self.__income + \
"\nTDS: " + self.__tds + \
"\nPNM: " + self.__PNM + \
"\nZia: " + self.__zia + \
"\nWater: " + self.__water
And the main program:
import Month_Class
import pickle
ADD_MONTH = 1
VIEW_ALL = 2
QUIT = 3
FILENAME = 'ruidoso.dat'
def main():
months = load_months()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == ADD_MONTH:
add_month(months)
elif choice == VIEW_ALL:
view_all(months)
save_months(months)
def load_months():
try:
input_file = open(FILENAME, 'rb')
months_dct = pickle.load(input_file)
input_file.close
except IOError:
month_dct = {}
return month_dct
def get_menu_choice():
print()
print('Menu')
print('------------------')
print("1. Add data for a new month")
print("2. View data for all months")
print('Any other number saves and quits the program!')
print()
choice = int(input('Enter your choice: '))
while choice < ADD_MONTH or choice > QUIT:
choice = int(input('Enter a valid choice: '))
return choice
def add_month(months):
month = input('Enter the name of the month: ')
income = input('Total income for this month: ')
tds = input('TDS Broadband bill total: ')
pnm = input('PNM bill total: ')
zia = input('Zia Natural Gas bill total: ')
water = input('City of Ruidoso bill total: ')
entry = Month_Class.Month(month, income, tds, pnm, zia, water)
if month not in months:
months[month] = entry
print('The entry has been added')
else:
print('That month already exists!')
def save_months(months):
output_file = open(FILENAME, 'wb')
pickle.dump(months, output_file)
output_file.close()
def view_all(months):
for item in months:
print(item.get_month())
print(item.get_income())
print(item.get_tds())
print(item.get_pnm())
print(item.get_zia())
print(item.get_water())
main()
You need to iterate over the dictionary differently
for month, item in months.items():
print(item.get_month())
...
In the view_all method, you must to iterate over dictionary:
for key, item in months.iteritems():
print(item.get_month())
and you got other error in __str__ method of Month class:
"\nPNM: " + self.__PNM + \
the correct is:
"\nPNM: " + self.__pnm + \

Categories