4 from typing import Dict, List, Optional, Tuple
6 import yfinance as yf # type: ignore
12 logger = logging.getLogger(__file__)
15 class stock_quote_renderer(renderer.abstaining_renderer):
16 """Render the stock prices page."""
20 name_to_timeout_dict: Dict[str, int],
22 display_subs: Dict[str, str] = None,
24 super().__init__(name_to_timeout_dict)
25 self.symbols = symbols
26 self.display_subs = display_subs
29 def get_ticker_name(ticker: yf.ticker.Ticker) -> str:
30 """Get friendly name of a ticker."""
31 info = ticker.get_info()
32 if "shortName" in info:
33 return info["shortName"]
37 def get_price(ticker: yf.ticker.Ticker) -> Optional[float]:
38 """Get most recent price of a ticker."""
47 info = ticker.get_info()
49 if key in info and info[key] is not None and info[key] != 0.0:
50 print(f"Price: picked {key}, ${info[key]}.")
51 return float(info[key])
55 def get_change_and_delta(
56 ticker: yf.ticker.Ticker, price: float
57 ) -> Tuple[float, float]:
58 """Given the current price, look up opening price and compute delta."""
63 info = ticker.get_info()
65 if key in info and info[key] is not None:
66 print(f"Change: picked {key}, ${info[key]}.")
67 old_price = float(info[key])
68 delta = price - old_price
69 return (delta / old_price * 100.0, delta)
72 def periodic_render(self, key: str) -> bool:
73 """Write an up-to-date stock page."""
74 with file_writer.file_writer("stock_3_86400.html") as f:
75 f.write("<H1>Stock Quotes</H1><HR>")
76 f.write("<TABLE WIDTH=99%>")
78 for symbol in self.symbols:
79 ticker = yf.Ticker(symbol)
80 # print(ticker.get_info())
82 logger.debug(f"Unknown symbol {symbol} -- ignored.")
84 name = stock_quote_renderer.get_ticker_name(ticker)
85 price = stock_quote_renderer.get_price(ticker)
87 logger.debug(f"No price information for {symbol} -- skipped.")
89 (percent_change, delta) = stock_quote_renderer.get_change_and_delta(
92 # print(f"delta: {delta}, change: {percent_change}")
93 cell_color = "#b00000" if percent_change < 0 else "#009000"
94 if symbols_finished % 4 == 0:
95 if symbols_finished > 0:
99 if self.display_subs is not None and symbol in self.display_subs:
100 symbol = self.display_subs[symbol]
103 <TD WIDTH=20% HEIGHT=150 BGCOLOR="{cell_color}">
105 <DIV style="position:relative;
107 <!-- Symbol {symbol} -->
108 <DIV style="position:absolute;
111 -webkit-transform:rotate(-90deg);
113 font-family: helvetica, arial, sans-serif;
115 -webkit-text-stroke: 2px black;
119 <!-- Current price, Change today and percent change today, name -->
120 <DIV style="position:absolute;
124 font-family: helvetica, arial, sans-serif;
127 <I>({percent_change:.1f}%)</I><BR>
133 f.write("</TR></TABLE>")
137 #x = stock_quote_renderer({}, ["MSFT", "GOOG", "BTC-USD", "OPTAX", "GC=F", "VNQ"], { "BTC-USD": "BTC", "GC=F": "GOLD" })
138 #x.periodic_render(None)