vfinance 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- vfinance/__init__.py +7 -0
- vfinance/_cache.py +246 -0
- vfinance/_dnse.py +360 -0
- vfinance/_utils.py +302 -0
- vfinance/models.py +110 -0
- vfinance/py.typed +0 -0
- vfinance/stocks.py +198 -0
- vfinance/utils.py +44 -0
- vfinance-0.1.0.dist-info/METADATA +194 -0
- vfinance-0.1.0.dist-info/RECORD +12 -0
- vfinance-0.1.0.dist-info/WHEEL +4 -0
- vfinance-0.1.0.dist-info/licenses/LICENSE.md +21 -0
vfinance/__init__.py
ADDED
vfinance/_cache.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Private, domain-based storage for reusable temporary values."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from threading import RLock
|
|
5
|
+
from time import monotonic
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import cachetools
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Cache",
|
|
12
|
+
"CacheEntry",
|
|
13
|
+
"create_domain",
|
|
14
|
+
"delete_domain",
|
|
15
|
+
"set",
|
|
16
|
+
"get",
|
|
17
|
+
"delete",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
_DEFAULT_MAX_SIZE = 1000
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class CacheEntry:
|
|
25
|
+
"""A cached value and its lifetime.
|
|
26
|
+
|
|
27
|
+
Attributes:
|
|
28
|
+
value (Any): The original value, held by reference.
|
|
29
|
+
ttl (int): Lifetime in seconds. Non-positive integers disable expiry;
|
|
30
|
+
non-integers, including booleans, become 0.
|
|
31
|
+
expires_at (float | None): Monotonic-clock deadline, or None when expiry
|
|
32
|
+
is disabled. This is not a Unix timestamp.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
value: Any
|
|
36
|
+
ttl: int = 0
|
|
37
|
+
expires_at: float | None = field(init=False)
|
|
38
|
+
|
|
39
|
+
def __post_init__(self) -> None:
|
|
40
|
+
ttl = self.ttl
|
|
41
|
+
if isinstance(ttl, bool) or not isinstance(ttl, int):
|
|
42
|
+
ttl = 0
|
|
43
|
+
expires_at = None
|
|
44
|
+
if ttl > 0:
|
|
45
|
+
try:
|
|
46
|
+
expires_at = monotonic() + ttl
|
|
47
|
+
except OverflowError:
|
|
48
|
+
# This clock cannot reach an unrepresentably long lifetime.
|
|
49
|
+
expires_at = float("inf")
|
|
50
|
+
object.__setattr__(self, "ttl", ttl)
|
|
51
|
+
object.__setattr__(self, "expires_at", expires_at)
|
|
52
|
+
|
|
53
|
+
def is_expired(self) -> bool:
|
|
54
|
+
"""Check whether this value has reached the end of its lifetime.
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
bool: True at or after the deadline; False when expiry is disabled
|
|
58
|
+
or the deadline has not been reached.
|
|
59
|
+
"""
|
|
60
|
+
return self.expires_at is not None and monotonic() >= self.expires_at
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Cache:
|
|
64
|
+
"""Reuse values within one bounded cache domain.
|
|
65
|
+
|
|
66
|
+
Notes:
|
|
67
|
+
Each instance owns one LRU store. Access is synchronized across threads,
|
|
68
|
+
but stored values are not copied or protected against external mutation.
|
|
69
|
+
Expired entries are removed when read; there is no background cleanup.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def __init__(self, max_size: int = _DEFAULT_MAX_SIZE) -> None:
|
|
73
|
+
"""Create bounded storage for one independent cache domain.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
max_size (int): Maximum number of entries, default 1000.
|
|
77
|
+
Non-positive or non-integer values, including booleans, use
|
|
78
|
+
1000 instead.
|
|
79
|
+
|
|
80
|
+
Notes:
|
|
81
|
+
The capacity is fixed for the lifetime of this instance.
|
|
82
|
+
Constructing an instance does not register a named domain.
|
|
83
|
+
"""
|
|
84
|
+
if isinstance(max_size, bool) or not isinstance(max_size, int) or max_size <= 0:
|
|
85
|
+
max_size = _DEFAULT_MAX_SIZE
|
|
86
|
+
self._cache: cachetools.LRUCache[str, CacheEntry] = cachetools.LRUCache(
|
|
87
|
+
maxsize=max_size
|
|
88
|
+
)
|
|
89
|
+
self._lock = RLock()
|
|
90
|
+
|
|
91
|
+
def set(self, key: str, value: Any, ttl: int = 0) -> None:
|
|
92
|
+
"""Store a reusable value or remove it when None is supplied.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
key (str): Cache key, used unchanged within the domain.
|
|
96
|
+
value (Any): Value to retain by reference. None deletes the key.
|
|
97
|
+
ttl (int): Lifetime in seconds, default 0. Non-positive or
|
|
98
|
+
non-integer values, including booleans, disable expiry.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
None: The value is stored, or the key is silently removed.
|
|
102
|
+
|
|
103
|
+
Notes:
|
|
104
|
+
Every write restarts the lifetime, even for the same key and value.
|
|
105
|
+
When full, the domain evicts its least recently used entry.
|
|
106
|
+
"""
|
|
107
|
+
with self._lock:
|
|
108
|
+
if value is None:
|
|
109
|
+
self._cache.pop(key, None)
|
|
110
|
+
else:
|
|
111
|
+
self._cache[key] = CacheEntry(value=value, ttl=ttl)
|
|
112
|
+
|
|
113
|
+
def get(self, key: str) -> Any | None:
|
|
114
|
+
"""Retrieve a retained value while its lifetime remains valid.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
key (str): Cache key, used unchanged within the domain.
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
Any | None: The original value, or None when the key is missing or
|
|
121
|
+
the entry has expired. Expired entries are removed.
|
|
122
|
+
|
|
123
|
+
Notes:
|
|
124
|
+
A successful read marks the entry as recently used without
|
|
125
|
+
extending its lifetime.
|
|
126
|
+
"""
|
|
127
|
+
with self._lock:
|
|
128
|
+
entry = self._cache.get(key)
|
|
129
|
+
if entry is None:
|
|
130
|
+
return None
|
|
131
|
+
if entry.is_expired():
|
|
132
|
+
del self._cache[key]
|
|
133
|
+
return None
|
|
134
|
+
return entry.value
|
|
135
|
+
|
|
136
|
+
def delete(self, key: str) -> None:
|
|
137
|
+
"""Discard a value without requiring it to exist.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
key (str): Cache key, used unchanged within the domain.
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
None: The key is removed; a missing key is ignored.
|
|
144
|
+
"""
|
|
145
|
+
with self._lock:
|
|
146
|
+
self._cache.pop(key, None)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
_domains: dict[str, Cache] = {}
|
|
150
|
+
_domains_lock = RLock()
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def create_domain(domain: str, max_size: int = _DEFAULT_MAX_SIZE) -> None:
|
|
154
|
+
"""Reserve shared storage for a named group of related values.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
domain (str): Domain name, used unchanged.
|
|
158
|
+
max_size (int): Maximum number of entries, default 1000. Non-positive
|
|
159
|
+
or non-integer values, including booleans, use 1000 instead.
|
|
160
|
+
|
|
161
|
+
Returns:
|
|
162
|
+
None: A Cache instance is registered, or the existing one is retained.
|
|
163
|
+
|
|
164
|
+
Notes:
|
|
165
|
+
Named domains are shared by all callers in this process. cachetools
|
|
166
|
+
exposes a read-only maxsize, so existing contents and capacity remain
|
|
167
|
+
unchanged. Delete and recreate a domain to change its limit.
|
|
168
|
+
"""
|
|
169
|
+
with _domains_lock:
|
|
170
|
+
if domain not in _domains:
|
|
171
|
+
_domains[domain] = Cache(max_size=max_size)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def delete_domain(domain: str) -> None:
|
|
175
|
+
"""Discard a named domain and all values owned by it.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
domain (str): Domain name, used unchanged.
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
None: The registered Cache instance is removed; a missing domain is
|
|
182
|
+
ignored.
|
|
183
|
+
"""
|
|
184
|
+
with _domains_lock:
|
|
185
|
+
_domains.pop(domain, None)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def set(domain: str, key: str, value: Any, ttl: int = 0) -> None:
|
|
189
|
+
"""Store a reusable value in a shared domain or remove it when None is supplied.
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
domain (str): Domain name, used unchanged. A missing domain is created
|
|
193
|
+
with a capacity of 1000, even when value is None.
|
|
194
|
+
key (str): Cache key, used unchanged within the domain.
|
|
195
|
+
value (Any): Value to retain by reference. None deletes the key.
|
|
196
|
+
ttl (int): Lifetime in seconds, default 0. Non-positive or non-integer
|
|
197
|
+
values, including booleans, disable expiry.
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
None: The value is stored, or the key is silently removed.
|
|
201
|
+
|
|
202
|
+
Notes:
|
|
203
|
+
Every write restarts the lifetime, even for the same key and value.
|
|
204
|
+
When full, the domain evicts its least recently used entry.
|
|
205
|
+
"""
|
|
206
|
+
with _domains_lock:
|
|
207
|
+
create_domain(domain)
|
|
208
|
+
cache = _domains[domain]
|
|
209
|
+
cache.set(key, value, ttl=ttl)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def get(domain: str, key: str) -> Any | None:
|
|
213
|
+
"""Retrieve a retained value from a shared domain while it remains valid.
|
|
214
|
+
|
|
215
|
+
Args:
|
|
216
|
+
domain (str): Domain name, used unchanged.
|
|
217
|
+
key (str): Cache key, used unchanged within the domain.
|
|
218
|
+
|
|
219
|
+
Returns:
|
|
220
|
+
Any | None: The original value, or None when the domain or key is missing
|
|
221
|
+
or the entry has expired. Expired entries are removed.
|
|
222
|
+
|
|
223
|
+
Notes:
|
|
224
|
+
A successful read updates LRU order without extending the lifetime.
|
|
225
|
+
Missing domains are not created.
|
|
226
|
+
"""
|
|
227
|
+
with _domains_lock:
|
|
228
|
+
cache = _domains.get(domain)
|
|
229
|
+
return cache.get(key) if cache is not None else None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def delete(domain: str, key: str) -> None:
|
|
233
|
+
"""Discard a value from a shared domain without requiring it to exist.
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
domain (str): Domain name, used unchanged.
|
|
237
|
+
key (str): Cache key, used unchanged within the domain.
|
|
238
|
+
|
|
239
|
+
Returns:
|
|
240
|
+
None: The key is removed; a missing domain or key is ignored.
|
|
241
|
+
Missing domains are not created.
|
|
242
|
+
"""
|
|
243
|
+
with _domains_lock:
|
|
244
|
+
cache = _domains.get(domain)
|
|
245
|
+
if cache is not None:
|
|
246
|
+
cache.delete(key)
|
vfinance/_dnse.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"""Private module to fetch VN stock market data from DNSE/Entrade"""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
from datetime import datetime, timedelta, timezone
|
|
6
|
+
|
|
7
|
+
from . import _utils, models, utils
|
|
8
|
+
|
|
9
|
+
__all__ = ["get_info", "get_quote", "get_history"]
|
|
10
|
+
|
|
11
|
+
_BASE_URL = "https://api.dnse.com.vn/"
|
|
12
|
+
_MARKET_TIMEZONE = timezone(timedelta(hours=7), "Asia/Ho_Chi_Minh")
|
|
13
|
+
_SECONDS_PER_DAY = 24 * 60 * 60
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def get_info(ticker: str) -> models.SymbolInfo | None:
|
|
17
|
+
"""Retrieve a VN stock symbol profile from DNSE/Entrade.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
ticker (str): CODE, EXCHANGE:CODE, or CODE.VN, such as fpt,
|
|
21
|
+
HOSE:FPT, or FPT.VN. Case and surrounding whitespace are ignored.
|
|
22
|
+
CODE may contain single dots between nonempty ASCII alphanumeric
|
|
23
|
+
parts, such as ABC.Z, but must not end with .VN. Exchange prefixes
|
|
24
|
+
contain only ASCII letters and cannot be combined with .VN.
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
vfinance.models.SymbolInfo | None: An immutable profile containing the
|
|
28
|
+
symbol, reported exchange, company names, instrument type, index
|
|
29
|
+
membership, and available GICS classifications. Returns None for
|
|
30
|
+
HTTP 404 or no matching symbol.
|
|
31
|
+
|
|
32
|
+
Raises:
|
|
33
|
+
TypeError: ticker is not a string.
|
|
34
|
+
RuntimeError: The lookup returns an HTTP error other than 404.
|
|
35
|
+
json.JSONDecodeError: The response is not valid JSON.
|
|
36
|
+
ValueError: ticker is empty or malformed, the response structure or
|
|
37
|
+
required symbol, exchange, or company name is invalid, a supplied
|
|
38
|
+
profile field is not text, or the HTTP content encoding is unsupported.
|
|
39
|
+
urllib.error.URLError: A connection or redirect failure occurs.
|
|
40
|
+
OSError: A socket timeout, response-reading failure, or invalid gzip
|
|
41
|
+
response occurs.
|
|
42
|
+
http.client.HTTPException: An HTTP response is invalid or incomplete.
|
|
43
|
+
EOFError: A compressed response is truncated.
|
|
44
|
+
zlib.error: A compressed response cannot be decoded.
|
|
45
|
+
asyncio.CancelledError: The task awaiting this lookup is canceled.
|
|
46
|
+
"""
|
|
47
|
+
symbol = utils.normalize_ticker(ticker)
|
|
48
|
+
|
|
49
|
+
response = await _utils.fetch_url_async(
|
|
50
|
+
f"{_BASE_URL.rstrip('/')}/market-api/tickers?symbol={symbol}"
|
|
51
|
+
)
|
|
52
|
+
if response.status == 404:
|
|
53
|
+
return None
|
|
54
|
+
if not response.is_successful():
|
|
55
|
+
raise RuntimeError(f"DNSE ticker lookup returned HTTP {response.status}")
|
|
56
|
+
|
|
57
|
+
payload = json.loads(response.content)
|
|
58
|
+
if not isinstance(payload, dict) or not isinstance(payload.get("data"), list):
|
|
59
|
+
raise ValueError("DNSE ticker response must contain a data list")
|
|
60
|
+
|
|
61
|
+
for entry in payload["data"]:
|
|
62
|
+
if not isinstance(entry, dict):
|
|
63
|
+
raise ValueError("DNSE ticker entries must be objects")
|
|
64
|
+
entry_symbol = _get_text(entry, "symbol")
|
|
65
|
+
if not entry_symbol:
|
|
66
|
+
raise ValueError("DNSE ticker entry is missing its symbol")
|
|
67
|
+
if entry_symbol.upper() != symbol:
|
|
68
|
+
continue
|
|
69
|
+
|
|
70
|
+
exchange = _get_text(entry, "floor")
|
|
71
|
+
name = _get_text(entry, "companyName")
|
|
72
|
+
if not exchange or not exchange.strip() or not name or not name.strip():
|
|
73
|
+
raise ValueError("DNSE ticker entry is missing its exchange or name")
|
|
74
|
+
symbol_type = _get_text(entry, "type")
|
|
75
|
+
index_code = _get_text(entry, "indexCode")
|
|
76
|
+
return models.SymbolInfo(
|
|
77
|
+
exchange=exchange.upper(),
|
|
78
|
+
symbol=symbol,
|
|
79
|
+
name=name,
|
|
80
|
+
overview="",
|
|
81
|
+
english_name=_get_text(entry, "companyNameEng"),
|
|
82
|
+
short_name=_get_text(entry, "shortName"),
|
|
83
|
+
symbol_type=symbol_type.upper() if symbol_type is not None else None,
|
|
84
|
+
index_code=index_code.upper() if index_code is not None else None,
|
|
85
|
+
industry=_get_text(entry, "gicsIndustry"),
|
|
86
|
+
sub_industry=_get_text(entry, "gicsSubIndustry"),
|
|
87
|
+
sector=_get_text(entry, "gicsSector"),
|
|
88
|
+
industry_group=_get_text(entry, "gicsIndustryGroup"),
|
|
89
|
+
industry_group_slug=_get_text(entry, "gicsIndustryGroupSlug"),
|
|
90
|
+
)
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _get_text(entry: dict[str, object], field: str) -> str | None:
|
|
95
|
+
value = entry.get(field)
|
|
96
|
+
if value is None or isinstance(value, str):
|
|
97
|
+
return value
|
|
98
|
+
raise ValueError(f"DNSE ticker field {field!r} must be text or null")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
async def get_quote(ticker: str) -> models.StockQuote | None:
|
|
102
|
+
"""Retrieve a VN stock symbol quote from DNSE/Entrade.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
ticker (str): CODE, EXCHANGE:CODE, or CODE.VN, such as fpt,
|
|
106
|
+
HOSE:FPT, or FPT.VN. Case and surrounding whitespace are ignored.
|
|
107
|
+
CODE may contain single dots between nonempty ASCII alphanumeric
|
|
108
|
+
parts, such as ABC.Z, but must not end with .VN. Exchange prefixes
|
|
109
|
+
contain only ASCII letters and cannot be combined with .VN.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
vfinance.models.StockQuote | None: A quote summarizing the returned
|
|
113
|
+
one-minute bars, with the latest Asia/Ho_Chi_Minh timestamp, prices
|
|
114
|
+
in VND, and total traded-unit volume. The reported listing exchange
|
|
115
|
+
is uppercase. A null closing price remains None, with market_price
|
|
116
|
+
using the last bar's opening price instead. Returns None for an invalid or
|
|
117
|
+
missing symbol, an error response without the required quote fields,
|
|
118
|
+
an unavailable listing profile, or no quote within today and the
|
|
119
|
+
previous 14 days.
|
|
120
|
+
|
|
121
|
+
Raises:
|
|
122
|
+
TypeError: ticker is not a string.
|
|
123
|
+
RuntimeError: The HTTP lookup fails, other than HTTP 404 or an error
|
|
124
|
+
response without the required quote fields.
|
|
125
|
+
json.JSONDecodeError: A successful HTTP response is not valid JSON.
|
|
126
|
+
ValueError: ticker is empty or malformed, the volume array is missing,
|
|
127
|
+
quote arrays are inconsistent, a timestamp, price, volume, or
|
|
128
|
+
listing field is invalid, pagination cannot move backward, or
|
|
129
|
+
the HTTP content encoding is unsupported.
|
|
130
|
+
urllib.error.URLError: A connection or redirect failure occurs.
|
|
131
|
+
OSError: A socket timeout, response-reading failure, or invalid gzip
|
|
132
|
+
response occurs.
|
|
133
|
+
http.client.HTTPException: An HTTP response is invalid or incomplete.
|
|
134
|
+
EOFError: A compressed response is truncated.
|
|
135
|
+
zlib.error: A compressed response cannot be decoded.
|
|
136
|
+
asyncio.CancelledError: The task awaiting this lookup is canceled.
|
|
137
|
+
"""
|
|
138
|
+
symbol = utils.normalize_ticker(ticker)
|
|
139
|
+
now = datetime.now(_MARKET_TIMEZONE)
|
|
140
|
+
start = int(now.replace(hour=0, minute=0, second=0, microsecond=0).timestamp())
|
|
141
|
+
end = int(now.timestamp())
|
|
142
|
+
earliest_start = start - 14 * _SECONDS_PER_DAY
|
|
143
|
+
fields = ("t", "o", "h", "l", "c", "v")
|
|
144
|
+
|
|
145
|
+
while True:
|
|
146
|
+
if start < earliest_start:
|
|
147
|
+
return None
|
|
148
|
+
response = await _utils.fetch_url_async(
|
|
149
|
+
f"{_BASE_URL.rstrip('/')}/chart-api/v2/ohlcs/stock"
|
|
150
|
+
f"?symbol={symbol}&resolution=1&from={start}&to={end}"
|
|
151
|
+
)
|
|
152
|
+
if response.status == 404:
|
|
153
|
+
return None
|
|
154
|
+
try:
|
|
155
|
+
payload = json.loads(response.content)
|
|
156
|
+
except json.JSONDecodeError:
|
|
157
|
+
if not response.is_successful():
|
|
158
|
+
raise RuntimeError(
|
|
159
|
+
f"DNSE quote lookup returned HTTP {response.status}"
|
|
160
|
+
) from None
|
|
161
|
+
raise
|
|
162
|
+
if not isinstance(payload, dict) or any(
|
|
163
|
+
field not in payload for field in ("t", "o", "h", "l", "c")
|
|
164
|
+
):
|
|
165
|
+
return None
|
|
166
|
+
if not response.is_successful():
|
|
167
|
+
raise RuntimeError(f"DNSE quote lookup returned HTTP {response.status}")
|
|
168
|
+
if "v" not in payload:
|
|
169
|
+
raise ValueError("DNSE quote response must contain a volume array")
|
|
170
|
+
|
|
171
|
+
columns = [payload[field] for field in fields]
|
|
172
|
+
if all(column is None for column in columns):
|
|
173
|
+
return None
|
|
174
|
+
if any(not isinstance(column, list) for column in columns):
|
|
175
|
+
raise ValueError("DNSE quote fields must be arrays")
|
|
176
|
+
if any(len(column) != len(columns[0]) for column in columns):
|
|
177
|
+
raise ValueError("DNSE quote arrays must have matching lengths")
|
|
178
|
+
if columns[0]:
|
|
179
|
+
break
|
|
180
|
+
|
|
181
|
+
next_time = _get_quote_number(payload.get("nextTime"), "nextTime")
|
|
182
|
+
if next_time != int(next_time):
|
|
183
|
+
raise ValueError("DNSE quote nextTime must use whole seconds")
|
|
184
|
+
next_time = int(next_time)
|
|
185
|
+
if next_time == 0 or next_time < earliest_start:
|
|
186
|
+
return None
|
|
187
|
+
if next_time >= end:
|
|
188
|
+
raise ValueError("DNSE quote pagination must move backward")
|
|
189
|
+
end = next_time
|
|
190
|
+
start -= _SECONDS_PER_DAY
|
|
191
|
+
# Reversed ranges produce the same null arrays as invalid symbols.
|
|
192
|
+
while start > end:
|
|
193
|
+
start -= _SECONDS_PER_DAY
|
|
194
|
+
|
|
195
|
+
timestamp = _get_quote_number(columns[0][-1], "t")
|
|
196
|
+
try:
|
|
197
|
+
quote_time = datetime.fromtimestamp(timestamp, tz=_MARKET_TIMEZONE)
|
|
198
|
+
except (OverflowError, OSError) as error:
|
|
199
|
+
raise ValueError("DNSE quote timestamp is out of range") from error
|
|
200
|
+
open_price = _get_quote_price(columns[1][0], "o")
|
|
201
|
+
high_price = max(_get_quote_price(value, "h") for value in columns[2])
|
|
202
|
+
low_price = min(_get_quote_price(value, "l") for value in columns[3])
|
|
203
|
+
close = (
|
|
204
|
+
_get_quote_price(columns[4][-1], "c") if columns[4][-1] is not None else None
|
|
205
|
+
)
|
|
206
|
+
market_price = close if close is not None else _get_quote_price(columns[1][-1], "o")
|
|
207
|
+
volume = 0
|
|
208
|
+
for value in columns[5]:
|
|
209
|
+
bar_volume = _get_quote_number(value, "v")
|
|
210
|
+
if bar_volume != int(bar_volume):
|
|
211
|
+
raise ValueError("DNSE quote volume must use whole traded units")
|
|
212
|
+
volume += int(bar_volume)
|
|
213
|
+
|
|
214
|
+
info = await get_info(symbol)
|
|
215
|
+
if info is None:
|
|
216
|
+
return None
|
|
217
|
+
return models.StockQuote(
|
|
218
|
+
timestamp=quote_time,
|
|
219
|
+
exchange=info.exchange,
|
|
220
|
+
symbol=symbol,
|
|
221
|
+
market_price=market_price,
|
|
222
|
+
open=open_price,
|
|
223
|
+
high=high_price,
|
|
224
|
+
low=low_price,
|
|
225
|
+
volume=volume,
|
|
226
|
+
close=close,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _get_quote_number(value: object, field: str) -> int | float:
|
|
231
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:
|
|
232
|
+
raise ValueError(f"DNSE quote field {field!r} must be a non-negative number")
|
|
233
|
+
try:
|
|
234
|
+
finite = math.isfinite(value)
|
|
235
|
+
except OverflowError:
|
|
236
|
+
finite = False
|
|
237
|
+
if not finite:
|
|
238
|
+
raise ValueError(f"DNSE quote field {field!r} must be finite")
|
|
239
|
+
return value
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _get_quote_price(value: object, field: str) -> float:
|
|
243
|
+
price = float(_get_quote_number(value, field)) * 1000
|
|
244
|
+
if not math.isfinite(price):
|
|
245
|
+
raise ValueError(f"DNSE quote price {field!r} is out of range")
|
|
246
|
+
return price
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
async def get_history(
|
|
250
|
+
ticker: str, num_days: int = 30
|
|
251
|
+
) -> list[models.StockQuote] | None:
|
|
252
|
+
"""Retrieve daily VN stock quotes from DNSE/Entrade for a recent period.
|
|
253
|
+
|
|
254
|
+
Args:
|
|
255
|
+
ticker (str): CODE, EXCHANGE:CODE, or CODE.VN, such as fpt,
|
|
256
|
+
HOSE:FPT, or FPT.VN. Case and surrounding whitespace are ignored.
|
|
257
|
+
CODE may contain single dots between nonempty ASCII alphanumeric
|
|
258
|
+
parts, such as ABC.Z, but must not end with .VN. Exchange prefixes
|
|
259
|
+
contain only ASCII letters and cannot be combined with .VN.
|
|
260
|
+
num_days (int): Number of calendar days to request before today's
|
|
261
|
+
midnight in Asia/Ho_Chi_Minh. Defaults to 30; non-positive integers
|
|
262
|
+
also use 30.
|
|
263
|
+
|
|
264
|
+
Returns:
|
|
265
|
+
list[vfinance.models.StockQuote] | None: One quote per returned daily
|
|
266
|
+
bar, in response order, with an Asia/Ho_Chi_Minh timestamp, the
|
|
267
|
+
reported uppercase listing exchange, VND prices, and whole-unit
|
|
268
|
+
volume. Each close supplies market_price; a null close remains
|
|
269
|
+
None and uses that day's opening price for market_price.
|
|
270
|
+
Returns an empty list for empty history. Returns None for HTTP 404,
|
|
271
|
+
an error response without all six quote fields, all-null arrays,
|
|
272
|
+
or an unavailable listing profile.
|
|
273
|
+
|
|
274
|
+
Raises:
|
|
275
|
+
TypeError: ticker is not a string or num_days is not an integer.
|
|
276
|
+
RuntimeError: The HTTP lookup fails, other than HTTP 404 or an error
|
|
277
|
+
response without the required quote fields.
|
|
278
|
+
json.JSONDecodeError: A successful HTTP response is not valid JSON.
|
|
279
|
+
ValueError: ticker is empty or malformed, history arrays are inconsistent,
|
|
280
|
+
a timestamp, price, volume, or listing field is invalid, or the
|
|
281
|
+
HTTP content encoding is unsupported.
|
|
282
|
+
urllib.error.URLError: A connection or redirect failure occurs.
|
|
283
|
+
OSError: A socket timeout, response-reading failure, or invalid gzip
|
|
284
|
+
response occurs.
|
|
285
|
+
http.client.HTTPException: An HTTP response is invalid or incomplete.
|
|
286
|
+
EOFError: A compressed response is truncated.
|
|
287
|
+
zlib.error: A compressed response cannot be decoded.
|
|
288
|
+
asyncio.CancelledError: The task awaiting this lookup is canceled.
|
|
289
|
+
"""
|
|
290
|
+
if isinstance(num_days, bool) or not isinstance(num_days, int):
|
|
291
|
+
raise TypeError("num_days must be an integer")
|
|
292
|
+
if num_days <= 0:
|
|
293
|
+
num_days = 30
|
|
294
|
+
symbol = utils.normalize_ticker(ticker)
|
|
295
|
+
today = datetime.now(_MARKET_TIMEZONE).replace(
|
|
296
|
+
hour=0, minute=0, second=0, microsecond=0
|
|
297
|
+
)
|
|
298
|
+
end = int(today.timestamp())
|
|
299
|
+
start = end - num_days * _SECONDS_PER_DAY
|
|
300
|
+
response = await _utils.fetch_url_async(
|
|
301
|
+
f"{_BASE_URL.rstrip('/')}/chart-api/v2/ohlcs/stock"
|
|
302
|
+
f"?symbol={symbol}&resolution=1D&from={start}&to={end}"
|
|
303
|
+
)
|
|
304
|
+
if response.status == 404:
|
|
305
|
+
return None
|
|
306
|
+
try:
|
|
307
|
+
payload = json.loads(response.content)
|
|
308
|
+
except json.JSONDecodeError:
|
|
309
|
+
if not response.is_successful():
|
|
310
|
+
raise RuntimeError(
|
|
311
|
+
f"DNSE history lookup returned HTTP {response.status}"
|
|
312
|
+
) from None
|
|
313
|
+
raise
|
|
314
|
+
fields = ("t", "o", "h", "l", "c", "v")
|
|
315
|
+
if not isinstance(payload, dict) or any(field not in payload for field in fields):
|
|
316
|
+
return None
|
|
317
|
+
if not response.is_successful():
|
|
318
|
+
raise RuntimeError(f"DNSE history lookup returned HTTP {response.status}")
|
|
319
|
+
|
|
320
|
+
columns = [payload[field] for field in fields]
|
|
321
|
+
if all(column is None for column in columns):
|
|
322
|
+
return None
|
|
323
|
+
if any(not isinstance(column, list) for column in columns):
|
|
324
|
+
raise ValueError("DNSE history fields must be arrays")
|
|
325
|
+
if any(len(column) != len(columns[0]) for column in columns):
|
|
326
|
+
raise ValueError("DNSE history arrays must have matching lengths")
|
|
327
|
+
if not columns[0]:
|
|
328
|
+
return []
|
|
329
|
+
|
|
330
|
+
history_data = []
|
|
331
|
+
for timestamp, opening, high, low, closing, volume in zip(*columns, strict=True):
|
|
332
|
+
timestamp = _get_quote_number(timestamp, "t")
|
|
333
|
+
try:
|
|
334
|
+
quote_time = datetime.fromtimestamp(timestamp, tz=_MARKET_TIMEZONE)
|
|
335
|
+
except (OverflowError, OSError) as error:
|
|
336
|
+
raise ValueError("DNSE history timestamp is out of range") from error
|
|
337
|
+
open_price = _get_quote_price(opening, "o")
|
|
338
|
+
close = _get_quote_price(closing, "c") if closing is not None else None
|
|
339
|
+
volume = _get_quote_number(volume, "v")
|
|
340
|
+
if volume != int(volume):
|
|
341
|
+
raise ValueError("DNSE history volume must use whole traded units")
|
|
342
|
+
history_data.append(
|
|
343
|
+
{
|
|
344
|
+
"timestamp": quote_time,
|
|
345
|
+
"market_price": close if close is not None else open_price,
|
|
346
|
+
"open": open_price,
|
|
347
|
+
"high": _get_quote_price(high, "h"),
|
|
348
|
+
"low": _get_quote_price(low, "l"),
|
|
349
|
+
"volume": int(volume),
|
|
350
|
+
"close": close,
|
|
351
|
+
}
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
info = await get_info(symbol)
|
|
355
|
+
if info is None:
|
|
356
|
+
return None
|
|
357
|
+
return [
|
|
358
|
+
models.StockQuote(exchange=info.exchange, symbol=symbol, **data)
|
|
359
|
+
for data in history_data
|
|
360
|
+
]
|