Question

In: Computer Science

The problem is below. This is for an intro to Python class, so, if possible keep...

The problem is below. This is for an intro to Python class, so, if possible keep it relatively simple and 'basic.'

The code in bold below is given:

def trade_action(current_stock, purchase_price, current_price, investment):
# Write your code here.
return "Hold Shares."

Instructions:

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

Code is as follows:

#trade action function to calculate the decision

def trade_action(current_shares , purchase_price, market_price , available_funds ):

    differenceInPrice = market_price - purchase_price

    #Let's see the purchase option first

    if (differenceInPrice < 0):

        #calculate the funds available after fees

        fund_after_fees_deduction = available_funds-10

        # calculate number of shares to be bought

        no_of_share = fund_after_fees_deduction // market_price

       

        #if number of share > 0 then bought the shares else hold

        if (no_of_share > 0):

            return "Buy " + str(no_of_share) + " shares"

        else:

            return "Hold Shares."

           

    elif (differenceInPrice > 0):

        #Calculate the profit amount

        profit_Amount = current_shares * differenceInPrice

        #deduct the fees from profit

        profit_after_fees_deduction = profit_Amount - 10;

        #if profit is there then sell the shares else hold

        if (profit_after_fees_deduction > 0):

            return "Sell " + str(current_shares) + " shares"

        else:

            return "Hold Shares."

    else:

        return "Hold Shares."

       

#driver program with the given values

print("result for test 1")

print(trade_action(10,100,1,10))

print("result for test 2")

print(trade_action(20,2,1,21))

print("result for test 3")

print(trade_action(15,12,1,12))

print("result for test 4")

print(trade_action(1,1,11,0))

print("result for test 5")

print(trade_action(10,1,3,30))

print("result for test 6")

print(trade_action(1,1,12,0))

Screen shot for code for your reference for indentation:

Output:

In case of any query, do comment.

Please rate your answer. Thanks


Related Solutions

USE C++ and please keep program as simple as possible and also comment so it is...
USE C++ and please keep program as simple as possible and also comment so it is easy to understad Create a structure called time. Its three members, all type int, should be called hours, minutes, and seconds. Write a program that prompts the user to enter a time value in hours, minutes, and seconds. This should be in 12:59:59 format. This entire input should be assigned first to a string variable. Then the string should be tokenized thereby assigning the...
I have a quick question about this C ++ problem in my intro class. I have...
I have a quick question about this C ++ problem in my intro class. I have been able to get the first answer consistently when I test it, but my second seems to either be high or low no matter how I change it. Can you show me how you would do this problem with the setprecision(2) Paula and Danny want to plant evergreen trees along the back side of their yard. They do not want to have an excessive...
answer in basic JAVA im in and INTRO JAVA CLASS Problem 2: Point of Sale System...
answer in basic JAVA im in and INTRO JAVA CLASS Problem 2: Point of Sale System The McDowell Restaurant chain has asked you to write a menu program for their new Fast-food service machines. Your program already prints the following menu like this: ********************************************************************** McDowell’s Restaurant ********************************************************************** Make your selection from the menu below: 1. Regular Hamburger $1.50 2. Regular Cheeseburger $1.75 3. Fish Sandwich $2.50 4. Half-pounder with cheese $2.75 5. French Fries $0.99 6. Large Soft Drink $1.25...
in python please ,, A SOON AS POSSIBLE PLEASE #Class invariant for SimpleQueue, a queue based...
in python please ,, A SOON AS POSSIBLE PLEASE #Class invariant for SimpleQueue, a queue based on a linked list # 1. The queue is a linked list of ListNode objects. # 2. A SimpleQueue object has instance variables self.head, a reference to the node at the front of the queue, self.tail, a reference # to the node at the end of the queue, and self.size, the number of nodes in the queue. # 3. If self.size = 0, then...
Python class DLLNode: """ Class representing a node in the doubly linked list implemented below. """...
Python class DLLNode: """ Class representing a node in the doubly linked list implemented below. """ def __init__(self, value, next=None, prev=None): """ Constructor @attribute value: the value to give this node @attribute next: the next node for this node @attribute prev: the previous node for this node """ self.__next = next self.__prev = prev self.__value = value def __repr__(self): return str(self.__value) def __str__(self): return str(self.__value) def get_value(self): """ Getter for value :return: the value of the node """ return self.__value...
Python: What are the defintions of the three method below for a class Date? class Date(object):...
Python: What are the defintions of the three method below for a class Date? class Date(object): "Represents a Calendar date"    def __init__(self, day=0, month=0, year=0): "Initialize" pass def __str__(self): "Return a printable string representing the date: m/d/y" pass    def before(self, other): "Is this date before that?"
​​​​​​This is an assignment that I'm having trouble figuring out in python: Modify Node class so...
​​​​​​This is an assignment that I'm having trouble figuring out in python: Modify Node class so it has a field called frequency and initialize it as one. Add a search function. If a number is in the list, return its frequency. Modify Insert function. Remove push, append, and insertAfter as one function called insert(self, data). If you insert a data that is already in the list, simply increase this node’s frequency. If the number is not in the list, add...
Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def...
Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def __init__(self, DataObject): self.data = DataObject self.parents = None self.left_child = None self.right_child = None @property def left_child(self): return self.__left_child @left_child.setter def left_child(self, node): self.__left_child = node if node is not None: node.parents = self @property def right_child(self): return self.__right_child @right_child.setter def right_child(self, node): self.__right_child = node if node is not None: node.parents = self def is_leafNode(self): if self.left_child is None and self.right_child is None:...
Python I am creating a class in python. Here is my code below: import csv import...
Python I am creating a class in python. Here is my code below: import csv import json population = list() with open('PopChange.csv', 'r') as p: reader = csv.reader(p) next(reader) for line in reader: population.append(obj.POP(line)) population.append(obj.POP(line)) class POP: """ Extract the data """ def __init__(self, line): self.data = line # get elements self.id = self.data[0].strip() self.geography = self.data[1].strip() self.targetGeoId = self.data[2].strip() self.targetGeoId2 = self.data[3].strip() self.popApr1 = self.data[4].strip() self.popJul1 = self.data[5].strip() self.changePop = self.data[6].strip() The problem is, I get an error saying:  ...
PYTHON - please finish the methods below that are apart of a linkedlist class #return the...
PYTHON - please finish the methods below that are apart of a linkedlist class #return the data value at index(position) in the list. values remain unchanged def __getpos__(self, position): #do not change, checks for valid index if self.size == 0: raise IndexError elif position is None: return self.pop(self.size - 1) elif type(position) != int: raise TypeError elif position < 0 or position >= self.size: raise IndexError #replace the data value at requested position(index). return nothing def __setpos__(self,position,value): #do not change,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT