quantvn 0.3.0__tar.gz → 0.4.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 (55) hide show
  1. {quantvn-0.3.0/quantvn.egg-info → quantvn-0.4.0}/PKG-INFO +28 -1
  2. {quantvn-0.3.0 → quantvn-0.4.0}/README.md +27 -0
  3. quantvn-0.4.0/quantvn/fx/__init__.py +4 -0
  4. quantvn-0.4.0/quantvn/fx/data.py +103 -0
  5. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/marketdata.py +1 -1
  6. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/paper/single_asset.py +16 -1
  7. {quantvn-0.3.0 → quantvn-0.4.0/quantvn.egg-info}/PKG-INFO +28 -1
  8. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn.egg-info/SOURCES.txt +2 -0
  9. {quantvn-0.3.0 → quantvn-0.4.0}/setup.py +1 -1
  10. {quantvn-0.3.0 → quantvn-0.4.0}/tests/test_paper.py +18 -0
  11. {quantvn-0.3.0 → quantvn-0.4.0}/LICENSE +0 -0
  12. {quantvn-0.3.0 → quantvn-0.4.0}/MANIFEST.in +0 -0
  13. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/__init__.py +0 -0
  14. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/crypto/__init__.py +0 -0
  15. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/crypto/data/__init__.py +0 -0
  16. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/crypto/data/derivatives.py +0 -0
  17. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/crypto/data/download.py +0 -0
  18. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/crypto/metrics/__init__.py +0 -0
  19. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/crypto/metrics/backtest.py +0 -0
  20. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/crypto/metrics/metrics.py +0 -0
  21. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/metrics/__init__.py +0 -0
  22. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/metrics/_fills.py +0 -0
  23. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/metrics/portfolio.py +0 -0
  24. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/metrics/single_asset.py +0 -0
  25. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/metrics/st.py +0 -0
  26. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/paper/__init__.py +0 -0
  27. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/paper/client.py +0 -0
  28. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/paper/portfolio.py +0 -0
  29. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/strategy/__init__.py +0 -0
  30. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/strategy/frames.py +0 -0
  31. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/strategy/harness.py +0 -0
  32. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/strategy/script.py +0 -0
  33. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/us/__init__.py +0 -0
  34. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/us/data/__init__.py +0 -0
  35. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/us/data/stocks.py +0 -0
  36. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/us/metrics/__init__.py +0 -0
  37. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/us/metrics/backtest.py +0 -0
  38. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/vn/__init__.py +0 -0
  39. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/vn/data/__init__.py +0 -0
  40. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/vn/data/const.py +0 -0
  41. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/vn/data/core.py +0 -0
  42. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/vn/data/derivatives.py +0 -0
  43. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/vn/data/macro.py +0 -0
  44. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/vn/data/stocks.py +0 -0
  45. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/vn/data/utils.py +0 -0
  46. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/vn/metrics/__init__.py +0 -0
  47. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/vn/metrics/backtest.py +0 -0
  48. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn/vn/metrics/metrics.py +0 -0
  49. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn.egg-info/dependency_links.txt +0 -0
  50. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn.egg-info/requires.txt +0 -0
  51. {quantvn-0.3.0 → quantvn-0.4.0}/quantvn.egg-info/top_level.txt +0 -0
  52. {quantvn-0.3.0 → quantvn-0.4.0}/setup.cfg +0 -0
  53. {quantvn-0.3.0 → quantvn-0.4.0}/tests/test_backtests.py +0 -0
  54. {quantvn-0.3.0 → quantvn-0.4.0}/tests/test_markets.py +0 -0
  55. {quantvn-0.3.0 → quantvn-0.4.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.0
3
+ Version: 0.4.0
4
4
  Summary: QuantVN API Library for Financial Data Analysis
5
5
  Author: quantvn
6
6
  Classifier: Development Status :: 3 - Alpha
@@ -961,6 +961,7 @@ Dữ liệu cổ phiếu/ETF Mỹ và crypto lấy từ **API dữ liệu thị
961
961
  | `crypto_funding` | Funding rate từng kỳ | Binance | 10 phút |
962
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
963
  | `us_stock_1d` | Nến ngày toàn bộ lịch sử, có `adj_close` | Yahoo Finance | mỗi ngày |
964
+ | `forex` | 28 cặp tiền của USD, EUR, GBP, JPY, CHF, AUD, CAD, NZD, cùng XAUUSD, XAGUSD; nến 1 phút từ 2000–2009 tùy mã | HistData (giá bid, công bố theo tháng); các tuần chưa công bố lấy giá giữa từ TradingView FX_IDC, phần cũ hơn 3,5 ngày lấy từ Yahoo (nến thô hơn) | 10 phút |
964
965
 
965
966
  #### 6.1. Crypto
966
967
 
@@ -1020,6 +1021,27 @@ marketdata.bars("crypto_spot", "SOLUSDT", "2026-11-01", "2026-11-02", interval="
1020
1021
 
1021
1022
  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
1023
 
1024
+ #### 6.5. Forex
1025
+
1026
+ ```python
1027
+ from quantvn import paper
1028
+ from quantvn.fx import data as fx
1029
+
1030
+ fx.list_symbols() # 30 mã: EURUSD, USDJPY, ..., XAUUSD, XAGUSD
1031
+ df = fx.get_hist("EURUSD", "15m", start="2026-10-01", end="2026-11-01") # Datetime theo UTC, volume rỗng
1032
+ df["position"] = ... # tỷ trọng vốn, -1 đến 1
1033
+ swap = fx.swap_schedule("EURUSD", "2026-10-01", "2026-11-01", rates={"EUR": 2.65, "USD": 4.0})
1034
+ print(paper.simulate(df, market="FOREX", symbol="EURUSD", funding=swap))
1035
+ ```
1036
+
1037
+ Chi phí giống Track Record (thị trường `FOREX`, mở từ 16/11/2026):
1038
+
1039
+ - **Phí:** 0,35 bp mỗi chiều, bằng hoa hồng tài khoản ECN (3,5 USD cho 100.000 đơn vị).
1040
+ - **Chênh lệch giá mua/bán:** mỗi lệnh khớp trả thêm nửa spread của cặp đó, đo trên dữ liệu tick HistData 2019 và 2023 (`fx.HALF_SPREAD_BP`): 0,15 bp với EURUSD, 0,25 bp với USDJPY, đến 1,7 bp với NZDCHF và 7,45 bp với XAGUSD. Truyền `symbol=` để `simulate` tính khoản này.
1041
+ - **Swap qua đêm:** giữ vị thế qua 17:00 New York thì trả hoặc nhận chênh lệch lãi suất hai đồng tiền, `(r_quote - r_base) / 365` mỗi ngày với vị thế mua; phiên thứ Tư tính 3 ngày. Track Record dùng lãi suất điều hành của ngân hàng trung ương; `swap_schedule` nhận lãi suất bạn đưa vào (phần trăm/năm). Vàng, bạc không có lãi suất, nên mua XAUUSD phải trả lãi suất USD.
1042
+
1043
+ Nến `1d` của API là ngày UTC, không phải ngày forex kết thúc lúc 17:00 New York. Giá trước tháng HistData công bố gần nhất là giá bid, sau đó là giá giữa, nên tại điểm nối có thể lệch khoảng nửa spread.
1044
+
1023
1045
  ---
1024
1046
 
1025
1047
  ## Ví dụ thực tế
@@ -1084,6 +1106,11 @@ Dự án này được phát hành theo giấy phép **MIT License**. Xem file [
1084
1106
 
1085
1107
  ## Changelog
1086
1108
 
1109
+ ### Version 0.4.0
1110
+
1111
+ - Thêm `quantvn.fx`: `get_hist`, `list_symbols`, `swap_schedule`, `HALF_SPREAD_BP` cho 28 cặp tiền chính, XAUUSD và XAGUSD (bộ dữ liệu `forex` của API dữ liệu thị trường, mục 6.5)
1112
+ - `paper.simulate`: thêm thị trường `FOREX` (phí 0,35 bp, nửa spread từng cặp qua `symbol=`, swap qua `funding=`), trùng với Track Record
1113
+
1087
1114
  ### Version 0.3.0
1088
1115
 
1089
1116
  - 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)
@@ -927,6 +927,7 @@ Dữ liệu cổ phiếu/ETF Mỹ và crypto lấy từ **API dữ liệu thị
927
927
  | `crypto_funding` | Funding rate từng kỳ | Binance | 10 phút |
928
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
929
  | `us_stock_1d` | Nến ngày toàn bộ lịch sử, có `adj_close` | Yahoo Finance | mỗi ngày |
930
+ | `forex` | 28 cặp tiền của USD, EUR, GBP, JPY, CHF, AUD, CAD, NZD, cùng XAUUSD, XAGUSD; nến 1 phút từ 2000–2009 tùy mã | HistData (giá bid, công bố theo tháng); các tuần chưa công bố lấy giá giữa từ TradingView FX_IDC, phần cũ hơn 3,5 ngày lấy từ Yahoo (nến thô hơn) | 10 phút |
930
931
 
931
932
  #### 6.1. Crypto
932
933
 
@@ -986,6 +987,27 @@ marketdata.bars("crypto_spot", "SOLUSDT", "2026-11-01", "2026-11-02", interval="
986
987
 
987
988
  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
989
 
990
+ #### 6.5. Forex
991
+
992
+ ```python
993
+ from quantvn import paper
994
+ from quantvn.fx import data as fx
995
+
996
+ fx.list_symbols() # 30 mã: EURUSD, USDJPY, ..., XAUUSD, XAGUSD
997
+ df = fx.get_hist("EURUSD", "15m", start="2026-10-01", end="2026-11-01") # Datetime theo UTC, volume rỗng
998
+ df["position"] = ... # tỷ trọng vốn, -1 đến 1
999
+ swap = fx.swap_schedule("EURUSD", "2026-10-01", "2026-11-01", rates={"EUR": 2.65, "USD": 4.0})
1000
+ print(paper.simulate(df, market="FOREX", symbol="EURUSD", funding=swap))
1001
+ ```
1002
+
1003
+ Chi phí giống Track Record (thị trường `FOREX`, mở từ 16/11/2026):
1004
+
1005
+ - **Phí:** 0,35 bp mỗi chiều, bằng hoa hồng tài khoản ECN (3,5 USD cho 100.000 đơn vị).
1006
+ - **Chênh lệch giá mua/bán:** mỗi lệnh khớp trả thêm nửa spread của cặp đó, đo trên dữ liệu tick HistData 2019 và 2023 (`fx.HALF_SPREAD_BP`): 0,15 bp với EURUSD, 0,25 bp với USDJPY, đến 1,7 bp với NZDCHF và 7,45 bp với XAGUSD. Truyền `symbol=` để `simulate` tính khoản này.
1007
+ - **Swap qua đêm:** giữ vị thế qua 17:00 New York thì trả hoặc nhận chênh lệch lãi suất hai đồng tiền, `(r_quote - r_base) / 365` mỗi ngày với vị thế mua; phiên thứ Tư tính 3 ngày. Track Record dùng lãi suất điều hành của ngân hàng trung ương; `swap_schedule` nhận lãi suất bạn đưa vào (phần trăm/năm). Vàng, bạc không có lãi suất, nên mua XAUUSD phải trả lãi suất USD.
1008
+
1009
+ Nến `1d` của API là ngày UTC, không phải ngày forex kết thúc lúc 17:00 New York. Giá trước tháng HistData công bố gần nhất là giá bid, sau đó là giá giữa, nên tại điểm nối có thể lệch khoảng nửa spread.
1010
+
989
1011
  ---
990
1012
 
991
1013
  ## Ví dụ thực tế
@@ -1050,6 +1072,11 @@ Dự án này được phát hành theo giấy phép **MIT License**. Xem file [
1050
1072
 
1051
1073
  ## Changelog
1052
1074
 
1075
+ ### Version 0.4.0
1076
+
1077
+ - Thêm `quantvn.fx`: `get_hist`, `list_symbols`, `swap_schedule`, `HALF_SPREAD_BP` cho 28 cặp tiền chính, XAUUSD và XAGUSD (bộ dữ liệu `forex` của API dữ liệu thị trường, mục 6.5)
1078
+ - `paper.simulate`: thêm thị trường `FOREX` (phí 0,35 bp, nửa spread từng cặp qua `symbol=`, swap qua `funding=`), trùng với Track Record
1079
+
1053
1080
  ### Version 0.3.0
1054
1081
 
1055
1082
  - 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)
@@ -0,0 +1,4 @@
1
+ from quantvn.fx import data
2
+ from quantvn.fx.data import get_hist as get_fx_hist, list_symbols as list_fx_symbols, swap_schedule
3
+
4
+ __all__ = ["data", "get_fx_hist", "list_fx_symbols", "swap_schedule"]
@@ -0,0 +1,103 @@
1
+ """Forex: the 28 pairs of USD, EUR, GBP, JPY, CHF, AUD, CAD, NZD, plus XAUUSD and XAGUSD.
2
+
3
+ Bars come from the QuantVN market-data API (dataset ``forex``): HistData 1-minute BID bars, and for the weeks
4
+ HistData has not published yet, live mid quotes (TradingView FX_IDC; Yahoo for older gaps of pairs). The
5
+ same prices, the same per-pair spread (``HALF_SPREAD_BP``) and the same swap rule are used by the QuantVN
6
+ Track Record service for ``FOREX`` paper trades.
7
+
8
+ from quantvn.fx import data
9
+ df = data.get_hist("EURUSD", "15m", "2026-10-01", "2026-11-01")
10
+ swap = data.swap_schedule("EURUSD", "2026-10-01", "2026-11-01", rates={"EUR": 2.65, "USD": 4.0})
11
+ quantvn.paper.simulate(df.assign(position=...), market="FOREX", symbol="EURUSD", funding=swap)
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import datetime as dt
16
+ import time
17
+ from typing import Optional
18
+ from zoneinfo import ZoneInfo
19
+
20
+ import pandas as pd
21
+
22
+ from quantvn import marketdata
23
+
24
+ __all__ = ["HALF_SPREAD_BP", "PAIRS", "get_hist", "list_symbols", "swap_schedule"]
25
+
26
+ # Half the bid-ask spread per side, bp: HistData tick data 2019 and 2023, the larger year (Track Record engine/fx.py).
27
+ HALF_SPREAD_BP = {
28
+ "EURUSD": 0.15, "GBPUSD": 0.40, "USDJPY": 0.25, "USDCHF": 0.60, "AUDUSD": 0.80, "USDCAD": 0.50, "NZDUSD": 0.95,
29
+ "EURJPY": 0.40, "EURGBP": 0.60, "EURCHF": 0.65, "EURAUD": 0.80, "EURCAD": 0.70, "EURNZD": 0.90, "GBPJPY": 0.70,
30
+ "GBPCHF": 0.90, "GBPAUD": 0.85, "GBPCAD": 1.00, "GBPNZD": 1.10, "AUDJPY": 0.55, "AUDCAD": 1.15, "AUDCHF": 1.25,
31
+ "AUDNZD": 1.00, "CADJPY": 0.60, "CADCHF": 1.15, "CHFJPY": 0.70, "NZDJPY": 0.65, "NZDCAD": 1.40, "NZDCHF": 1.70,
32
+ "XAUUSD": 1.15, "XAGUSD": 7.45,
33
+ }
34
+ PAIRS = tuple(HALF_SPREAD_BP)
35
+ METALS = ("XAU", "XAG")
36
+ RESOLUTIONS = {"1m", "5m", "15m", "30m", "1h", "4h", "1d"}
37
+ _NY = ZoneInfo("America/New_York")
38
+
39
+
40
+ def get_hist(symbol: str, resolution: str = "1m", start=None, end=None, tz: Optional[str] = None) -> pd.DataFrame:
41
+ """
42
+ Historical bars of a currency pair, gold or silver.
43
+
44
+ Parameters
45
+ ----------
46
+ symbol : str
47
+ "EURUSD", "USDJPY", "XAUUSD", ... (``PAIRS``). "EUR/USD" is accepted.
48
+ resolution : str
49
+ "1m", "5m", "15m", "30m", "1h", "4h" or "1d". Aggregated bars are built from 1-minute bars on UTC
50
+ boundaries (a "1d" bar is a UTC day, not the 17:00 New York forex day).
51
+ start, end : date, datetime or epoch ms, optional
52
+ The window, end exclusive; a value without a time zone is UTC. Default: the 30 days before now.
53
+ tz : str or None
54
+ Time zone of the Datetime column (default None = UTC).
55
+
56
+ Returns
57
+ -------
58
+ pd.DataFrame
59
+ [Datetime, Date, time, Open, High, Low, Close, volume]. Datetime is the bar's OPEN time. volume is NaN:
60
+ spot forex has no consolidated volume. Prices are bid up to HistData's last published month, mid after.
61
+ """
62
+ res = str(resolution).lower().strip()
63
+ if res not in RESOLUTIONS:
64
+ raise ValueError(f"resolution must be one of: {', '.join(sorted(RESOLUTIONS))}.")
65
+ sym = str(symbol).upper().replace("/", "").strip()
66
+ end_ms = marketdata.to_ms(end, int(time.time() * 1000))
67
+ start_ms = marketdata.to_ms(start, end_ms - 30 * 86_400_000)
68
+ return marketdata.to_candles(marketdata.bars("forex", sym, start_ms, end_ms, res), tz)
69
+
70
+
71
+ def list_symbols() -> list:
72
+ """Symbols the QuantVN API stores for forex."""
73
+ return marketdata.symbols("forex")
74
+
75
+
76
+ def swap_schedule(symbol: str, start, end, rates: dict) -> pd.DataFrame:
77
+ """Overnight swap of a forex position as the Track Record service charges it, for ``paper.simulate(...,
78
+ funding=)``: one row per rollover at 17:00 New York, Monday to Friday, with start <= time < end.
79
+
80
+ ``rates``: annual interest rate in percent per currency, e.g. ``{"EUR": 2.65, "USD": 4.0}`` (the service
81
+ uses the central banks' policy rates, held constant between changes). Gold and silver earn no rate.
82
+
83
+ Returns ``Datetime`` (UTC) and ``rate``: what a LONG position pays at that rollover, as a fraction of its
84
+ size, ``(r_quote - r_base) / 100 / 365`` per day; Wednesday's rollover counts three days. Negative = the long
85
+ receives. A short receives what a long pays.
86
+ """
87
+ sym = str(symbol).upper().replace("/", "").strip()
88
+ base, quote = sym[:3], sym[3:6]
89
+ r_base = 0.0 if base in METALS else float(rates[base])
90
+ r_quote = float(rates[quote])
91
+ a, b = marketdata.to_ms(start), marketdata.to_ms(end)
92
+ d = dt.datetime.fromtimestamp(a / 1000, _NY).date() - dt.timedelta(days=1)
93
+ last = dt.datetime.fromtimestamp(b / 1000, _NY).date()
94
+ rows = []
95
+ while d <= last:
96
+ if d.weekday() < 5:
97
+ t = dt.datetime(d.year, d.month, d.day, 17, 0, tzinfo=_NY)
98
+ ms = int(t.timestamp() * 1000)
99
+ if a <= ms < b:
100
+ days = 3 if d.weekday() == 2 else 1
101
+ rows.append((pd.Timestamp(ms, unit="ms", tz="UTC"), (r_quote - r_base) / 100 / 365 * days))
102
+ d += dt.timedelta(days=1)
103
+ return pd.DataFrame(rows, columns=["Datetime", "rate"])
@@ -86,7 +86,7 @@ def datasets() -> dict:
86
86
 
87
87
 
88
88
  def symbols(dataset: str) -> list:
89
- """Symbols of a dataset: crypto_spot, crypto_perp, crypto_funding, us_stock, us_stock_1d."""
89
+ """Symbols of a dataset: crypto_spot, crypto_perp, crypto_funding, us_stock, us_stock_1d, forex."""
90
90
  return [s["symbol"] for s in _get("/symbols", {"dataset": dataset}).json()["symbols"]]
91
91
 
92
92
 
@@ -16,6 +16,7 @@ from typing import List, Optional
16
16
  import numpy as np
17
17
  import pandas as pd
18
18
 
19
+ from quantvn.fx.data import HALF_SPREAD_BP as FX_HALF_SPREAD_BP
19
20
  from quantvn.metrics._fills import VN_FUTURES_FEE, VN_STOCK_FEE, VN_STOCK_SELL_TAX, vn_tick
20
21
 
21
22
  # Costs per market as the Track Record service charges them (GET https://paper.quantvn.com/v1/assets).
@@ -28,6 +29,8 @@ MARKETS = {
28
29
  # Binance USD-M perpetuals: 5 bp per side, short allowed, funding settled at every funding event
29
30
  "CRYPTO_PERP": {"fee": 5e-4, "sell_tax": 0.0, "min_pos": -1.0, "max_pos": 1.0, "spread_ticks": 0.0},
30
31
  "US_STOCK": {"fee": 1e-4, "sell_tax": 0.0, "min_pos": -1.0, "max_pos": 1.0, "spread_ticks": 0.0},
32
+ # ECN commission per side; half the pair's spread (quantvn.fx.data.HALF_SPREAD_BP) and the swap come on top
33
+ "FOREX": {"fee": 0.35e-4, "sell_tax": 0.0, "min_pos": -1.0, "max_pos": 1.0, "spread_ticks": 0.0},
31
34
  }
32
35
 
33
36
 
@@ -52,7 +55,8 @@ class PaperResult:
52
55
 
53
56
  def simulate(df: pd.DataFrame, market: str = "VN_DERIVATIVE", delay_bars: int = 1, fee: Optional[float] = None,
54
57
  sell_tax: Optional[float] = None, spread_ticks: Optional[float] = None,
55
- exchange: str = "HOSE", funding: Optional[pd.DataFrame] = None) -> PaperResult:
58
+ exchange: str = "HOSE", funding: Optional[pd.DataFrame] = None,
59
+ symbol: Optional[str] = None) -> PaperResult:
56
60
  """Price the ``position`` column of `df` with the Track Record fill rule.
57
61
 
58
62
  `df` needs ``Datetime`` (bar open time), ``Open``, ``Close`` and ``position``, where the position on a
@@ -66,6 +70,9 @@ def simulate(df: pd.DataFrame, market: str = "VN_DERIVATIVE", delay_bars: int =
66
70
  time t is settled at the first bar that opens at or after t, on the weight held before that bar's fill:
67
71
  equity is multiplied by ``1 - weight * rate`` (a long pays a positive rate, a short receives it). A bar
68
72
  ``Datetime`` without a time zone is read as UTC.
73
+
74
+ ``FOREX``: pass ``symbol`` ("EURUSD") to charge half the pair's spread on every fill, as the service does,
75
+ and ``funding=quantvn.fx.data.swap_schedule(symbol, start, end, rates)`` for the overnight swap.
69
76
  """
70
77
  if market not in MARKETS:
71
78
  raise ValueError(f"market must be one of {', '.join(MARKETS)}")
@@ -75,6 +82,9 @@ def simulate(df: pd.DataFrame, market: str = "VN_DERIVATIVE", delay_bars: int =
75
82
  fee = m["fee"] if fee is None else fee
76
83
  sell_tax = m["sell_tax"] if sell_tax is None else sell_tax
77
84
  spread_ticks = m["spread_ticks"] if spread_ticks is None else spread_ticks
85
+ fx_half = 0.0
86
+ if market == "FOREX" and symbol is not None:
87
+ fx_half = FX_HALF_SPREAD_BP[str(symbol).upper().replace("/", "")] / 1e4
78
88
  d = df.sort_values("Datetime").reset_index(drop=True)
79
89
  ts = pd.to_datetime(d["Datetime"])
80
90
  op, cl = d["Open"].to_numpy(float), d["Close"].to_numpy(float)
@@ -97,6 +107,7 @@ def simulate(df: pd.DataFrame, market: str = "VN_DERIVATIVE", delay_bars: int =
97
107
  cost = dw * fee + max(max(w, 0.0) - max(new, 0.0), 0.0) * sell_tax
98
108
  if spread_ticks:
99
109
  cost += dw * spread_ticks * (vn_tick(op[k], exchange) if market == "VN_STOCK" else 0.0) / 2 / op[k]
110
+ cost += dw * fx_half
100
111
  nav *= 1 - cost
101
112
  fills.append((ts.iloc[k], op[k], w, new, cost))
102
113
  w = new
@@ -122,6 +133,10 @@ def simulate(df: pd.DataFrame, market: str = "VN_DERIVATIVE", delay_bars: int =
122
133
  notes.append("the monthly contract roll is not simulated here; the Track Record service applies it")
123
134
  if market == "CRYPTO_PERP" and funding is None:
124
135
  notes.append("funding was not charged: pass funding=quantvn.crypto.data.get_funding_rates(symbol, start, end)")
136
+ if market == "FOREX" and symbol is None:
137
+ notes.append("the spread was not charged: pass symbol='EURUSD' (or the pair traded)")
138
+ if market == "FOREX" and funding is None:
139
+ notes.append("the swap was not charged: pass funding=quantvn.fx.data.swap_schedule(symbol, start, end, rates)")
125
140
  return PaperResult(nav_s, pd.DataFrame(fills, columns=["time", "price", "before", "after", "cost"]), daily, stats, notes)
126
141
 
127
142
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantvn
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: QuantVN API Library for Financial Data Analysis
5
5
  Author: quantvn
6
6
  Classifier: Development Status :: 3 - Alpha
@@ -961,6 +961,7 @@ Dữ liệu cổ phiếu/ETF Mỹ và crypto lấy từ **API dữ liệu thị
961
961
  | `crypto_funding` | Funding rate từng kỳ | Binance | 10 phút |
962
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
963
  | `us_stock_1d` | Nến ngày toàn bộ lịch sử, có `adj_close` | Yahoo Finance | mỗi ngày |
964
+ | `forex` | 28 cặp tiền của USD, EUR, GBP, JPY, CHF, AUD, CAD, NZD, cùng XAUUSD, XAGUSD; nến 1 phút từ 2000–2009 tùy mã | HistData (giá bid, công bố theo tháng); các tuần chưa công bố lấy giá giữa từ TradingView FX_IDC, phần cũ hơn 3,5 ngày lấy từ Yahoo (nến thô hơn) | 10 phút |
964
965
 
965
966
  #### 6.1. Crypto
966
967
 
@@ -1020,6 +1021,27 @@ marketdata.bars("crypto_spot", "SOLUSDT", "2026-11-01", "2026-11-02", interval="
1020
1021
 
1021
1022
  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
1023
 
1024
+ #### 6.5. Forex
1025
+
1026
+ ```python
1027
+ from quantvn import paper
1028
+ from quantvn.fx import data as fx
1029
+
1030
+ fx.list_symbols() # 30 mã: EURUSD, USDJPY, ..., XAUUSD, XAGUSD
1031
+ df = fx.get_hist("EURUSD", "15m", start="2026-10-01", end="2026-11-01") # Datetime theo UTC, volume rỗng
1032
+ df["position"] = ... # tỷ trọng vốn, -1 đến 1
1033
+ swap = fx.swap_schedule("EURUSD", "2026-10-01", "2026-11-01", rates={"EUR": 2.65, "USD": 4.0})
1034
+ print(paper.simulate(df, market="FOREX", symbol="EURUSD", funding=swap))
1035
+ ```
1036
+
1037
+ Chi phí giống Track Record (thị trường `FOREX`, mở từ 16/11/2026):
1038
+
1039
+ - **Phí:** 0,35 bp mỗi chiều, bằng hoa hồng tài khoản ECN (3,5 USD cho 100.000 đơn vị).
1040
+ - **Chênh lệch giá mua/bán:** mỗi lệnh khớp trả thêm nửa spread của cặp đó, đo trên dữ liệu tick HistData 2019 và 2023 (`fx.HALF_SPREAD_BP`): 0,15 bp với EURUSD, 0,25 bp với USDJPY, đến 1,7 bp với NZDCHF và 7,45 bp với XAGUSD. Truyền `symbol=` để `simulate` tính khoản này.
1041
+ - **Swap qua đêm:** giữ vị thế qua 17:00 New York thì trả hoặc nhận chênh lệch lãi suất hai đồng tiền, `(r_quote - r_base) / 365` mỗi ngày với vị thế mua; phiên thứ Tư tính 3 ngày. Track Record dùng lãi suất điều hành của ngân hàng trung ương; `swap_schedule` nhận lãi suất bạn đưa vào (phần trăm/năm). Vàng, bạc không có lãi suất, nên mua XAUUSD phải trả lãi suất USD.
1042
+
1043
+ Nến `1d` của API là ngày UTC, không phải ngày forex kết thúc lúc 17:00 New York. Giá trước tháng HistData công bố gần nhất là giá bid, sau đó là giá giữa, nên tại điểm nối có thể lệch khoảng nửa spread.
1044
+
1023
1045
  ---
1024
1046
 
1025
1047
  ## Ví dụ thực tế
@@ -1084,6 +1106,11 @@ Dự án này được phát hành theo giấy phép **MIT License**. Xem file [
1084
1106
 
1085
1107
  ## Changelog
1086
1108
 
1109
+ ### Version 0.4.0
1110
+
1111
+ - Thêm `quantvn.fx`: `get_hist`, `list_symbols`, `swap_schedule`, `HALF_SPREAD_BP` cho 28 cặp tiền chính, XAUUSD và XAGUSD (bộ dữ liệu `forex` của API dữ liệu thị trường, mục 6.5)
1112
+ - `paper.simulate`: thêm thị trường `FOREX` (phí 0,35 bp, nửa spread từng cặp qua `symbol=`, swap qua `funding=`), trùng với Track Record
1113
+
1087
1114
  ### Version 0.3.0
1088
1115
 
1089
1116
  - 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)
@@ -16,6 +16,8 @@ quantvn/crypto/data/download.py
16
16
  quantvn/crypto/metrics/__init__.py
17
17
  quantvn/crypto/metrics/backtest.py
18
18
  quantvn/crypto/metrics/metrics.py
19
+ quantvn/fx/__init__.py
20
+ quantvn/fx/data.py
19
21
  quantvn/metrics/__init__.py
20
22
  quantvn/metrics/_fills.py
21
23
  quantvn/metrics/portfolio.py
@@ -2,7 +2,7 @@ from setuptools import find_packages, setup
2
2
 
3
3
  setup(
4
4
  name="quantvn",
5
- version="0.3.0",
5
+ version="0.4.0",
6
6
  packages=find_packages(),
7
7
  install_requires=[
8
8
  "requests",
@@ -48,6 +48,24 @@ def test_daily_statistics():
48
48
  assert r.stats["max_drawdown"] == pytest.approx(102 / 103 - 1) and "return" in repr(r)
49
49
 
50
50
 
51
+ def test_forex_pays_commission_half_spread_and_swap_like_the_service():
52
+ from quantvn.fx import data as fx
53
+ # winter: 17:00 New York is 22:00 UTC; Wednesday's rollover counts three days
54
+ s = fx.swap_schedule("USDJPY", "2026-11-16", "2026-11-21", {"USD": 4.0, "JPY": 1.25})
55
+ assert [t.strftime("%a %H:%M") for t in s["Datetime"]] == ["Mon 22:00", "Tue 22:00", "Wed 22:00", "Thu 22:00",
56
+ "Fri 22:00"]
57
+ assert list(s["rate"]) == pytest.approx([-2.75 / 36500 * d for d in (1, 1, 3, 1, 1)]) # long USD receives
58
+ assert fx.swap_schedule("XAUUSD", "2026-11-16", "2026-11-17", {"USD": 4.0})["rate"][0] == pytest.approx(4 / 36500)
59
+ # long EURUSD bought at 21:58 UTC, flat prices, held through Monday's rollover
60
+ df = frame([1.1] * 5, [1.1] * 5, [1, 1, 1, 1, 1], "2026-11-16 21:57")
61
+ swap = fx.swap_schedule("EURUSD", "2026-11-16", "2026-11-17", {"EUR": 2.65, "USD": 4.0})
62
+ r = paper.simulate(df, market="FOREX", symbol="EURUSD", funding=swap)
63
+ assert r.nav.iloc[-1] == pytest.approx((1 - 0.35e-4 - 0.15e-4) * (1 - 1.35 / 36500))
64
+ assert r.stats["funding"] == pytest.approx(1.35 / 36500) and not r.notes
65
+ bare = paper.simulate(df, market="FOREX")
66
+ assert bare.nav.iloc[-1] == pytest.approx(1 - 0.35e-4) and len(bare.notes) == 2
67
+
68
+
51
69
  class FakeResponse:
52
70
  def __init__(self, status, body):
53
71
  self.status_code, self._body, self.text = status, body, str(body)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes