Skip to content

Commit 356bf50

Browse files
committed
Add stock data source parameter
Add `force_data_source` parameter to Stock.__init__ allowing manual selection of data source ('twse' or 'tpex'), this also implied that we will not check if the stock ID exist in the database or not. For example, the TPEX has some warrants: 上櫃認購(售)權證,70000U,譜瑞群益39售07 上櫃認購(售)權證,70001U,宣德國票3A售01 which does not exist in the latest codes. Perhaps someone would like to know their history price, if they update the codes, twstock will block them down. But, in this commit, you can explicit passing which data source you want, and implicitly bypass the stock ID check: # Skip stock ID validation (use with caution) stock = twstock.Stock('731120', force_data_source="twse")
1 parent 744fb6c commit 356bf50

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

twstock/stock.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,29 @@ def purify(self, original_data):
160160
return [self._make_datatuple(d) for d in original_data["tables"][0]["data"]]
161161

162162

163+
DATA_FETCHER = {
164+
"twse": TWSEFetcher,
165+
"tpex": TPEXFetcher,
166+
}
167+
168+
163169
class Stock(analytics.Analytics):
164-
def __init__(self, sid: str, initial_fetch: bool = True):
165-
if sid not in codes:
170+
def __init__(
171+
self,
172+
sid: str,
173+
initial_fetch: bool = True,
174+
force_data_source: str = None,
175+
):
176+
"""
177+
Args:
178+
sid (str): Stock ID
179+
initial_fetch (bool): Fetch data when initializing
180+
force_data_source (str): Force data source, can be 'twse' or 'tpex',
181+
if not set, will use the data source from stock codes database,
182+
if set, it also implied that we will not check if the stock ID is in the database.
183+
"""
184+
185+
if force_data_source is None and sid not in codes:
166186
raise StockIDNotFoundError(
167187
f'Stock ID "{sid}" not found in database.\n'
168188
"Either you misspelled it or it is not in the database.\n"
@@ -172,9 +192,9 @@ def __init__(self, sid: str, initial_fetch: bool = True):
172192
)
173193

174194
self.sid = sid
175-
self.fetcher = (
176-
TWSEFetcher() if codes[sid].data_source == "twse" else TPEXFetcher()
177-
)
195+
self.fetcher = DATA_FETCHER.get(
196+
force_data_source if force_data_source else codes[sid].data_source
197+
)()
178198
self.raw_data = []
179199
self.data = []
180200

0 commit comments

Comments
 (0)