3 from typing import Dict, List, Optional, Tuple
4 import yfinance as yf # type: ignore
10 class stock_quote_renderer(renderer.debuggable_abstaining_renderer):
11 """Render the stock prices page."""
15 name_to_timeout_dict: Dict[str, int],
17 display_subs: Dict[str, str] = None,
19 super(stock_quote_renderer, self).__init__(name_to_timeout_dict, False)
20 self.symbols = symbols
21 self.display_subs = display_subs
23 def debug_prefix(self) -> str:
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"]
33 def get_price(ticker: yf.ticker.Ticker) -> Optional[float]:
34 """Get most recent price of a ticker."""
43 info = ticker.get_info()
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])
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."""
59 info = ticker.get_info()
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)
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%>")
74 for symbol in self.symbols:
75 ticker = yf.Ticker(symbol)
77 # print(ticker.get_info())
79 self.debug_print(f"Unknown symbol {symbol} -- ignored.")
81 name = stock_quote_renderer.get_ticker_name(ticker)
82 price = stock_quote_renderer.get_price(ticker)
84 self.debug_print(f"No price information for {symbol} -- skipped.")
86 (percent_change, delta) = stock_quote_renderer.get_change_and_delta(
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:
96 if self.display_subs is not None and symbol in self.display_subs:
97 symbol = self.display_subs[symbol]
100 <TD WIDTH=20% HEIGHT=150 BGCOLOR="{cell_color}">
102 <DIV style="position:relative;
104 <!-- Symbol {symbol} -->
105 <DIV style="position:absolute;
108 -webkit-transform:rotate(-90deg);
110 font-family: helvetica, arial, sans-serif;
112 -webkit-text-stroke: 2px black;
116 <!-- Current price, Change today and percent change today, name -->
117 <DIV style="position:absolute;
121 font-family: helvetica, arial, sans-serif;
124 <I>({percent_change:.1f}%)</I><BR>
130 f.write("</TR></TABLE>")
134 #x = stock_quote_renderer({}, ["MSFT", "GOOG", "BTC-USD", "OPTAX", "GC=F", "VNQ"], { "BTC-USD": "BTC", "GC=F": "GOLD" })
135 #x.periodic_render(None)