I have a file "Dow.txt"
formated as follows: name, symbol, exchange, industry, value0, value1, value2, value3
for each of the 30 stocks in the Dow Jones Industrial Average.
How can I determine the best and worst-performing stocks in 2013 with regards to percentage growth? The possible outcome as shown below:
Best performing stock: stock name, percentage of growth
Worst performing stock: stock name, percentage of growth
I don't know how to tell the program to know which is the start price and which is the end price, so I don't know how to begin with the calculation.
So the tasks are:
the file link as below: https://drive.google.com/file/d/107pPSYgSrjEVdqR7QZW1W2l6QP8n-18g/view?usp=sharing
Here's one possible solution without using any imports:
def lines(file: str):
with open(file) as f:
for line in f:
yield line
def parse(lines):
for line in lines:
yield line.split(",")
def get_percentage_growth(path):
line = lines(path)
best = {"name": None, "percentage": float('-inf')}
worst = {"name": None, "percentage": float('inf')}
for row in parse(line):
first, second = float(row[4]), float(row[5])
percentage = (second-first)/first * 100
if percentage > best["percentage"]:
best["name"] = row[0]
best["percentage"] = percentage
if percentage < worst["percentage"]:
worst["name"] = row[0]
worst["percentage"] = percentage
return best, worst
if __name__ == '__main__':
f = "data.txt"
b, w = get_percentage_growth(f)
print(f'Best performing stock: {b["name"]}, {b["percentage"]}')
print(f'Worst performing stock: {w["name"]}, {w["percentage"]}')
assuming that the python file is located in the same directory as the data.txt file, this hsould work. The benefit is that this method is able to deal with files of TB due to the generators.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments