Spaces:
Running
Running
Update app.py
Browse filesAdded date to stock report & handled exceptions
app.py
CHANGED
@@ -63,36 +63,56 @@ def Client():
|
|
63 |
return OpenAI(api_key = key)
|
64 |
|
65 |
def get_stock_report():
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
return rv
|
82 |
|
83 |
def get_last_closing(symbol, timeout=10):
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
|
97 |
def create_stock_data_file(txt):
|
98 |
with open(stock_data_path, 'wt') as fp:
|
|
|
63 |
return OpenAI(api_key = key)
|
64 |
|
65 |
def get_stock_report():
|
66 |
+
try:
|
67 |
+
stock_data = {}
|
68 |
+
global stock_data_path
|
69 |
+
error_msg = ''
|
70 |
+
with open(stock_data_path, 'rt') as fp:
|
71 |
+
lines = fp.readlines()
|
72 |
+
for line in lines:
|
73 |
+
(name, symbol, shares) = line.rstrip().split(',')
|
74 |
+
name = name.strip()
|
75 |
+
symbol = symbol.strip()
|
76 |
+
shares = shares.strip()
|
77 |
+
stock_data[symbol] = {"symbol": symbol, "name": name, "shares": shares, "closing": '0'}
|
78 |
+
for symbol in stock_data.keys():
|
79 |
+
(closing_price, closing_date) = get_last_closing(symbol)
|
80 |
+
if closing_price == 0:
|
81 |
+
error_msg += f'Error getting closing for {symbol}\n'
|
82 |
+
stock_data[symbol]['closing'] = f'{closing_price:.2f}'
|
83 |
+
total_value = 0.0
|
84 |
+
rv = f'At closing on {closing_date}:\n'
|
85 |
+
for item in stock_data.values():
|
86 |
+
rv += str(item) + '\n'
|
87 |
+
total_value += float(item['closing']) * float(item['shares'])
|
88 |
+
rv += (f'\nTotal value = {total_value:.2f}\n')
|
89 |
+
if len(error_msg) > 0:
|
90 |
+
rv += error_msg
|
91 |
+
except:
|
92 |
+
rv = 'Error getting stock report'
|
93 |
return rv
|
94 |
|
95 |
def get_last_closing(symbol, timeout=10):
|
96 |
+
try:
|
97 |
+
today = datetime.today()+timedelta(days=1)
|
98 |
+
five_days_ago = today - timedelta(days=5)
|
99 |
+
end = today.strftime('%Y-%m-%d')
|
100 |
+
start = five_days_ago.strftime('%Y-%m-%d')
|
101 |
+
df = yf.download(symbol,
|
102 |
+
start = start,
|
103 |
+
end = end,
|
104 |
+
progress = False,
|
105 |
+
timeout=timeout,
|
106 |
+
)
|
107 |
+
# print(df)
|
108 |
+
closing_date = 'unknown'
|
109 |
+
data_top = df.tail(1)
|
110 |
+
for row in data_top.index:
|
111 |
+
closing_date = row.strftime('%Y-%m-%d')
|
112 |
+
# print(closing_date)
|
113 |
+
return (df.iat[-1,1], closing_date)
|
114 |
+
except:
|
115 |
+
return (0.0, "0000-00-00")
|
116 |
|
117 |
def create_stock_data_file(txt):
|
118 |
with open(stock_data_path, 'wt') as fp:
|