quantvn 0.2.0__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.
Files changed (58) hide show
  1. {quantvn-0.2.0/quantvn.egg-info → quantvn-0.3.0}/PKG-INFO +86 -3
  2. {quantvn-0.2.0 → quantvn-0.3.0}/README.md +85 -2
  3. quantvn-0.3.0/quantvn/crypto/data/__init__.py +5 -0
  4. quantvn-0.3.0/quantvn/crypto/data/derivatives.py +202 -0
  5. quantvn-0.3.0/quantvn/crypto/data/download.py +52 -0
  6. quantvn-0.3.0/quantvn/marketdata.py +148 -0
  7. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/metrics/_fills.py +40 -3
  8. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/paper/single_asset.py +38 -3
  9. quantvn-0.3.0/quantvn/us/data/__init__.py +5 -0
  10. quantvn-0.3.0/quantvn/us/data/stocks.py +87 -0
  11. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/vn/metrics/backtest.py +13 -25
  12. {quantvn-0.2.0 → quantvn-0.3.0/quantvn.egg-info}/PKG-INFO +86 -3
  13. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn.egg-info/SOURCES.txt +2 -0
  14. {quantvn-0.2.0 → quantvn-0.3.0}/setup.py +1 -1
  15. {quantvn-0.2.0 → quantvn-0.3.0}/tests/test_backtests.py +27 -12
  16. quantvn-0.3.0/tests/test_markets.py +244 -0
  17. quantvn-0.2.0/quantvn/crypto/data/__init__.py +0 -7
  18. quantvn-0.2.0/quantvn/crypto/data/derivatives.py +0 -85
  19. quantvn-0.2.0/quantvn/crypto/data/download.py +0 -56
  20. quantvn-0.2.0/quantvn/us/data/__init__.py +0 -5
  21. quantvn-0.2.0/quantvn/us/data/stocks.py +0 -60
  22. {quantvn-0.2.0 → quantvn-0.3.0}/LICENSE +0 -0
  23. {quantvn-0.2.0 → quantvn-0.3.0}/MANIFEST.in +0 -0
  24. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/__init__.py +0 -0
  25. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/crypto/__init__.py +0 -0
  26. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/crypto/metrics/__init__.py +0 -0
  27. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/crypto/metrics/backtest.py +0 -0
  28. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/crypto/metrics/metrics.py +0 -0
  29. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/metrics/__init__.py +0 -0
  30. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/metrics/portfolio.py +0 -0
  31. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/metrics/single_asset.py +0 -0
  32. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/metrics/st.py +0 -0
  33. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/paper/__init__.py +0 -0
  34. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/paper/client.py +0 -0
  35. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/paper/portfolio.py +0 -0
  36. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/strategy/__init__.py +0 -0
  37. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/strategy/frames.py +0 -0
  38. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/strategy/harness.py +0 -0
  39. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/strategy/script.py +0 -0
  40. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/us/__init__.py +0 -0
  41. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/us/metrics/__init__.py +0 -0
  42. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/us/metrics/backtest.py +0 -0
  43. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/vn/__init__.py +0 -0
  44. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/vn/data/__init__.py +0 -0
  45. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/vn/data/const.py +0 -0
  46. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/vn/data/core.py +0 -0
  47. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/vn/data/derivatives.py +0 -0
  48. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/vn/data/macro.py +0 -0
  49. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/vn/data/stocks.py +0 -0
  50. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/vn/data/utils.py +0 -0
  51. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/vn/metrics/__init__.py +0 -0
  52. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn/vn/metrics/metrics.py +0 -0
  53. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn.egg-info/dependency_links.txt +0 -0
  54. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn.egg-info/requires.txt +0 -0
  55. {quantvn-0.2.0 → quantvn-0.3.0}/quantvn.egg-info/top_level.txt +0 -0
  56. {quantvn-0.2.0 → quantvn-0.3.0}/setup.cfg +0 -0
  57. {quantvn-0.2.0 → quantvn-0.3.0}/tests/test_paper.py +0 -0
  58. {quantvn-0.2.0 → 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.2.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
@@ -673,7 +673,7 @@ Vị thế ghi ở một nến được quyết định bằng giá đóng cửa
673
673
  - Vị thế của nến `t` được khớp tại `Open` của nến `t+1`.
674
674
  - Mỗi nến ghi nhận lãi lỗ của vị thế cũ từ giá đóng cửa trước đến giá khớp, rồi của vị thế mới từ giá khớp đến giá đóng cửa.
675
675
  - Phí được tính tại nến khớp, trên giá khớp.
676
- - Chi phí thị trường Việt Nam dùng cùng mức với dịch vụ Track Record. Phái sinh VN30: 1,5 bp giá trị hợp đồng mỗi chiều (phí sở, phí bù trừ, thuế, môi giới và nửa bước giá), khoảng 0,28 điểm khi chỉ số ở 1.850. Cổ phiếu: 0,15% mỗi chiều, thêm 0,1% thuế khi bán và nửa bước giá. Các bản cũ chỉ tính phí sở 2.700 đồng cho phái sinh, khoảng một phần mười chi phí thực.
676
+ - Chi phí thị trường Việt Nam được tính theo từng khoản, đúng như nút "Run test" trên website QuantVN. Phái sinh VN30, mỗi hợp đồng mỗi chiều: phí giao dịch HNX 2.700 đồng và thuế thu nhập cá nhân 0,1% trên (giá khớp × 100.000 × tỷ lệ ký quỹ ban đầu 17% ÷ 2); thêm phí quản lý vị thế VSDC 2.550 đồng mỗi hợp đồng mỗi ngày cho vị thế còn mở cuối ngày, tính cả ngày nghỉ. Khi chỉ số ở 1.850, một chiều tốn khoảng 0,18 điểm. Cổ phiếu: phí môi giới 0,1% mỗi chiều và thuế 0,1% trên giá trị bán; cổ phiếu mua ngày T bán được từ 13:00 ngày T+2. Phí môi giới phái sinh và chênh lệch giá mua bán không nằm trong các lớp backtest; `paper.simulate` (mục 5.4) có tính.
677
677
  - Nếu dữ liệu không có cột `Open`, vị thế được khớp tại giá đóng cửa của nến kế tiếp và thư viện phát cảnh báo.
678
678
 
679
679
  Các bản đến 0.1.25 tính lãi lỗ của vị thế ngay từ giá đóng cửa của chính nến ra quyết định, tức là một mức giá đã qua. Vì vậy **kết quả backtest của cùng một chiến lược sẽ khác so với bản cũ**, nhất là với chiến lược giao dịch nhiều. Con số mới là con số có thể đạt được khi chạy thật; các ví dụ đầu ra bên dưới được tạo từ bản cũ nên chỉ minh họa định dạng.
@@ -925,7 +925,7 @@ print(result)
925
925
  print(paper.simulate(df, market="VN_DERIVATIVE", delay_bars=2)) # chậm thêm một nến, gần với chạy thật ở khung 1 phút
926
926
  ```
927
927
 
928
- - Chi phí mặc định lấy theo dịch vụ: phái sinh 1,5 bp mỗi chiều; cổ phiếu 15 bp mỗi chiều, thêm 10 bp thuế khi bán và nửa bước giá cho chênh lệch mua bán.
928
+ - Chi phí mặc định lấy theo dịch vụ: phái sinh 1,5 bp mỗi chiều; cổ phiếu 15 bp mỗi chiều, thêm 10 bp thuế khi bán và nửa bước giá cho chênh lệch mua bán. Mức này gồm cả phí môi giới và chênh lệch giá mua bán nên cao hơn chi phí theo từng khoản của các lớp backtest (mục 4.0).
929
929
  - `result.nav` là vốn theo từng nến (bắt đầu từ 1), `result.fills` là các lần khớp, `result.daily` là lợi nhuận theo ngày, `result.stats` gồm lợi nhuận, Sharpe, mức sụt giảm tối đa.
930
930
  - `result.notes` ghi rõ những gì mô phỏng này **chưa** tính: quy định T+2 và biên độ giá với cổ phiếu, việc chuyển hợp đồng hằng tháng với phái sinh. Dịch vụ Track Record có áp dụng các quy định đó.
931
931
 
@@ -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,19 @@ 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
+
1095
+ ### Version 0.2.1
1096
+
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"
1098
+ - `paper.simulate` giữ mức phí của dịch vụ Track Record (1,5 bp mỗi chiều cho phái sinh)
1099
+
1017
1100
  ### Version 0.2.0
1018
1101
 
1019
1102
  - Thêm `quantvn.strategy`: lấy nến theo đúng khung nền tảng dùng, chạy thử chiến lược như khi chạy thật (`replay`), phát hiện nhìn trước tương lai (`check`), kiểm tra file trước khi tải lên (`validate_script`)
@@ -639,7 +639,7 @@ Vị thế ghi ở một nến được quyết định bằng giá đóng cửa
639
639
  - Vị thế của nến `t` được khớp tại `Open` của nến `t+1`.
640
640
  - Mỗi nến ghi nhận lãi lỗ của vị thế cũ từ giá đóng cửa trước đến giá khớp, rồi của vị thế mới từ giá khớp đến giá đóng cửa.
641
641
  - Phí được tính tại nến khớp, trên giá khớp.
642
- - Chi phí thị trường Việt Nam dùng cùng mức với dịch vụ Track Record. Phái sinh VN30: 1,5 bp giá trị hợp đồng mỗi chiều (phí sở, phí bù trừ, thuế, môi giới và nửa bước giá), khoảng 0,28 điểm khi chỉ số ở 1.850. Cổ phiếu: 0,15% mỗi chiều, thêm 0,1% thuế khi bán và nửa bước giá. Các bản cũ chỉ tính phí sở 2.700 đồng cho phái sinh, khoảng một phần mười chi phí thực.
642
+ - Chi phí thị trường Việt Nam được tính theo từng khoản, đúng như nút "Run test" trên website QuantVN. Phái sinh VN30, mỗi hợp đồng mỗi chiều: phí giao dịch HNX 2.700 đồng và thuế thu nhập cá nhân 0,1% trên (giá khớp × 100.000 × tỷ lệ ký quỹ ban đầu 17% ÷ 2); thêm phí quản lý vị thế VSDC 2.550 đồng mỗi hợp đồng mỗi ngày cho vị thế còn mở cuối ngày, tính cả ngày nghỉ. Khi chỉ số ở 1.850, một chiều tốn khoảng 0,18 điểm. Cổ phiếu: phí môi giới 0,1% mỗi chiều và thuế 0,1% trên giá trị bán; cổ phiếu mua ngày T bán được từ 13:00 ngày T+2. Phí môi giới phái sinh và chênh lệch giá mua bán không nằm trong các lớp backtest; `paper.simulate` (mục 5.4) có tính.
643
643
  - Nếu dữ liệu không có cột `Open`, vị thế được khớp tại giá đóng cửa của nến kế tiếp và thư viện phát cảnh báo.
644
644
 
645
645
  Các bản đến 0.1.25 tính lãi lỗ của vị thế ngay từ giá đóng cửa của chính nến ra quyết định, tức là một mức giá đã qua. Vì vậy **kết quả backtest của cùng một chiến lược sẽ khác so với bản cũ**, nhất là với chiến lược giao dịch nhiều. Con số mới là con số có thể đạt được khi chạy thật; các ví dụ đầu ra bên dưới được tạo từ bản cũ nên chỉ minh họa định dạng.
@@ -891,7 +891,7 @@ print(result)
891
891
  print(paper.simulate(df, market="VN_DERIVATIVE", delay_bars=2)) # chậm thêm một nến, gần với chạy thật ở khung 1 phút
892
892
  ```
893
893
 
894
- - Chi phí mặc định lấy theo dịch vụ: phái sinh 1,5 bp mỗi chiều; cổ phiếu 15 bp mỗi chiều, thêm 10 bp thuế khi bán và nửa bước giá cho chênh lệch mua bán.
894
+ - Chi phí mặc định lấy theo dịch vụ: phái sinh 1,5 bp mỗi chiều; cổ phiếu 15 bp mỗi chiều, thêm 10 bp thuế khi bán và nửa bước giá cho chênh lệch mua bán. Mức này gồm cả phí môi giới và chênh lệch giá mua bán nên cao hơn chi phí theo từng khoản của các lớp backtest (mục 4.0).
895
895
  - `result.nav` là vốn theo từng nến (bắt đầu từ 1), `result.fills` là các lần khớp, `result.daily` là lợi nhuận theo ngày, `result.stats` gồm lợi nhuận, Sharpe, mức sụt giảm tối đa.
896
896
  - `result.notes` ghi rõ những gì mô phỏng này **chưa** tính: quy định T+2 và biên độ giá với cổ phiếu, việc chuyển hợp đồng hằng tháng với phái sinh. Dịch vụ Track Record có áp dụng các quy định đó.
897
897
 
@@ -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,19 @@ 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
+
1061
+ ### Version 0.2.1
1062
+
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"
1064
+ - `paper.simulate` giữ mức phí của dịch vụ Track Record (1,5 bp mỗi chiều cho phái sinh)
1065
+
983
1066
  ### Version 0.2.0
984
1067
 
985
1068
  - Thêm `quantvn.strategy`: lấy nến theo đúng khung nền tảng dùng, chạy thử chiến lược như khi chạy thật (`replay`), phát hiện nhìn trước tương lai (`check`), kiểm tra file trước khi tải lên (`validate_script`)
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ from .derivatives import get_funding_rates, get_hist as get_crypto_hist, list_symbols as list_crypto_symbols
4
+
5
+ __all__ = ["get_crypto_hist", "get_funding_rates", "list_crypto_symbols"]
@@ -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)