-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStockReport.py
More file actions
237 lines (198 loc) · 7.57 KB
/
Copy pathStockReport.py
File metadata and controls
237 lines (198 loc) · 7.57 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""
Fetch and format stock reports for LEDarcade terminal scrolling.
"""
import os
import re
import traceback
from configparser import ConfigParser
KeyConfigFileName = "KeyConfig.ini"
DEFAULT_SYMBOLS = ["TSLA", "MSFT", "AAPL"]
STOCK_TYPE_SPEED = 0.064
STOCK_SCROLL_REPEAT = 2
STOCK_POST_SCROLL_WAIT = 0
STOCK_HEADER_RGB = (200, 200, 0)
STOCK_SYMBOL_RGB = (200, 0, 200)
STOCK_BLANK_LINES_BEFORE_FIRST = 1
STOCK_BLANK_LINES_BETWEEN = 2
def CheckConfigFiles():
if os.path.exists(KeyConfigFileName):
return
try:
with open(KeyConfigFileName, "a+") as config_file:
config_file.write("[KEYS]\n")
config_file.write("STOCK_SYMBOLS = TSLA,MSFT,AAPL\n")
config_file.write("\n")
print(f"[StockReport] Created default {KeyConfigFileName}")
except Exception as error:
print(f"[StockReport] Could not create {KeyConfigFileName}: {error}")
def ParseStockSymbols(symbols):
if symbols is None:
return None
if isinstance(symbols, str):
raw_symbols = re.split(r"[,\s]+", symbols.strip())
elif isinstance(symbols, (list, tuple)):
raw_symbols = symbols
else:
return None
parsed = []
for symbol in raw_symbols:
cleaned = str(symbol).strip().upper()
if cleaned:
parsed.append(cleaned)
return parsed or None
def LoadStockSymbols(symbols_override=None):
parsed = ParseStockSymbols(symbols_override)
if parsed:
return parsed
CheckConfigFiles()
if not os.path.exists(KeyConfigFileName):
return DEFAULT_SYMBOLS.copy()
try:
key_file = ConfigParser()
key_file.read(KeyConfigFileName)
raw = key_file.get("KEYS", "STOCK_SYMBOLS", fallback=",".join(DEFAULT_SYMBOLS))
symbols = [symbol.strip().upper() for symbol in raw.split(",") if symbol.strip()]
return symbols or DEFAULT_SYMBOLS.copy()
except Exception as error:
print(f"[StockReport] Config read error: {error}")
return DEFAULT_SYMBOLS.copy()
def _FormatChangePercent(change_percent):
if change_percent is None:
return None
try:
value = float(change_percent)
except (TypeError, ValueError):
return None
if abs(value) <= 1:
value *= 100
return value
def _FormatPrice(value):
if value is None:
return None
try:
return f"${float(value):.2f}"
except (TypeError, ValueError):
return None
def _FormatLargeCount(value):
if value is None:
return None
try:
number = float(value)
except (TypeError, ValueError):
return None
abs_number = abs(number)
if abs_number >= 1_000_000_000_000:
return f"{number / 1_000_000_000_000:.2f}T"
if abs_number >= 1_000_000_000:
return f"{number / 1_000_000_000:.2f}B"
if abs_number >= 1_000_000:
return f"{number / 1_000_000:.2f}M"
if abs_number >= 1_000:
return f"{number / 1_000:.2f}K"
return f"{int(number)}"
def _FormatMarketCap(value):
formatted = _FormatLargeCount(value)
if formatted is None:
return None
return f"${formatted}"
def _JoinParts(parts):
return " ".join(part for part in parts if part)
def _FormatSymbolEntry(symbol, info):
price = info.get("regularMarketPrice")
if price is None:
return {"symbol": symbol, "detail_lines": ["Data unavailable."]}
try:
price_value = float(price)
except (TypeError, ValueError):
return {"symbol": symbol, "detail_lines": ["Data unavailable."]}
name = info.get("shortName") or info.get("longName") or symbol
change = info.get("regularMarketChange")
change_percent = _FormatChangePercent(info.get("regularMarketChangePercent"))
price_parts = [f"Price ${price_value:.2f}"]
if change is not None:
try:
change_value = float(change)
sign = "+" if change_value >= 0 else ""
price_parts.append(f"{sign}{change_value:.2f} today")
except (TypeError, ValueError):
pass
if change_percent is not None:
price_parts.append(f"({change_percent:+.2f} pct)")
lines = [
name,
_JoinParts(price_parts),
_JoinParts([
f"Open {_FormatPrice(info.get('regularMarketOpen'))}" if _FormatPrice(info.get('regularMarketOpen')) else None,
f"High {_FormatPrice(info.get('regularMarketDayHigh'))}" if _FormatPrice(info.get('regularMarketDayHigh')) else None,
f"Low {_FormatPrice(info.get('regularMarketDayLow'))}" if _FormatPrice(info.get('regularMarketDayLow')) else None,
]),
_JoinParts([
f"Prev close {_FormatPrice(info.get('regularMarketPreviousClose'))}" if _FormatPrice(info.get('regularMarketPreviousClose')) else None,
f"Volume {_FormatLargeCount(info.get('regularMarketVolume'))}" if _FormatLargeCount(info.get('regularMarketVolume')) else None,
f"Avg vol {_FormatLargeCount(info.get('averageVolume'))}" if _FormatLargeCount(info.get('averageVolume')) else None,
]),
_JoinParts([
f"52 week low {_FormatPrice(info.get('fiftyTwoWeekLow'))}" if _FormatPrice(info.get('fiftyTwoWeekLow')) else None,
f"high {_FormatPrice(info.get('fiftyTwoWeekHigh'))}" if _FormatPrice(info.get('fiftyTwoWeekHigh')) else None,
]),
_JoinParts([
f"Market cap {_FormatMarketCap(info.get('marketCap'))}" if _FormatMarketCap(info.get('marketCap')) else None,
f"PE {float(info.get('trailingPE')):.2f}" if info.get("trailingPE") is not None else None,
f"Fwd PE {float(info.get('forwardPE')):.2f}" if info.get("forwardPE") is not None else None,
]),
_JoinParts([
f"Bid {_FormatPrice(info.get('bid'))}" if _FormatPrice(info.get('bid')) else None,
f"Ask {_FormatPrice(info.get('ask'))}" if _FormatPrice(info.get('ask')) else None,
f"Yield {float(info.get('dividendYield')) * 100:.2f} pct" if info.get("dividendYield") is not None else None,
]),
_JoinParts([
info.get("fullExchangeName") or info.get("exchange"),
info.get("currency"),
]),
]
detail_lines = [line for line in lines if line]
return {"symbol": symbol, "detail_lines": detail_lines}
def FetchSymbolInfo(symbol):
try:
import yfinance as yf
except ImportError as error:
print(f"[StockReport] yfinance not installed: {error}")
return None
try:
ticker = yf.Ticker(symbol)
info = ticker.info or {}
if not info:
return None
return info
except Exception as error:
print(f"[StockReport] Fetch failed for {symbol}: {error}")
return None
def FetchStockReport(symbols=None):
"""Fetch stock data and return a scrollable header/body report."""
symbol_list = LoadStockSymbols(symbols)
stock_lines = []
errors = []
for symbol in symbol_list:
info = FetchSymbolInfo(symbol)
if info:
stock_lines.append(_FormatSymbolEntry(symbol, info))
else:
errors.append(symbol)
if not stock_lines and errors:
return {
"header": "",
"body": f"Stock data unavailable for {', '.join(errors)}.",
"stock_lines": [],
}
body_parts = []
for entry in stock_lines:
body_parts.append(entry["symbol"])
body_parts.extend(entry.get("detail_lines", []))
if errors:
body_parts.append(f"Unavailable: {', '.join(errors)}.")
return {
"header": "Stock report.",
"body": " ".join(body_parts),
"stock_lines": stock_lines,
"errors": errors,
}