Move the kiosk server to another machine; changes needed to make it work there.
[kiosk.git] / stock_renderer.py
1 #!/usr/bin/env python3
2
3 from typing import Dict, List, Optional, Tuple
4 import yfinance as yf  # type: ignore
5
6 import file_writer
7 import renderer
8
9
10 class stock_quote_renderer(renderer.debuggable_abstaining_renderer):
11     """Render the stock prices page."""
12
13     def __init__(
14             self,
15             name_to_timeout_dict: Dict[str, int],
16             symbols: List[str],
17             display_subs: Dict[str, str] = None,
18     ) -> None:
19         super(stock_quote_renderer, self).__init__(name_to_timeout_dict, False)
20         self.symbols = symbols
21         self.display_subs = display_subs
22
23     def debug_prefix(self) -> str:
24         return "stock"
25
26     @staticmethod
27     def get_ticker_name(ticker: yf.ticker.Ticker) -> str:
28         """Get friendly name of a ticker."""
29         info = ticker.get_info()
30         return info["shortName"]
31
32     @staticmethod
33     def get_price(ticker: yf.ticker.Ticker) -> Optional[float]:
34         """Get most recent price of a ticker."""
35         keys = [
36             "bid",
37             "ask",
38             "regularMarketPrice",
39             "lastMarket",
40             "open",
41             "previousClose",
42         ]
43         info = ticker.get_info()
44         for key in keys:
45             if key in info and info[key] is not None and info[key] != 0.0:
46                 print(f"Price: picked {key}, ${info[key]}.")
47                 return float(info[key])
48         return None
49
50     @staticmethod
51     def get_change_and_delta(
52         ticker: yf.ticker.Ticker, price: float
53     ) -> Tuple[float, float]:
54         """Given the current price, look up opening price and compute delta."""
55         keys = [
56             "open",
57             "previousClose",
58         ]
59         info = ticker.get_info()
60         for key in keys:
61             if key in info and info[key] is not None:
62                 print(f"Change: picked {key}, ${info[key]}.")
63                 old_price = float(info[key])
64                 delta = price - old_price
65                 return (delta / old_price * 100.0, delta)
66         return (0.0, 0.0)
67
68     def periodic_render(self, key: str) -> bool:
69         """Write an up-to-date stock page."""
70         with file_writer.file_writer("stock_3_86400.html") as f:
71             f.write("<H1>Stock Quotes</H1><HR>")
72             f.write("<TABLE WIDTH=99%>")
73             symbols_finished = 0
74             for symbol in self.symbols:
75                 ticker = yf.Ticker(symbol)
76                 print(type(ticker))
77                 # print(ticker.get_info())
78                 if ticker is None:
79                     self.debug_print(f"Unknown symbol {symbol} -- ignored.")
80                     continue
81                 name = stock_quote_renderer.get_ticker_name(ticker)
82                 price = stock_quote_renderer.get_price(ticker)
83                 if price is None:
84                     self.debug_print(f"No price information for {symbol} -- skipped.")
85                     continue
86                 (percent_change, delta) = stock_quote_renderer.get_change_and_delta(
87                     ticker, price
88                 )
89                 # print(f"delta: {delta}, change: {percent_change}")
90                 cell_color = "#b00000" if percent_change < 0 else "#009000"
91                 if symbols_finished % 4 == 0:
92                     if symbols_finished > 0:
93                         f.write("</TR>")
94                         f.write("<TR>")
95                 symbols_finished += 1
96                 if self.display_subs is not None and symbol in self.display_subs:
97                     symbol = self.display_subs[symbol]
98                 f.write(
99                     f"""
100 <TD WIDTH=20% HEIGHT=150 BGCOLOR="{cell_color}">
101   <!-- Container -->
102   <DIV style="position:relative;
103               height:150px;">
104     <!-- Symbol {symbol} -->
105     <DIV style="position:absolute;
106                 bottom:50;
107                 right:-20;
108                 -webkit-transform:rotate(-90deg);
109                 font-size:28pt;
110                 font-family: helvetica, arial, sans-serif;
111                 font-weight:900;
112                 -webkit-text-stroke: 2px black;
113                 color: #ddd">
114       {symbol}
115     </DIV>
116     <!-- Current price, Change today and percent change today, name -->
117     <DIV style="position:absolute;
118                 left:10;
119                 top:20;
120                 font-size:23pt;
121                 font-family: helvetica, arial, sans-serif;
122                 width:70%">
123             ${price:.2f}<BR>
124             <I>({percent_change:.1f}%)</I><BR>
125             <B>${delta:.2f}</B>
126     </DIV>
127   </DIV>
128 </TD>"""
129                 )
130             f.write("</TR></TABLE>")
131         return True
132
133 # Test
134 #x = stock_quote_renderer({}, ["MSFT", "GOOG", "BTC-USD", "OPTAX", "GC=F", "VNQ"], { "BTC-USD": "BTC", "GC=F": "GOLD" })
135 #x.periodic_render(None)