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:
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()
Python coding exercise: please include comments Goal #1: import financial data given into your pr...
Coding for Python – don’t need it to be complex: In this assignment, your goal is to write a Python program to determine whether a given pattern appears in a data series, and if so, where it is located in the data series. This type of problem is common in many health disciplines. For example, identifying treatment pathways. The goal is to detect whether a certain pattern appears in the data series. In the following example, the pattern to be...
PROGRAMING IN C. PLEASE HELP FIX MY CODE TO FIT THE FOLLOWING CRITERIA: 1.)Read your stocks from your mystocks.txt file. You can use this information for the simulator. 2.)The stock price simulator will return the current price of the stock. The current prices is the prices of the requested ticker + a random number. 3.)We will assume that the stock price remains constant after the price check till your trade gets executed. Therefore, a buy or a sell order placed...
Requires Python to answer A client wishes to keep track of his investment in shares. Write a program to help him manage his stock portfolio. You are to record both the shares that he is holding as well as shares that he has sold. For shares be is curreatly holding, record the following data: .a 3-character share code, share name, last purchase date, volume currently held and average purchase price (refer to description under part cii) option 2) For shares...
Kindly answer Question 1-4 with well structured paragraphs. Alibaba-China's Ecommerce Giant: Challenging Amazon? TODAY, ALIBABA GROUP is the largest Chinese ecommerce company. In the original Arabic tale of Ali Baba and the Forty Thieves, Ali Baha, the poor woodcutter, opened the cave with hidden treasure by calling out the magic words "Open Sesame." Alibaba's founder selected the name to open up opportunities for small Chinese manufacturers to sell their goods around the world, with the hope of finding treasures for...