Question

In: Computer Science

My code in python keeps failing when the investment is 12 and the market price is...

My code in python keeps failing when the investment is 12 and the market price is 1. I'd like to keep my code, just fix the issue. Thank you.

This is what the automated tests keep saying:

market_price = 1

available_funds = 12

Expected output: Buy 2 shares

Actual output : Hold Shares

We can profit most by buying 2 shares

--------------------------------------------------------------

I'm stopping the tests for now,

because it looks like you still have some work to do.

You should review the test feedback above,

and then work to resolve these issues in your code.

I Ran 7 of 8 test(s).

Your code passed 4 test(s).

Your code failed 3 test(s).

Continue to build on your success,

and focus on creating the simplest code

that will pass just one more test.

Here is my Code:

def trade_action(current_stock, purchase_price, current_price, investment):
# Write your code here.
if purchase_price>= current_price:
investment-=10
number_shares = investment/current_price
profits= (number_shares*current_price-purchase_price)-10
if profits >= 0:
return number_shares
else:
return "Hold Shares"
elif current_price>= purchase_price:
if current_price-purchase_price*current_stock-10>0:
return "Sell Shares"
else:
return "Hold Shares"

As stated. The problem is when the computer inputs 12 for investment and 1 for market share, the program returns Hold Shares, when it is suppose to return purchase 2 shares.

Project Challenge: Automatic Stock Trader

DIRECTIONS

Many investment management companies are switching from manual stock trading done by humans to automatic stock trading by computers. You've been tasked to write a simple automatic stock trader function that determines whether to buy, sell, or do nothing (hold) for a particular account. It should follow the old saying "Buy low, sell high!"

This function takes 4 input parameters in this order:

  1. current_shares - current number of shares of this stock in the account (int).
  2. purchase_price - price (per share) paid for current stock in the account (float).
  3. market_price - current market price (per share) of stock in the account (float).
  4. available_funds - maximum amount the client is willing to spend on a stock purchase (float).

Any transaction (buy or sell) costs $10. This $10 must be paid out of the available_funds for a purchase, or out of the proceeds of a stock sale. Be sure to account for this fee in your profit calculations.

A purchase would be considered profitable when the current market price is lower than the purchase price, and the available funds will allow us to buy enough shares so that the difference in value will cover the $10 transaction fee. In this case the function should return the string "Buy # shares" where # is an integer representing the number of shares to purchase.

A sale would be considered profitable when the current market price is higher than the purchase price, and the value gained by selling the shares will cover the $10 transaction fee. In this case the function should return the string "Sell # shares" where # is an integer representing the number of shares to sell.

If neither a buy nor a sell would be profitable, then the function should return the string "Hold shares."

Here are some test cases that your function should satisfy:  

Test 1 Test 2 Test 3 Test 4 Test 5 Test 6
current_shares 10 20 15 1 10 1
purchase_price 100 2 12 1 1 1
market_price 1 1 1 11 3 12
available_funds 10 21 12 0 30 0
OUTPUT Hold shares Buy 11 shares Buy 2 shares HoldShares Sell 10 shares Sell 1 shares

Rationale for test cases:

Test 1
Even though the current market price is very low (compared to the purchase price), after paying the $10 transaction fee, we would not have any funds left to buy shares; so we can only hold.

Test 2
After paying the $10 transaction fee, there are enough funds remaining to buy 11 shares. At a purchase_price vs. market_price difference of $1 per share, our 11 shares represent a value gain of $11 dollars, which is $1 more than the $10 transaction fee - so we come out $1 ahead.

Test 3
After paying the $10 transaction fee, there are enough funds remaining to buy 2 shares. At a purchase_price vs. market_price difference of $11 per share, our 2 shares represent a value gain of $22 dollars, which is $12 more than the $10 transaction fee - so we come out $12 ahead.

Test 4
Selling our 1 share for $11 will leave us with just $1 after we pay the $10 transaction fee. That is the same as what we paid for it, and we won't make any profit - so we should hold.

Test 5
With a market_price vs. purchase_price vs. difference of $2 per share, we stand to make $20 from the sale of our 10 shares. This is $10 more than the price of the transaction fee, so we will come out $10 ahead - therefore we should sell all 10 shares.

Test 6
Our 1 share is worth $11 more than we paid for it at the current market price. The $11 dollars obtained by selling that share now will still leave us with a profit of $1 after paying the $10 transaction fee. Profit is profit, so we should sell.

Things to think about when you’re designing and writing this program:

  1. Look for opportunities to use variables as a way to name things, and to break larger more complex expressions down into simpler expressions.
  2. Spend some time choosing your names carefully. Names should be descriptive.
  3. Try to design and write your code a few lines at a time. Design and write a few lines, then run some tests to see if these lines are doing what you want them to do. If they are not, then analyze and correct them before you move on to the next few lines of code.

Solutions

Expert Solution

def trade_action(current_stock, purchase_price, current_price, investment):
if purchase_price<= current_price:
spent=purchase_price*current_stock
earned=current_price*current_stock
if earned-10>spent:
return 'Sell '+str(current_stock)+' shares'
else:
return 'Hold shares'
else:
if investment-10<=0:
return 'Hold shares'
else:
remaining=investment-10
sharesToPurchase=remaining//current_price
if sharesToPurchase*(purchase_price-current_price)>10:
return 'Buy '+str(sharesToPurchase)+' shares'
else:
return 'Hold shares'
  
  
  
  
  


Related Solutions

(Python) This is my code for printing a roster for a team. When I print to...
(Python) This is my code for printing a roster for a team. When I print to the console, it makes the first player's name show up as number 2, and it says [] (its just blank for 1). How can I fix that so the first player's name is 1, not skipping 1 and going to 2. def file_to_dictionary(rosterFile): myDictionary={} myDict=[]    with open(rosterFile,'r') as f: for line in f:    (num,first,last,position)=line.split() myDictionary[num]= myDict myDict=[first, last, position] print (myDictionary) return...
I'm having a problem getting my code to function correct, *num_stu keeps losing its value when...
I'm having a problem getting my code to function correct, *num_stu keeps losing its value when ever another function is called from the class. Can someone proof read this for me and let me know what'd up? Header.h file #include <iostream> using namespace std; class report {    private:        int* num_stu;         int xx;        int* id;        double* gpa;    public:                report(int x) {             num_stu = &x;             xx = x;            ...
In Python I have a code: here's my problem, and below it is my code. Below...
In Python I have a code: here's my problem, and below it is my code. Below that is the error I received. Please assist. Complete the swapCaps() function to change all lowercase letters in string to uppercase letters and all uppercase letters to lowercase letters. Anything else remains the same. Examples: swapCaps( 'Hope you are all enjoying October' ) returns 'hOPE YOU ARE ALL ENJOYING oCTOBER' swapCaps( 'i hope my caps lock does not get stuck on' ) returns 'I...
What's wrong with my Python code. We have to find the regularexpression in Python My output...
What's wrong with my Python code. We have to find the regularexpression in Python My output should look like this My IP address 128. 0. 0. 1 My IP address 53. 20. 62. 201 My code ipAddresses = [] ipRegEx = re.compile(r"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")    result = myRegEx.find all(Search Text)    def Regular_expression(ipAddresses)       for i in ipAddresses:          print(i) ipSearchResult = ipRegEx.search(line)    if ipSearchResult != None and ipSearchResult.group() not in ipAddresses:       ipAddresses.append(ipSearchResult.group()) we have to use loop too.
Python I want to name my hero and my alien in my code how do I...
Python I want to name my hero and my alien in my code how do I do that: Keep in mind I don't want to change my code except to give the hero and alien a name import random class Hero:     def __init__(self,ammo,health):         self.ammo=ammo         self.health=health     def blast(self):         print("The Hero blasts an Alien!")         if self.ammo>0:             self.ammo-=1             return True         else:             print("Oh no! Hero is out of ammo.")             return False     def...
In a perfectly competitive market, if the market price is $5 and my price is $5.01,...
In a perfectly competitive market, if the market price is $5 and my price is $5.01, can I sell all my goods?
This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
Trying to score a hand of blackjack in this python code but my loop is consistently...
Trying to score a hand of blackjack in this python code but my loop is consistently outputting (13,1) which makes me think that something is wrong with my loop. Could someone help me with this code?: import random cards = [random.randint(1,13) for i in range(0,2)] #initialize hand with two random cards def get_card(): #this function will randomly return a card with the value between 1 and 13 return random.randint(1,13) def score(cards): stand_on_value = 0 soft_ace = 0 for i in...
this is my code in python I am trying to open a file and then print...
this is my code in python I am trying to open a file and then print the contents on my console but when i run it nothing prints in the console def file_to_dictionary(rosterFile): myDictionary={}    with open(rosterFile,'r') as f: for line in f: myDictionary.append(line.strip()) print(myDictionary)             return myDictionary    file_to_dictionary((f"../data/Roster.txt"))      
Below is my source code for file merging. when i run the code my merged file...
Below is my source code for file merging. when i run the code my merged file is blank and it never shows merging complete prompt. i dont see any errors or why my code would be causing this. i saved both files with male names and female names in the same location my source code is in as a rtf #include #include #include using namespace std; int main() { ifstream inFile1; ifstream inFile2; ofstream outFile1; int mClientNumber, fClientNumber; string mClientName;...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT