Question

Python coding exercise: please include comments Goal #1: import financial data given into your pr...

Python coding exercise: please include comments

Goal #1: import financial data given into your program provided to you as a CSV formatted text file

Use the following data for testing (the following is only a sample of the data; there are over 4000 rows of data):
*Note: The data you will read in is linear by date (but, non-contiguous due to holidays and weekends,) reflecting a timeline of stock performance in chronological order; however your program should run through the days in the data from the earliest date to the most recent

Date Open High Low Close Adj Close Volume
1/3/2000 3.745536 4.017857 3.631696 3.997768 2.69592 1.34E+08
1/4/2000 3.866071 3.950893 3.613839 3.660714 2.468626 1.28E+08
1/5/2000 3.705357 3.948661 3.678571 3.714286 2.504751 1.95E+08
1/6/2000 3.790179 3.821429 3.392857 3.392857 2.287994 1.92E+08
1/7/2000 3.446429 3.607143 3.410714 3.553571 2.396373 1.15E+08

Write the code in the clearest and most efficient way possible however you need to but need the required function named test_data() that relies on calling other functions you have written. It should have the following characteristics:

def test_data(filename, col, day):
    """A test function to query the data you loaded into your program.

    Args:
        filename: A string for the filename containing the stock data,
                  in CSV format.

        col: A string of either "date", "open", "high", "low", "close",
             "volume", or "adj_close" for the column of stock market data to
             look into.

             The string arguments MUST be LOWERCASE!

        day: An integer reflecting the absolute number of the day in the
             data to look up, e.g. day 1, 15, or 1200 is row 1, 15, or 1200
             in the file.

    Returns:
        A value selected for the stock on some particular day, in some
        column col. The returned value *must* be of the appropriate type,
        such as float, int or str.
    """

The code will be tested and should give output similar to the following:

>>> val = test_data("AAPL.csv", "close", 25)
>>> val
4.073661
>>> type(val)

>>>

There should be a main function but it shouldn't do anything yet when called:

def main():
pass # Do nothing, just passing through!
if __name__ == '__main__':
main()

goal #2: write the function transact() that should operate as the docstring describes
*note: you need to look up the pricing of a current day and column before calling this function (choose any column you want)

you can use test_data() to lookup pricing to test transact() only in this section

def transact(funds, stocks, qty, price, buy=False, sell=False):
    """A bookkeeping function to help make stock transactions.

       Args:
           funds: An account balance, a float; it is a value of how much money you have,
                  currently.

           stocks: An int, representing the number of stock you currently own.

           qty: An int, representing how many stock you wish to buy or sell.

           price: An float reflecting a price of a single stock.

           buy: This option parameter, if set to true, will initiate a buy.

           sell: This option parameter, if set to true, will initiate a sell.

       Returns:
           Two values *must* be returned. The first (a float) is the new
           account balance (funds) as the transaction is completed. The second
           is the number of stock now owned (an int) after the transaction is
           complete.

           Error condition #1: If the `buy` and `sell` keyword parameters are both set to true,
           or both false. You *must* print an error message, and then return
           the `funds` and `stocks` parameters unaltered. This is an ambiguous
           transaction request!

           Error condition #2: If you buy, or sell without enough funds or
           stocks to sell, respectively.  You *must* print an error message,
           and then return the `funds` and `stocks` parameters unaltered. This
           is an ambiguous transaction request!
    """
>>> cash_balance = 1000
>>> stocks_owned = 25
>>> price = test_data("AAPL.csv", "close", 42)
>>> price
4.357143
>>>
>>> cash_balance, stocks_owned = transact(cash_balance, stocks_owned, 3, price)
Ambigious transaction! Can't determine whether to buy or sell. No action performed.
>>> print(cash_balance, stocks_owned)
1000 25
>>>


other information:

  1. It would be good form to have separate functions to open, read, and parse the CSV file all to be called inside test_data().
  2. Do not ask the user for a filename. Unit test your function by calling it inside the interpreter with the filename for your data you want to use.
  3. Lists are virtually required here, so make sure you call help(list) in the Python interpreter to know what a list can do for you!
  4. You will not be allowed to edit the CSV file directly. You can only change the data after you read it in using your Python program.
  5. The stock data isn’t contiguous in its dates listed. You will have gaps that correspond to weekends or market holidays. Do not count those missing dates as part of your day number counting.
0 0
Add a comment Improve this question Transcribed image text
Answer #1
stocks = 0
funds = 1000

def test_data(filename, col, day):

    Date = []
    Open = []
    High = []
    Low = []
    Close = []
    AdjClose = []
    Volume = []
    
    file = open(filename, "r")
    file.readline() # to get rid of titles
    for line in file:

        temp = line.split(",")
        Date.append(temp[0])
        Open.append(temp[1])
        High.append(temp[2])
        Low.append(temp[3])  
        Close.append(temp[4])  
        AdjClose.append(temp[5])  
        Volume.append(temp[6])  
    
    if col == 'date':
        return float(Date[day-1])
    elif col == 'open':
        return float(Open[day-1])
    elif col == 'high':
        return float(High[day-1])
    elif col == 'low':
        return float(Low[day-1])
    elif col == 'close':
        return float(Close[day-1])
    elif col == 'adj_close':
        return float(AdjClose[day-1])
    elif col == 'volume':
        return float(Volume[day-1])
    
    
def transact(funds1, stocks1, qty, price, buy=False, sell=False):
    global funds
    global stocks
    
    if buy == sell:
        #print("Ambigious transaction! Can't determine whether to buy or sell. No action performed.")    
        return funds, stocks
    elif buy and funds >= qty*price:
        funds -= qty*price
        stocks += qty
        #print("Insufficient funds")
        return funds, stocks
    elif sell and stocks >= qty:
        funds += qty*price
        stocks -= qty
        #print("Insufficient stock")
        return funds, stocks

def alg_moving_average(filename):
    global funds
    global stocks
    
    Prices = [] #open column for prices
    file = open(filename, "r")
    file.readline() # to get rid of titles
    for line in file:
        temp = line.split(",")
        Prices.append(float(temp[1]))

    i = 21
    while i < len(Prices):
        total = 0
    
        j = i-21
        while j < i:
            total += Prices[j]
            j += 1
            
        movAvg = total/20
        
        if i == len(Prices):
            transact(funds, stocks, stocks, Prices[i], buy=False, sell=True)
        elif Prices[i] > movAvg*1.05:
            transact(funds, stocks, 10, Prices[i], buy=False, sell=True)
        elif Prices[i] < movAvg*0.95:
            transact(funds, stocks, 10, Prices[i], buy=True, sell=False)
        i += 1
        
    transact(funds, stocks, stocks, Prices[i-1], buy=False, sell=True)
    
    return(stocks, funds)
    
def main():
    
    global funds
    global stocks
    
    stocks = 0
    funds = 1000
    
    filename = input("Enter a filename for stock data (CSV format): ")
    alg1_stocks, alg1_balance = alg_moving_average(filename)
    
    print("The results are: " + str(alg1_stocks) + " stocks, balance of " + str(alg1_balance))

    stocks = 0
    funds = 1000
    
    
    #not sure why it makes 1359100 for AAPL, but only 5187 for MSFT
main()

if __name__ == '__name__':
    main()
Add a comment
Know the answer?
Add Answer to:
Python coding exercise: please include comments Goal #1: import financial data given into your pr...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT