-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproj2.py
More file actions
133 lines (103 loc) · 3.91 KB
/
Copy pathproj2.py
File metadata and controls
133 lines (103 loc) · 3.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import csv
# Hardcoded dictionary of stock prices
STOCK_PRICES = {
"AAPL": 180,
"TSLA": 250,
"GOOGL": 140,
"AMZN": 175,
"MSFT": 420,
"META": 480,
}
def display_available_stocks():
print("\nAvailable Stocks and Prices ($):")
print("-" * 30)
for stock, price in STOCK_PRICES.items():
print(f"{stock:<10} ${price}")
print("-" * 30)
def get_portfolio():
"""Collect stock names and quantities from the user."""
portfolio = {}
print("\nEnter the stocks you own. Type 'done' when finished.")
while True:
stock = input("\nEnter stock symbol (or 'done' to finish): ").upper().strip()
if stock == "DONE":
break
if stock not in STOCK_PRICES:
print(f"'{stock}' not found in our price list. Please choose from the available stocks.")
continue
try:
quantity = int(input(f"Enter quantity of {stock} you own: "))
if quantity < 0:
print("Quantity cannot be negative. Try again.")
continue
except ValueError:
print("Please enter a valid whole number for quantity.")
continue
# Add to portfolio (accumulate if stock entered more than once)
portfolio[stock] = portfolio.get(stock, 0) + quantity
return portfolio
def calculate_investment(portfolio):
"""Calculate value per stock and total investment."""
details = []
total = 0
for stock, quantity in portfolio.items():
price = STOCK_PRICES[stock]
value = price * quantity
total += value
details.append((stock, quantity, price, value))
return details, total
def display_summary(details, total):
print("\n" + "=" * 50)
print("PORTFOLIO SUMMARY")
print("=" * 50)
print(f"{'Stock':<10}{'Qty':<8}{'Price($)':<12}{'Value($)':<10}")
print("-" * 50)
for stock, quantity, price, value in details:
print(f"{stock:<10}{quantity:<8}{price:<12}{value:<10}")
print("-" * 50)
print(f"Total Investment: ${total:,.2f}")
print("=" * 50)
def save_to_file(details, total):
"""Save the portfolio summary to a .txt or .csv file."""
choice = input("\nSave results to a file? (y/n): ").lower().strip()
if choice != "y":
return
file_format = input("Choose format - 'txt' or 'csv': ").lower().strip()
if file_format == "csv":
filename = "portfolio_summary.csv"
with open(filename, mode="w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Stock", "Quantity", "Price ($)", "Value ($)"])
for stock, quantity, price, value in details:
writer.writerow([stock, quantity, price, value])
writer.writerow([])
writer.writerow(["Total Investment", "", "", total])
print(f"Portfolio saved to {filename}")
elif file_format == "txt":
filename = "portfolio_summary.txt"
with open(filename, mode="w") as f:
f.write("PORTFOLIO SUMMARY\n")
f.write("=" * 50 + "\n")
f.write(f"{'Stock':<10}{'Qty':<8}{'Price($)':<12}{'Value($)':<10}\n")
f.write("-" * 50 + "\n")
for stock, quantity, price, value in details:
f.write(f"{stock:<10}{quantity:<8}{price:<12}{value:<10}\n")
f.write("-" * 50 + "\n")
f.write(f"Total Investment: ${total:,.2f}\n")
print(f"Portfolio saved to {filename}")
else:
print("Invalid format. Skipping file save.")
def main():
print("=" * 50)
print("Welcome to the Stock Portfolio Tracker")
print("=" * 50)
display_available_stocks()
portfolio = get_portfolio()
if not portfolio:
print("\nNo stocks entered. Exiting.")
return
details, total = calculate_investment(portfolio)
display_summary(details, total)
save_to_file(details, total)
if __name__ == "__main__":
main()