quantvn 0.2.1__tar.gz → 0.3.0__tar.gz
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.
- {quantvn-0.2.1/quantvn.egg-info → quantvn-0.3.0}/PKG-INFO +79 -1
- {quantvn-0.2.1 → quantvn-0.3.0}/README.md +78 -0
- quantvn-0.3.0/quantvn/crypto/data/__init__.py +5 -0
- quantvn-0.3.0/quantvn/crypto/data/derivatives.py +202 -0
- quantvn-0.3.0/quantvn/crypto/data/download.py +52 -0
- quantvn-0.3.0/quantvn/marketdata.py +148 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/paper/single_asset.py +38 -3
- quantvn-0.3.0/quantvn/us/data/__init__.py +5 -0
- quantvn-0.3.0/quantvn/us/data/stocks.py +87 -0
- {quantvn-0.2.1 → quantvn-0.3.0/quantvn.egg-info}/PKG-INFO +79 -1
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn.egg-info/SOURCES.txt +2 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/setup.py +1 -1
- quantvn-0.3.0/tests/test_markets.py +244 -0
- quantvn-0.2.1/quantvn/crypto/data/__init__.py +0 -7
- quantvn-0.2.1/quantvn/crypto/data/derivatives.py +0 -85
- quantvn-0.2.1/quantvn/crypto/data/download.py +0 -56
- quantvn-0.2.1/quantvn/us/data/__init__.py +0 -5
- quantvn-0.2.1/quantvn/us/data/stocks.py +0 -60
- {quantvn-0.2.1 → quantvn-0.3.0}/LICENSE +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/MANIFEST.in +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/__init__.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/crypto/__init__.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/crypto/metrics/__init__.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/crypto/metrics/backtest.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/crypto/metrics/metrics.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/metrics/__init__.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/metrics/_fills.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/metrics/portfolio.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/metrics/single_asset.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/metrics/st.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/paper/__init__.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/paper/client.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/paper/portfolio.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/strategy/__init__.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/strategy/frames.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/strategy/harness.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/strategy/script.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/us/__init__.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/us/metrics/__init__.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/us/metrics/backtest.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/vn/__init__.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/vn/data/__init__.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/vn/data/const.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/vn/data/core.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/vn/data/derivatives.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/vn/data/macro.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/vn/data/stocks.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/vn/data/utils.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/vn/metrics/__init__.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/vn/metrics/backtest.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn/vn/metrics/metrics.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn.egg-info/dependency_links.txt +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn.egg-info/requires.txt +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/quantvn.egg-info/top_level.txt +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/setup.cfg +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/tests/test_backtests.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/tests/test_paper.py +0 -0
- {quantvn-0.2.1 → quantvn-0.3.0}/tests/test_strategy.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: quantvn
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: QuantVN API Library for Financial Data Analysis
|
|
5
5
|
Author: quantvn
|
|
6
6
|
Classifier: Development Status :: 3 - Alpha
|
|
@@ -950,6 +950,76 @@ print(tr.record("bot-dau-tien")["fills"]) # các lần khớp: thời điể
|
|
|
950
950
|
- `tr.publish(ten_bot)` công khai thành tích. Việc công khai là vĩnh viễn: về sau có thể đánh dấu rút lại, nhưng bản ghi vẫn xem được.
|
|
951
951
|
- Khi máy chủ từ chối, thư viện báo `paper.TrackRecordError` với `code` như `rate_limited`, `position_out_of_range`, `bot_limit_reached`.
|
|
952
952
|
|
|
953
|
+
### 6. Thị trường Mỹ và Crypto (từ bản 0.3.0)
|
|
954
|
+
|
|
955
|
+
Dữ liệu cổ phiếu/ETF Mỹ và crypto lấy từ **API dữ liệu thị trường của QuantVN**, kho giá QuantVN dùng cho paper trading: nến 1 phút, gắn nhãn theo **giờ mở cửa** của nến, chỉ gồm nến đã đóng. Không cần API key; có key (`client(apikey=...)`) thì hạn mức cao hơn.
|
|
956
|
+
|
|
957
|
+
| Bộ dữ liệu | Nội dung | Nguồn | Cập nhật |
|
|
958
|
+
|---|---|---|---|
|
|
959
|
+
| `crypto_spot` | ~40 cặp USDT spot của Binance, từ ngày niêm yết | Kho lưu trữ chính thức của Binance (data.binance.vision, có checksum) + REST API | 10 phút |
|
|
960
|
+
| `crypto_perp` | Hợp đồng vĩnh cửu USD-M của các cặp đó | như trên | 10 phút |
|
|
961
|
+
| `crypto_funding` | Funding rate từng kỳ | Binance | 10 phút |
|
|
962
|
+
| `us_stock` | S&P 500 + ~40 ETF, nến 1 phút phiên chính (09:30–16:00 New York) | Yahoo Finance: chỉ có 30 ngày gần nhất, kho dài thêm mỗi ngày | mỗi giờ |
|
|
963
|
+
| `us_stock_1d` | Nến ngày toàn bộ lịch sử, có `adj_close` | Yahoo Finance | mỗi ngày |
|
|
964
|
+
|
|
965
|
+
#### 6.1. Crypto
|
|
966
|
+
|
|
967
|
+
```python
|
|
968
|
+
from quantvn.crypto.data import get_crypto_hist, get_funding_rates, list_crypto_symbols
|
|
969
|
+
|
|
970
|
+
list_crypto_symbols("spot")[:5] # các cặp có trong kho
|
|
971
|
+
btc = get_crypto_hist("BTCUSDT", "1h", start="2025-01-01", end="2026-01-01")
|
|
972
|
+
perp = get_crypto_hist("BTCUSDT", "1m", start="2026-11-01", market="perp")
|
|
973
|
+
fund = get_funding_rates("BTCUSDT", start="2026-01-01") # Datetime, rate, mark_price
|
|
974
|
+
```
|
|
975
|
+
|
|
976
|
+
- Gọi như bản cũ, `get_crypto_hist("BTCUSDT")` (không có `start`/`end`), vẫn trả về giai đoạn 2019-07 đến 2022-12 như trước.
|
|
977
|
+
- Khung `1m 5m 15m 30m 1h 4h 1d` lấy từ API QuantVN; các khung khác (`3m`, `2h`, `1w`, ...) hoặc khi API không trả lời thì thư viện tải thẳng từ Binance (`source="binance"` để luôn dùng Binance).
|
|
978
|
+
- `Datetime` mặc định theo giờ Việt Nam như trước; `tz=None` cho UTC.
|
|
979
|
+
|
|
980
|
+
#### 6.2. Cổ phiếu Mỹ
|
|
981
|
+
|
|
982
|
+
```python
|
|
983
|
+
from quantvn.us.data import get_us_hist, list_us_symbols
|
|
984
|
+
|
|
985
|
+
aapl = get_us_hist("AAPL", "1m", start="2026-11-01") # giờ New York
|
|
986
|
+
spy_daily = get_us_hist("SPY", "1d", start="2000-01-01")
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
Gọi như bản cũ, `get_us_hist("AAPL")` (nến 1 phút, không có khoảng thời gian) vẫn đọc dịch vụ dữ liệu cũ và cần API key.
|
|
990
|
+
|
|
991
|
+
#### 6.3. Paper trading Mỹ và Crypto
|
|
992
|
+
|
|
993
|
+
`paper.simulate` có thêm hai thị trường, cùng quy tắc với dịch vụ Track Record:
|
|
994
|
+
|
|
995
|
+
| Thị trường | Vị thế | Phí mỗi chiều | Ghi chú |
|
|
996
|
+
|---|---|---|---|
|
|
997
|
+
| `CRYPTO` | 0 đến 1 | 10 bp | spot |
|
|
998
|
+
| `CRYPTO_PERP` | -1 đến 1 | 5 bp | trả/nhận funding ở mỗi kỳ funding |
|
|
999
|
+
| `US_STOCK` | -1 đến 1 | 1 bp | |
|
|
1000
|
+
|
|
1001
|
+
```python
|
|
1002
|
+
from quantvn import paper
|
|
1003
|
+
from quantvn.crypto.data import get_crypto_hist, get_funding_rates
|
|
1004
|
+
|
|
1005
|
+
df = get_crypto_hist("ETHUSDT", "1m", start="2026-10-01", end="2026-11-01", market="perp", tz=None)
|
|
1006
|
+
df["position"] = ... # tỷ trọng vốn, quyết định tại giá đóng cửa từng nến
|
|
1007
|
+
fund = get_funding_rates("ETHUSDT", start="2026-10-01", end="2026-11-01")
|
|
1008
|
+
print(paper.simulate(df, market="CRYPTO_PERP", funding=fund))
|
|
1009
|
+
```
|
|
1010
|
+
|
|
1011
|
+
Funding: một kỳ funding tại thời điểm t được tính ở nến đầu tiên mở cửa từ t trở đi, trên tỷ trọng đang giữ **trước** lệnh khớp ở nến đó: vốn nhân với `1 - tỷ trọng x rate` (vị thế mua trả khi rate dương, vị thế bán nhận). Kết quả của `simulate` trùng với engine của Track Record (chênh lệch tương đối dưới 1e-13 trên 200 kịch bản ngẫu nhiên). Gửi vị thế lên Track Record vẫn qua `TrackRecord.send` (mục 5.5); thị trường nào đang nhận vị thế xem ở `TrackRecord.assets()`.
|
|
1012
|
+
|
|
1013
|
+
#### 6.4. API trực tiếp
|
|
1014
|
+
|
|
1015
|
+
```python
|
|
1016
|
+
from quantvn import marketdata
|
|
1017
|
+
marketdata.datasets() # độ phủ và hạn mức hiện tại
|
|
1018
|
+
marketdata.bars("crypto_spot", "SOLUSDT", "2026-11-01", "2026-11-02", interval="15m") # ts = ms UTC
|
|
1019
|
+
```
|
|
1020
|
+
|
|
1021
|
+
Hạn mức (mặc định): không có key 30 yêu cầu/phút và 5 triệu dòng/ngày; có key 120 yêu cầu/phút và 50 triệu dòng/ngày; tối đa 600.000 dòng mỗi yêu cầu (thư viện tự chia nhỏ). Vượt hạn mức: HTTP 429, thư viện tự chờ và thử lại. Đổi địa chỉ API bằng biến môi trường `QUANTVN_DATA_URL`.
|
|
1022
|
+
|
|
953
1023
|
---
|
|
954
1024
|
|
|
955
1025
|
## Ví dụ thực tế
|
|
@@ -1014,6 +1084,14 @@ Dự án này được phát hành theo giấy phép **MIT License**. Xem file [
|
|
|
1014
1084
|
|
|
1015
1085
|
## Changelog
|
|
1016
1086
|
|
|
1087
|
+
### Version 0.3.0
|
|
1088
|
+
|
|
1089
|
+
- Thêm `quantvn.marketdata`: client của API dữ liệu thị trường QuantVN (cổ phiếu/ETF Mỹ, crypto spot và vĩnh cửu Binance, funding rate) có hạn mức theo key/địa chỉ (mục 6)
|
|
1090
|
+
- `get_crypto_hist`: thêm `start`, `end`, `market="perp"`, `tz`, `source`; tải dữ liệu sau 2022; đọc đúng thời gian micro giây trong kho Binance từ 2025. Gọi không có `start`/`end` cho kết quả như cũ
|
|
1091
|
+
- Thêm `get_funding_rates`, `list_crypto_symbols`, `list_us_symbols`
|
|
1092
|
+
- `get_us_hist`: thêm khung `5m 15m 30m 1h 1d`, `start`, `end`, `tz`. Gọi như cũ vẫn dùng dịch vụ cũ
|
|
1093
|
+
- `paper.simulate`: thêm thị trường `CRYPTO_PERP` (có funding, tham số `funding`) và `US_STOCK`, trùng với Track Record
|
|
1094
|
+
|
|
1017
1095
|
### Version 0.2.1
|
|
1018
1096
|
|
|
1019
1097
|
- Chi phí của `Backtest_Derivates` và `Backtest_Stock` trùng với website QuantVN: phí HNX, thuế thu nhập cá nhân và phí quản lý vị thế VSDC cho phái sinh; phí 0,1% và thuế bán 0,1% cho cổ phiếu, bán được từ 13:00 ngày T+2 (mục 4.0). Cùng một chiến lược cho cùng một kết quả trong thư viện và khi bấm "Run test"
|
|
@@ -916,6 +916,76 @@ print(tr.record("bot-dau-tien")["fills"]) # các lần khớp: thời điể
|
|
|
916
916
|
- `tr.publish(ten_bot)` công khai thành tích. Việc công khai là vĩnh viễn: về sau có thể đánh dấu rút lại, nhưng bản ghi vẫn xem được.
|
|
917
917
|
- Khi máy chủ từ chối, thư viện báo `paper.TrackRecordError` với `code` như `rate_limited`, `position_out_of_range`, `bot_limit_reached`.
|
|
918
918
|
|
|
919
|
+
### 6. Thị trường Mỹ và Crypto (từ bản 0.3.0)
|
|
920
|
+
|
|
921
|
+
Dữ liệu cổ phiếu/ETF Mỹ và crypto lấy từ **API dữ liệu thị trường của QuantVN**, kho giá QuantVN dùng cho paper trading: nến 1 phút, gắn nhãn theo **giờ mở cửa** của nến, chỉ gồm nến đã đóng. Không cần API key; có key (`client(apikey=...)`) thì hạn mức cao hơn.
|
|
922
|
+
|
|
923
|
+
| Bộ dữ liệu | Nội dung | Nguồn | Cập nhật |
|
|
924
|
+
|---|---|---|---|
|
|
925
|
+
| `crypto_spot` | ~40 cặp USDT spot của Binance, từ ngày niêm yết | Kho lưu trữ chính thức của Binance (data.binance.vision, có checksum) + REST API | 10 phút |
|
|
926
|
+
| `crypto_perp` | Hợp đồng vĩnh cửu USD-M của các cặp đó | như trên | 10 phút |
|
|
927
|
+
| `crypto_funding` | Funding rate từng kỳ | Binance | 10 phút |
|
|
928
|
+
| `us_stock` | S&P 500 + ~40 ETF, nến 1 phút phiên chính (09:30–16:00 New York) | Yahoo Finance: chỉ có 30 ngày gần nhất, kho dài thêm mỗi ngày | mỗi giờ |
|
|
929
|
+
| `us_stock_1d` | Nến ngày toàn bộ lịch sử, có `adj_close` | Yahoo Finance | mỗi ngày |
|
|
930
|
+
|
|
931
|
+
#### 6.1. Crypto
|
|
932
|
+
|
|
933
|
+
```python
|
|
934
|
+
from quantvn.crypto.data import get_crypto_hist, get_funding_rates, list_crypto_symbols
|
|
935
|
+
|
|
936
|
+
list_crypto_symbols("spot")[:5] # các cặp có trong kho
|
|
937
|
+
btc = get_crypto_hist("BTCUSDT", "1h", start="2025-01-01", end="2026-01-01")
|
|
938
|
+
perp = get_crypto_hist("BTCUSDT", "1m", start="2026-11-01", market="perp")
|
|
939
|
+
fund = get_funding_rates("BTCUSDT", start="2026-01-01") # Datetime, rate, mark_price
|
|
940
|
+
```
|
|
941
|
+
|
|
942
|
+
- Gọi như bản cũ, `get_crypto_hist("BTCUSDT")` (không có `start`/`end`), vẫn trả về giai đoạn 2019-07 đến 2022-12 như trước.
|
|
943
|
+
- Khung `1m 5m 15m 30m 1h 4h 1d` lấy từ API QuantVN; các khung khác (`3m`, `2h`, `1w`, ...) hoặc khi API không trả lời thì thư viện tải thẳng từ Binance (`source="binance"` để luôn dùng Binance).
|
|
944
|
+
- `Datetime` mặc định theo giờ Việt Nam như trước; `tz=None` cho UTC.
|
|
945
|
+
|
|
946
|
+
#### 6.2. Cổ phiếu Mỹ
|
|
947
|
+
|
|
948
|
+
```python
|
|
949
|
+
from quantvn.us.data import get_us_hist, list_us_symbols
|
|
950
|
+
|
|
951
|
+
aapl = get_us_hist("AAPL", "1m", start="2026-11-01") # giờ New York
|
|
952
|
+
spy_daily = get_us_hist("SPY", "1d", start="2000-01-01")
|
|
953
|
+
```
|
|
954
|
+
|
|
955
|
+
Gọi như bản cũ, `get_us_hist("AAPL")` (nến 1 phút, không có khoảng thời gian) vẫn đọc dịch vụ dữ liệu cũ và cần API key.
|
|
956
|
+
|
|
957
|
+
#### 6.3. Paper trading Mỹ và Crypto
|
|
958
|
+
|
|
959
|
+
`paper.simulate` có thêm hai thị trường, cùng quy tắc với dịch vụ Track Record:
|
|
960
|
+
|
|
961
|
+
| Thị trường | Vị thế | Phí mỗi chiều | Ghi chú |
|
|
962
|
+
|---|---|---|---|
|
|
963
|
+
| `CRYPTO` | 0 đến 1 | 10 bp | spot |
|
|
964
|
+
| `CRYPTO_PERP` | -1 đến 1 | 5 bp | trả/nhận funding ở mỗi kỳ funding |
|
|
965
|
+
| `US_STOCK` | -1 đến 1 | 1 bp | |
|
|
966
|
+
|
|
967
|
+
```python
|
|
968
|
+
from quantvn import paper
|
|
969
|
+
from quantvn.crypto.data import get_crypto_hist, get_funding_rates
|
|
970
|
+
|
|
971
|
+
df = get_crypto_hist("ETHUSDT", "1m", start="2026-10-01", end="2026-11-01", market="perp", tz=None)
|
|
972
|
+
df["position"] = ... # tỷ trọng vốn, quyết định tại giá đóng cửa từng nến
|
|
973
|
+
fund = get_funding_rates("ETHUSDT", start="2026-10-01", end="2026-11-01")
|
|
974
|
+
print(paper.simulate(df, market="CRYPTO_PERP", funding=fund))
|
|
975
|
+
```
|
|
976
|
+
|
|
977
|
+
Funding: một kỳ funding tại thời điểm t được tính ở nến đầu tiên mở cửa từ t trở đi, trên tỷ trọng đang giữ **trước** lệnh khớp ở nến đó: vốn nhân với `1 - tỷ trọng x rate` (vị thế mua trả khi rate dương, vị thế bán nhận). Kết quả của `simulate` trùng với engine của Track Record (chênh lệch tương đối dưới 1e-13 trên 200 kịch bản ngẫu nhiên). Gửi vị thế lên Track Record vẫn qua `TrackRecord.send` (mục 5.5); thị trường nào đang nhận vị thế xem ở `TrackRecord.assets()`.
|
|
978
|
+
|
|
979
|
+
#### 6.4. API trực tiếp
|
|
980
|
+
|
|
981
|
+
```python
|
|
982
|
+
from quantvn import marketdata
|
|
983
|
+
marketdata.datasets() # độ phủ và hạn mức hiện tại
|
|
984
|
+
marketdata.bars("crypto_spot", "SOLUSDT", "2026-11-01", "2026-11-02", interval="15m") # ts = ms UTC
|
|
985
|
+
```
|
|
986
|
+
|
|
987
|
+
Hạn mức (mặc định): không có key 30 yêu cầu/phút và 5 triệu dòng/ngày; có key 120 yêu cầu/phút và 50 triệu dòng/ngày; tối đa 600.000 dòng mỗi yêu cầu (thư viện tự chia nhỏ). Vượt hạn mức: HTTP 429, thư viện tự chờ và thử lại. Đổi địa chỉ API bằng biến môi trường `QUANTVN_DATA_URL`.
|
|
988
|
+
|
|
919
989
|
---
|
|
920
990
|
|
|
921
991
|
## Ví dụ thực tế
|
|
@@ -980,6 +1050,14 @@ Dự án này được phát hành theo giấy phép **MIT License**. Xem file [
|
|
|
980
1050
|
|
|
981
1051
|
## Changelog
|
|
982
1052
|
|
|
1053
|
+
### Version 0.3.0
|
|
1054
|
+
|
|
1055
|
+
- Thêm `quantvn.marketdata`: client của API dữ liệu thị trường QuantVN (cổ phiếu/ETF Mỹ, crypto spot và vĩnh cửu Binance, funding rate) có hạn mức theo key/địa chỉ (mục 6)
|
|
1056
|
+
- `get_crypto_hist`: thêm `start`, `end`, `market="perp"`, `tz`, `source`; tải dữ liệu sau 2022; đọc đúng thời gian micro giây trong kho Binance từ 2025. Gọi không có `start`/`end` cho kết quả như cũ
|
|
1057
|
+
- Thêm `get_funding_rates`, `list_crypto_symbols`, `list_us_symbols`
|
|
1058
|
+
- `get_us_hist`: thêm khung `5m 15m 30m 1h 1d`, `start`, `end`, `tz`. Gọi như cũ vẫn dùng dịch vụ cũ
|
|
1059
|
+
- `paper.simulate`: thêm thị trường `CRYPTO_PERP` (có funding, tham số `funding`) và `US_STOCK`, trùng với Track Record
|
|
1060
|
+
|
|
983
1061
|
### Version 0.2.1
|
|
984
1062
|
|
|
985
1063
|
- Chi phí của `Backtest_Derivates` và `Backtest_Stock` trùng với website QuantVN: phí HNX, thuế thu nhập cá nhân và phí quản lý vị thế VSDC cho phái sinh; phí 0,1% và thuế bán 0,1% cho cổ phiếu, bán được từ 13:00 ngày T+2 (mục 4.0). Cùng một chiến lược cho cùng một kết quả trong thư viện và khi bấm "Run test"
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""Crypto prices: Binance spot and USD-M perpetual futures, and perpetual funding rates.
|
|
2
|
+
|
|
3
|
+
Data come from the QuantVN market-data API (the store QuantVN uses for paper trading, refreshed every 10
|
|
4
|
+
minutes) or, when it cannot be reached or the interval is one it does not serve, straight from Binance's
|
|
5
|
+
public archive and REST API. Both give Binance's own record of its market.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
11
|
+
from datetime import datetime, timedelta, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Optional, Union
|
|
14
|
+
|
|
15
|
+
import pandas as pd
|
|
16
|
+
import requests
|
|
17
|
+
|
|
18
|
+
from quantvn import marketdata
|
|
19
|
+
from quantvn.crypto.data.download import VALID_INTERVALS, download_monthly, extract_csv
|
|
20
|
+
|
|
21
|
+
__all__ = ["get_hist", "get_funding_rates", "list_symbols"]
|
|
22
|
+
|
|
23
|
+
VN_TZ = timezone(timedelta(hours=7))
|
|
24
|
+
COLUMNS = ["Datetime", "Date", "time", "Open", "High", "Low", "Close", "volume"]
|
|
25
|
+
# The window get_hist returned before 0.3, and still returns when no start or end is given.
|
|
26
|
+
LEGACY_START = datetime(2019, 7, 1, tzinfo=VN_TZ)
|
|
27
|
+
LEGACY_END = datetime(2022, 12, 31, 23, 59, 59, tzinfo=VN_TZ)
|
|
28
|
+
_MARKETS = {"spot": "crypto_spot", "perp": "crypto_perp"}
|
|
29
|
+
_REST = {"spot": "https://api.binance.com/api/v3/klines", "perp": "https://fapi.binance.com/fapi/v1/klines"}
|
|
30
|
+
_INTERVAL_MS = {"1m": 60_000, "3m": 180_000, "5m": 300_000, "15m": 900_000, "30m": 1_800_000, "1h": 3_600_000,
|
|
31
|
+
"2h": 7_200_000, "4h": 14_400_000, "6h": 21_600_000, "8h": 28_800_000, "12h": 43_200_000,
|
|
32
|
+
"1d": 86_400_000, "3d": 259_200_000, "1w": 604_800_000}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_hist(
|
|
36
|
+
symbol: str,
|
|
37
|
+
interval: str = "1m",
|
|
38
|
+
cache_dir: Optional[Union[str, Path]] = None,
|
|
39
|
+
start=None,
|
|
40
|
+
end=None,
|
|
41
|
+
market: str = "spot",
|
|
42
|
+
tz: Optional[str] = "Asia/Ho_Chi_Minh",
|
|
43
|
+
source: str = "auto",
|
|
44
|
+
) -> pd.DataFrame:
|
|
45
|
+
"""Historical OHLCV bars of a Binance pair.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
symbol: Binance symbol, e.g. "BTCUSDT".
|
|
49
|
+
interval: 1m 3m 5m 15m 30m 1h 2h 4h 6h 8h 12h 1d 3d 1w 1M.
|
|
50
|
+
cache_dir: where monthly archives are kept when they are downloaded from Binance (default ~/.cache/quantvn).
|
|
51
|
+
start, end: the window (dates, datetimes or epoch ms; end exclusive; without a time zone = UTC).
|
|
52
|
+
When both are omitted the window is 2019-07-01 to 2022-12-31 (Vietnam time), as before 0.3.
|
|
53
|
+
When only end is omitted it is now.
|
|
54
|
+
market: "spot" or "perp" (USD-M perpetual futures, last price).
|
|
55
|
+
tz: time zone of the Datetime column (default Vietnam time, as before; None = UTC).
|
|
56
|
+
source: "auto" (QuantVN API, falling back to Binance), "quantvn" or "binance".
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
DataFrame [Datetime, Date, time, Open, High, Low, Close, volume]; Datetime is the bar's OPEN time.
|
|
60
|
+
Only bars that have closed are returned.
|
|
61
|
+
"""
|
|
62
|
+
if interval not in VALID_INTERVALS:
|
|
63
|
+
raise ValueError(f"Invalid interval {interval!r}. Choose one of: {', '.join(sorted(VALID_INTERVALS))}")
|
|
64
|
+
if market not in _MARKETS:
|
|
65
|
+
raise ValueError("market must be 'spot' or 'perp'")
|
|
66
|
+
if source not in ("auto", "quantvn", "binance"):
|
|
67
|
+
raise ValueError("source must be 'auto', 'quantvn' or 'binance'")
|
|
68
|
+
symbol = symbol.upper().strip()
|
|
69
|
+
now = int(time.time() * 1000)
|
|
70
|
+
if start is None and end is None:
|
|
71
|
+
start_ms, end_ms = int(LEGACY_START.timestamp() * 1000), int(LEGACY_END.timestamp() * 1000) + 1000
|
|
72
|
+
else:
|
|
73
|
+
end_ms = marketdata.to_ms(end, now)
|
|
74
|
+
start_ms = marketdata.to_ms(start, int(LEGACY_START.timestamp() * 1000))
|
|
75
|
+
if start_ms >= end_ms:
|
|
76
|
+
raise ValueError("start must be before end")
|
|
77
|
+
|
|
78
|
+
if source != "binance" and interval in marketdata.INTERVALS:
|
|
79
|
+
try:
|
|
80
|
+
df = marketdata.bars(_MARKETS[market], symbol, start_ms, end_ms, interval)
|
|
81
|
+
newest = df.attrs.get("newest")
|
|
82
|
+
want = min(end_ms, now)
|
|
83
|
+
# the store may not reach the end of the window yet (a symbol still downloading, a late refresh):
|
|
84
|
+
# take the rest from Binance, from the first minute the store does not have
|
|
85
|
+
if source == "auto" and newest is not None and newest + 60_000 < want - 15 * 60_000:
|
|
86
|
+
step = marketdata.INTERVALS[interval] * 60_000
|
|
87
|
+
rest_from = max(start_ms, (newest + 60_000 + step - 1) // step * step)
|
|
88
|
+
if rest_from < want:
|
|
89
|
+
rest = _from_binance(symbol, interval, rest_from, want, market, cache_dir, None)
|
|
90
|
+
head = marketdata.to_candles(df, None)
|
|
91
|
+
head = head[head["Datetime"] < pd.Timestamp(rest_from, unit="ms", tz="UTC")]
|
|
92
|
+
both = pd.concat([x for x in (head, rest) if len(x)], ignore_index=True) if len(head) or len(rest) else head
|
|
93
|
+
if tz and len(both):
|
|
94
|
+
both["Datetime"] = both["Datetime"].dt.tz_convert(tz)
|
|
95
|
+
both["Date"] = both["Datetime"].dt.strftime("%Y-%m-%d")
|
|
96
|
+
both["time"] = both["Datetime"].dt.strftime("%H:%M:%S")
|
|
97
|
+
return both.reset_index(drop=True)
|
|
98
|
+
return marketdata.to_candles(df, tz)
|
|
99
|
+
except (requests.RequestException, marketdata.MarketDataError) as e:
|
|
100
|
+
if source == "quantvn" or (isinstance(e, marketdata.MarketDataError) and e.code in ("invalid_time",)):
|
|
101
|
+
raise
|
|
102
|
+
elif source == "quantvn":
|
|
103
|
+
raise ValueError(f"the QuantVN API serves {', '.join(marketdata.INTERVALS)}; use source='binance' for {interval}")
|
|
104
|
+
return _from_binance(symbol, interval, start_ms, min(end_ms, now), market, cache_dir, tz)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _from_binance(symbol, interval, start_ms, end_ms, market, cache_dir, tz) -> pd.DataFrame:
|
|
108
|
+
cache = Path(cache_dir or Path.home() / ".cache/quantvn")
|
|
109
|
+
first = datetime.fromtimestamp(start_ms / 1000, timezone.utc).replace(day=1, hour=0, minute=0, second=0,
|
|
110
|
+
microsecond=0)
|
|
111
|
+
last = datetime.fromtimestamp((end_ms - 1) / 1000, timezone.utc)
|
|
112
|
+
this_month = datetime.now(timezone.utc).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
|
113
|
+
months, m = [], first
|
|
114
|
+
while m <= last and m < this_month:
|
|
115
|
+
months.append(m.strftime("%Y-%m"))
|
|
116
|
+
m = m.replace(year=m.year + (m.month == 12), month=m.month % 12 + 1)
|
|
117
|
+
|
|
118
|
+
results = {}
|
|
119
|
+
|
|
120
|
+
def fetch(month):
|
|
121
|
+
return month, extract_csv(download_monthly(symbol, interval, month, cache, market))
|
|
122
|
+
|
|
123
|
+
with ThreadPoolExecutor(max_workers=8) as ex:
|
|
124
|
+
futures = {ex.submit(fetch, mo): mo for mo in months}
|
|
125
|
+
for fut in as_completed(futures):
|
|
126
|
+
try:
|
|
127
|
+
mo, df = fut.result()
|
|
128
|
+
results[mo] = df
|
|
129
|
+
except Exception as e: # a month Binance has not archived: the REST API covers it
|
|
130
|
+
print(f"Skip {symbol} {interval} {futures[fut]}: {e}")
|
|
131
|
+
parts = [results[mo] for mo in sorted(results)]
|
|
132
|
+
covered = max((int(p["t"].max()) for p in parts if len(p)), default=start_ms - 1)
|
|
133
|
+
if covered + 1 < end_ms and interval in _INTERVAL_MS:
|
|
134
|
+
parts.append(_rest(symbol, interval, max(covered + 1, start_ms), end_ms, market))
|
|
135
|
+
parts = [p for p in parts if len(p)]
|
|
136
|
+
if not parts:
|
|
137
|
+
return pd.DataFrame(columns=COLUMNS)
|
|
138
|
+
df = pd.concat(parts, ignore_index=True).drop_duplicates("t").sort_values("t")
|
|
139
|
+
step = _INTERVAL_MS.get(interval, 0)
|
|
140
|
+
now = int(time.time() * 1000)
|
|
141
|
+
df = df[(df["t"] >= start_ms) & (df["t"] < end_ms) & (df["t"] + step <= now)]
|
|
142
|
+
df = df.rename(columns={"t": "ts", "Open": "open", "High": "high", "Low": "low", "Close": "close",
|
|
143
|
+
"Volume": "volume"})
|
|
144
|
+
return marketdata.to_candles(df, tz)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _rest(symbol, interval, start_ms, end_ms, market) -> pd.DataFrame:
|
|
148
|
+
rows, a = [], start_ms
|
|
149
|
+
limit = 1000
|
|
150
|
+
while a < end_ms:
|
|
151
|
+
r = requests.get(_REST[market], params={"symbol": symbol, "interval": interval, "startTime": a,
|
|
152
|
+
"endTime": end_ms - 1, "limit": limit}, timeout=30)
|
|
153
|
+
r.raise_for_status()
|
|
154
|
+
d = r.json()
|
|
155
|
+
if not d:
|
|
156
|
+
break
|
|
157
|
+
rows += [(int(k[0]), float(k[1]), float(k[2]), float(k[3]), float(k[4]), float(k[5])) for k in d]
|
|
158
|
+
a = int(d[-1][0]) + _INTERVAL_MS[interval]
|
|
159
|
+
if len(d) < limit:
|
|
160
|
+
break
|
|
161
|
+
return pd.DataFrame(rows, columns=["t", "Open", "High", "Low", "Close", "Volume"])
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def get_funding_rates(symbol: str, start=None, end=None, source: str = "auto") -> pd.DataFrame:
|
|
165
|
+
"""Funding events of a Binance USD-M perpetual: columns Datetime (UTC), rate, mark_price.
|
|
166
|
+
|
|
167
|
+
A long position pays ``rate x notional`` at each event (a short receives it). Default window: the last
|
|
168
|
+
365 days. ``quantvn.paper.simulate(..., market="CRYPTO_PERP", funding=...)`` takes this frame."""
|
|
169
|
+
symbol = symbol.upper().strip()
|
|
170
|
+
now = int(time.time() * 1000)
|
|
171
|
+
end_ms = marketdata.to_ms(end, now)
|
|
172
|
+
start_ms = marketdata.to_ms(start, end_ms - 365 * 86_400_000)
|
|
173
|
+
df = None
|
|
174
|
+
if source != "binance":
|
|
175
|
+
try:
|
|
176
|
+
df = marketdata.funding(symbol, start_ms, end_ms)
|
|
177
|
+
except (requests.RequestException, marketdata.MarketDataError):
|
|
178
|
+
if source == "quantvn":
|
|
179
|
+
raise
|
|
180
|
+
if df is None:
|
|
181
|
+
rows, a = [], start_ms
|
|
182
|
+
while a < end_ms:
|
|
183
|
+
r = requests.get("https://fapi.binance.com/fapi/v1/fundingRate",
|
|
184
|
+
params={"symbol": symbol, "startTime": a, "endTime": end_ms - 1, "limit": 1000}, timeout=30)
|
|
185
|
+
r.raise_for_status()
|
|
186
|
+
d = r.json()
|
|
187
|
+
if not d:
|
|
188
|
+
break
|
|
189
|
+
rows += [(int(x["fundingTime"]) // 1000 * 1000, float(x["fundingRate"]),
|
|
190
|
+
float(x["markPrice"]) if x.get("markPrice") else float("nan")) for x in d]
|
|
191
|
+
a = int(d[-1]["fundingTime"]) + 1
|
|
192
|
+
if len(d) < 1000:
|
|
193
|
+
break
|
|
194
|
+
df = pd.DataFrame(rows, columns=["ts", "rate", "mark_price"])
|
|
195
|
+
out = pd.DataFrame({"Datetime": pd.to_datetime(df["ts"].astype("int64"), unit="ms", utc=True),
|
|
196
|
+
"rate": df["rate"].astype(float), "mark_price": df["mark_price"].astype(float)})
|
|
197
|
+
return out.reset_index(drop=True)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def list_symbols(market: str = "spot") -> list:
|
|
201
|
+
"""Symbols the QuantVN API stores for a market: "spot", "perp" or "funding"."""
|
|
202
|
+
return marketdata.symbols({"spot": "crypto_spot", "perp": "crypto_perp", "funding": "crypto_funding"}[market])
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Binance's public archive (data.binance.vision): one zip per symbol, interval and month, no key needed."""
|
|
2
|
+
import io
|
|
3
|
+
import zipfile
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
import requests
|
|
9
|
+
|
|
10
|
+
BASE = "https://data.binance.vision/data"
|
|
11
|
+
MARKET_PATH = {"spot": "spot", "perp": "futures/um"}
|
|
12
|
+
BASE_URL = f"{BASE}/spot/monthly/klines/" # kept for code written against 0.2
|
|
13
|
+
|
|
14
|
+
VALID_INTERVALS = {
|
|
15
|
+
"1m", "3m", "5m", "15m", "30m",
|
|
16
|
+
"1h", "2h", "4h", "6h", "8h", "12h",
|
|
17
|
+
"1d", "3d", "1w", "1M",
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def download_monthly(symbol: str, interval: str, month: str, cache_dir: Path, market: str = "spot") -> Path:
|
|
22
|
+
"""Download (once) the monthly zip of a symbol and interval, return its local path. Raises RuntimeError
|
|
23
|
+
when Binance has no file for that month."""
|
|
24
|
+
folder = cache_dir / ("" if market == "spot" else market) / symbol / interval
|
|
25
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
26
|
+
zip_name = f"{symbol}-{interval}-{month}.zip"
|
|
27
|
+
zip_path = folder / zip_name
|
|
28
|
+
if zip_path.exists():
|
|
29
|
+
return zip_path
|
|
30
|
+
url = f"{BASE}/{MARKET_PATH[market]}/monthly/klines/{symbol}/{interval}/{zip_name}"
|
|
31
|
+
resp = requests.get(url, stream=True, timeout=60)
|
|
32
|
+
if resp.status_code != 200:
|
|
33
|
+
raise RuntimeError(f"File not found: {url}")
|
|
34
|
+
tmp = zip_path.with_suffix(".part")
|
|
35
|
+
with open(tmp, "wb") as f:
|
|
36
|
+
for chunk in resp.iter_content(1024 * 1024):
|
|
37
|
+
f.write(chunk)
|
|
38
|
+
tmp.replace(zip_path)
|
|
39
|
+
return zip_path
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def extract_csv(zip_path: Path) -> pd.DataFrame:
|
|
43
|
+
"""The klines of a monthly zip: columns t (open time, ms UTC), Open, High, Low, Close, Volume.
|
|
44
|
+
Handles the header row of the futures archive and the microsecond times of the spot archive from 2025."""
|
|
45
|
+
with zipfile.ZipFile(zip_path, "r") as zf:
|
|
46
|
+
with zf.open(zf.namelist()[0]) as f:
|
|
47
|
+
df = pd.read_csv(io.TextIOWrapper(f), header=None, usecols=range(6), dtype=str)
|
|
48
|
+
df.columns = ["t", "Open", "High", "Low", "Close", "Volume"]
|
|
49
|
+
df = df.apply(pd.to_numeric, errors="coerce").dropna(subset=["t", "Open", "Close"])
|
|
50
|
+
t = df["t"].astype("int64").to_numpy()
|
|
51
|
+
df["t"] = np.where(t > 10 ** 14, t // 1000, t)
|
|
52
|
+
return df.reset_index(drop=True)
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Client of the QuantVN market-data API (US stocks and ETFs, Binance crypto spot and perpetuals, funding).
|
|
2
|
+
|
|
3
|
+
The API serves the price store that QuantVN collects for paper trading: 1-minute bars labelled by their OPEN
|
|
4
|
+
time. No key is needed; with the API key of your QuantVN account (``quantvn.client(apikey=...)``) the limits
|
|
5
|
+
are higher. The address can be changed with the ``QUANTVN_DATA_URL`` environment variable or
|
|
6
|
+
``set_data_url``.
|
|
7
|
+
|
|
8
|
+
from quantvn.marketdata import bars, symbols
|
|
9
|
+
symbols("crypto_spot")[:5]
|
|
10
|
+
bars("crypto_spot", "BTCUSDT", "2026-01-01", "2026-02-01", interval="1h")
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import io
|
|
15
|
+
import os
|
|
16
|
+
import time
|
|
17
|
+
from typing import Optional, Union
|
|
18
|
+
|
|
19
|
+
import pandas as pd
|
|
20
|
+
import requests
|
|
21
|
+
|
|
22
|
+
DEFAULT_URL = "https://data.quantvn.com/v1"
|
|
23
|
+
INTERVALS = {"1m": 1, "5m": 5, "15m": 15, "30m": 30, "1h": 60, "4h": 240, "1d": 1440}
|
|
24
|
+
MAX_ROWS = 600_000
|
|
25
|
+
_url = os.environ.get("QUANTVN_DATA_URL", DEFAULT_URL).rstrip("/")
|
|
26
|
+
_session = requests.Session()
|
|
27
|
+
_session.headers["User-Agent"] = "quantvn-sdk"
|
|
28
|
+
|
|
29
|
+
TimeLike = Union[str, int, float, pd.Timestamp, None]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class MarketDataError(Exception):
|
|
33
|
+
"""The API refused a request. ``code`` is its error code (``unknown_symbol``, ``rate_limited``, ...)."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, status: int, code: str, message: str):
|
|
36
|
+
super().__init__(f"{code}: {message}")
|
|
37
|
+
self.status, self.code, self.message = status, code, message
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def set_data_url(url: str) -> None:
|
|
41
|
+
global _url
|
|
42
|
+
_url = url.rstrip("/")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def data_url() -> str:
|
|
46
|
+
return _url
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def to_ms(t: TimeLike, default: Optional[int] = None) -> Optional[int]:
|
|
50
|
+
"""Epoch milliseconds from a date string, datetime, Timestamp or epoch seconds/milliseconds. A string or
|
|
51
|
+
datetime without a time zone is read as UTC."""
|
|
52
|
+
if t is None:
|
|
53
|
+
return default
|
|
54
|
+
if isinstance(t, (int, float)):
|
|
55
|
+
return int(t * 1000) if abs(t) < 10 ** 11 else int(t)
|
|
56
|
+
ts = pd.Timestamp(t)
|
|
57
|
+
if ts.tzinfo is None:
|
|
58
|
+
ts = ts.tz_localize("UTC")
|
|
59
|
+
return int(ts.value // 1_000_000)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _headers() -> dict:
|
|
63
|
+
from quantvn.vn.data.utils import Config
|
|
64
|
+
return {"X-API-Key": Config._api_key} if getattr(Config, "_api_key", None) else {}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _get(path: str, params: dict, timeout: float = 120, tries: int = 6) -> requests.Response:
|
|
68
|
+
for k in range(tries):
|
|
69
|
+
r = _session.get(f"{_url}{path}", params=params, headers=_headers(), timeout=timeout)
|
|
70
|
+
if r.status_code == 429 and k < tries - 1:
|
|
71
|
+
time.sleep(min(float(r.headers.get("Retry-After", "2")), 60))
|
|
72
|
+
continue
|
|
73
|
+
if r.status_code >= 400:
|
|
74
|
+
try:
|
|
75
|
+
err = r.json().get("error", {})
|
|
76
|
+
except ValueError:
|
|
77
|
+
err = {}
|
|
78
|
+
raise MarketDataError(r.status_code, err.get("code", "http_error"), err.get("message", r.text[:200]))
|
|
79
|
+
return r
|
|
80
|
+
raise MarketDataError(429, "rate_limited", "still rate limited after retries")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def datasets() -> dict:
|
|
84
|
+
"""What the API stores, with coverage and the current limits."""
|
|
85
|
+
return _get("/datasets", {}).json()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def symbols(dataset: str) -> list:
|
|
89
|
+
"""Symbols of a dataset: crypto_spot, crypto_perp, crypto_funding, us_stock, us_stock_1d."""
|
|
90
|
+
return [s["symbol"] for s in _get("/symbols", {"dataset": dataset}).json()["symbols"]]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def bars(dataset: str, symbol: str, start: TimeLike = None, end: TimeLike = None, interval: str = "1m") -> pd.DataFrame:
|
|
94
|
+
"""Bars with start <= open time < end: columns ts (open time, ms UTC), open, high, low, close, volume (and
|
|
95
|
+
adj_close for daily US bars). Long windows are fetched in several requests."""
|
|
96
|
+
if interval not in INTERVALS:
|
|
97
|
+
raise ValueError(f"interval must be one of {', '.join(INTERVALS)}")
|
|
98
|
+
now = int(time.time() * 1000)
|
|
99
|
+
end_ms = to_ms(end, now)
|
|
100
|
+
start_ms = to_ms(start, end_ms - 7 * 86_400_000)
|
|
101
|
+
if dataset == "us_stock_1d":
|
|
102
|
+
step = 100 * 365 * 86_400_000 # one row per session: any window fits
|
|
103
|
+
elif interval == "1m":
|
|
104
|
+
step = int(MAX_ROWS * 0.9) * 60_000
|
|
105
|
+
else:
|
|
106
|
+
step = 365 * 86_400_000 # the API aggregates at most 400 days per request
|
|
107
|
+
parts, a, newest = [], start_ms, None
|
|
108
|
+
while a < end_ms:
|
|
109
|
+
b = min(a + step, end_ms)
|
|
110
|
+
r = _get("/bars", {"dataset": dataset, "symbol": symbol, "start": a, "end": b, "interval": interval})
|
|
111
|
+
parts.append(pd.read_parquet(io.BytesIO(r.content)))
|
|
112
|
+
if r.headers.get("X-Newest", "").isdigit():
|
|
113
|
+
newest = int(r.headers["X-Newest"])
|
|
114
|
+
a = b
|
|
115
|
+
parts = [p for p in parts if len(p)]
|
|
116
|
+
if not parts:
|
|
117
|
+
out = pd.DataFrame(columns=["ts", "open", "high", "low", "close", "volume"])
|
|
118
|
+
else:
|
|
119
|
+
out = pd.concat(parts, ignore_index=True).drop_duplicates("ts").sort_values("ts").reset_index(drop=True)
|
|
120
|
+
out.attrs["newest"] = newest # open time of the newest 1-minute bar stored for the symbol
|
|
121
|
+
return out
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def funding(symbol: str, start: TimeLike = None, end: TimeLike = None) -> pd.DataFrame:
|
|
125
|
+
"""Funding events of a Binance USD-M perpetual: ts (ms UTC), rate, mark_price (NaN where unknown)."""
|
|
126
|
+
now = int(time.time() * 1000)
|
|
127
|
+
end_ms = to_ms(end, now)
|
|
128
|
+
start_ms = to_ms(start, end_ms - 365 * 86_400_000)
|
|
129
|
+
r = _get("/funding", {"symbol": symbol, "start": start_ms, "end": end_ms})
|
|
130
|
+
return pd.read_parquet(io.BytesIO(r.content))
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def to_candles(df: pd.DataFrame, tz: Optional[str]) -> pd.DataFrame:
|
|
134
|
+
"""API bars in the library's candle layout: Datetime (open time, in `tz`; UTC when None), Date, time,
|
|
135
|
+
Open, High, Low, Close, volume."""
|
|
136
|
+
cols = ["Datetime", "Date", "time", "Open", "High", "Low", "Close", "volume"]
|
|
137
|
+
if df is None or not len(df):
|
|
138
|
+
return pd.DataFrame(columns=cols)
|
|
139
|
+
t = pd.to_datetime(df["ts"].astype("int64"), unit="ms", utc=True)
|
|
140
|
+
if tz:
|
|
141
|
+
t = t.dt.tz_convert(tz)
|
|
142
|
+
out = pd.DataFrame({"Datetime": t, "Date": t.dt.strftime("%Y-%m-%d"), "time": t.dt.strftime("%H:%M:%S"),
|
|
143
|
+
"Open": df["open"].astype(float), "High": df["high"].astype(float),
|
|
144
|
+
"Low": df["low"].astype(float), "Close": df["close"].astype(float),
|
|
145
|
+
"volume": df["volume"].astype(float)})
|
|
146
|
+
if "adj_close" in df.columns:
|
|
147
|
+
out["adj_close"] = df["adj_close"].astype(float)
|
|
148
|
+
return out.reset_index(drop=True)
|