RichardVR commited on
Commit
fce236e
·
verified ·
1 Parent(s): 696bfeb

Upload 27 files

Browse files
Advance_version/.DS_Store ADDED
Binary file (6.15 kB). View file
 
Advance_version/__pycache__/backtester.cpython-312.pyc ADDED
Binary file (6.08 kB). View file
 
Advance_version/__pycache__/data_loader.cpython-312.pyc ADDED
Binary file (3.61 kB). View file
 
Advance_version/__pycache__/kalman_hedge.cpython-312.pyc ADDED
Binary file (7.08 kB). View file
 
Advance_version/__pycache__/logger.cpython-312.pyc ADDED
Binary file (1.25 kB). View file
 
Advance_version/__pycache__/pair_selector.cpython-312.pyc ADDED
Binary file (4.41 kB). View file
 
Advance_version/__pycache__/portfolio_optimizer.cpython-312.pyc ADDED
Binary file (3.32 kB). View file
 
Advance_version/__pycache__/risk_engine.cpython-312.pyc ADDED
Binary file (5.64 kB). View file
 
Advance_version/__pycache__/signal_generator.cpython-312.pyc ADDED
Binary file (5.45 kB). View file
 
Advance_version/__pycache__/utils.cpython-312.pyc ADDED
Binary file (4.95 kB). View file
 
Advance_version/backtester.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import logging
4
+
5
+ logger = logging.getLogger(__name__)
6
+ class Backtester:
7
+ def __init__(self, trade_df: pd.DataFrame, costs: dict, volume: pd.DataFrame, ticker1: str, ticker2: str):
8
+ self.df = trade_df.copy()
9
+ self.fixed_cost = costs["fixed_per_trade"]
10
+ self.slip_coeff = costs["slippage_coefficient"]
11
+ self.volume = volume
12
+ self.ticker1 = ticker1
13
+ self.ticker2 = ticker2
14
+ self._prepare()
15
+
16
+
17
+ def _prepare(self):
18
+ """
19
+ 1. Compute daily returns for each leg.
20
+ 2. Align positions with returns (shift positions by 1 day to avoid look‐ahead).
21
+ 3. Compute trades (where positions change).
22
+ """
23
+ self.df["ret1"] = self.df["price1"].pct_change().fillna(0)
24
+ self.df["ret2"] = self.df["price2"].pct_change().fillna(0)
25
+
26
+ # Shift positions to align with next day's pnl
27
+ self.df["pos1_lag"] = self.df["pos1"].shift(1).fillna(0)
28
+ self.df["pos2_lag"] = self.df["pos2"].shift(1).fillna(0)
29
+
30
+ # Identify when trades occur (pos changes)
31
+ self.df["trade1"] = (self.df["pos1"] != self.df["pos1_lag"]).astype(int)
32
+ self.df["trade2"] = (self.df["pos2"] != self.df["pos2_lag"]).astype(int)
33
+
34
+ def run(self) -> pd.DataFrame:
35
+ """
36
+ Compute P&L step by step:
37
+ 1) Gross P&L: pos_lag * returns
38
+ 2) Subtract transaction costs when trade occurs:
39
+ fixed cost + slippage based on ADV
40
+ Returns a DataFrame augmented with P&L columns.
41
+ """
42
+ df = self.df.copy()
43
+
44
+ # 1) Gross P&L (as fraction of capital)
45
+ df["pnl1"] = df["pos1_lag"] * df["ret1"]
46
+ df["pnl2"] = df["pos2_lag"] * df["ret2"]
47
+ df["gross_pnl"] = df["pnl1"] + df["pnl2"]
48
+
49
+ # 2) Transaction costs
50
+ # For each trade, cost = fixed + slippage_coefficient * (notional / ADV)
51
+ # Approx ADV: use prev day's volume * price
52
+ adv1 = self.volume[self.ticker1].shift(1) * df["price1"].shift(1)
53
+ adv2 = self.volume[self.ticker2].shift(1) * df["price2"].shift(1)
54
+
55
+ # Avoid division by zero
56
+ adv1 = adv1.replace(0, np.nan).fillna(method="ffill").fillna(1e6)
57
+ adv2 = adv2.replace(0, np.nan).fillna(method="ffill").fillna(1e6)
58
+
59
+ df["slip1"] = (
60
+ self.slip_coeff * (abs(df["pos1"] - df["pos1_lag"]) * df["price1"])
61
+ / adv1
62
+ )
63
+ df["slip2"] = (
64
+ self.slip_coeff * (abs(df["pos2"] - df["pos2_lag"]) * df["price2"])
65
+ / adv2
66
+ )
67
+
68
+ df["trans_cost1"] = df["trade1"] * (self.fixed_cost + df["slip1"])
69
+ df["trans_cost2"] = df["trade2"] * (self.fixed_cost + df["slip2"])
70
+ df["total_tc"] = df["trans_cost1"] + df["trans_cost2"]
71
+
72
+ # 3) Net P&L
73
+ df["net_pnl"] = df["gross_pnl"] - df["total_tc"]
74
+
75
+ # 4) Cumulative returns
76
+ df["strategy_return"] = df["net_pnl"]
77
+ df["cum_return"] = (1 + df["strategy_return"]).cumprod() - 1
78
+
79
+ logger.info("Backtest run completed.")
80
+ return df
81
+
82
+ def performance_metrics(self, df: pd.DataFrame) -> dict:
83
+ """
84
+ Compute standard metrics: Sharpe, annualized return, max drawdown.
85
+ :return: dict of metrics.
86
+ """
87
+ returns = df["strategy_return"].fillna(0)
88
+ ann_return = (1 + returns).prod() ** (252 / len(returns)) - 1
89
+ ann_vol = returns.std() * np.sqrt(252)
90
+ sharpe = ann_return / ann_vol if ann_vol != 0 else np.nan
91
+
92
+ # Max drawdown
93
+ cum = (1 + returns).cumprod()
94
+ peak = cum.cummax()
95
+ drawdown = (cum - peak) / peak
96
+ max_dd = drawdown.min()
97
+
98
+ return {
99
+ "annual_return": ann_return,
100
+ "annual_vol": ann_vol,
101
+ "sharpe": sharpe,
102
+ "max_drawdown": max_dd
103
+ }
Advance_version/config.yaml ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===========================
2
+ # Data Loader Settings
3
+ # ===========================
4
+ data:
5
+ tickers: # List of tickers to consider in universe
6
+ - "3N4.SG"
7
+ - "CUBEXTUB.NS"
8
+ - "JIX.F"
9
+ - "HINDCOPPER.NS"
10
+ - "SARKY.IS"
11
+ - "RE8.F"
12
+ - "BHAGYANGR.NS"
13
+ - "FDY.TO"
14
+ - "9CM0.F"
15
+ - "GRX.AX"
16
+ - "ARREF"
17
+ - "MTJ3.F"
18
+ - "GRX.L"
19
+ - "005810.KS"
20
+ - "2009.TW"
21
+ - "OUW0.F"
22
+ - "CS.TO"
23
+ - "SFR.AX"
24
+ - "PUCOBRE.SN"
25
+ - "ATYM.L"
26
+
27
+ start_date: "2021-01-01"
28
+ end_date: "2025-07-01"
29
+ interval: "1d" # "1d", "5m", etc.
30
+
31
+ # ===========================
32
+ # Pair Selector Settings
33
+ # ===========================
34
+ pair_selector:
35
+ cluster_size: 20 # approx. number of tickers per cluster
36
+ coint_pval_threshold: 0.05
37
+ rolling_window: 252 # days for rolling cointegration
38
+ rolling_step: 63 # days per step
39
+ min_valid_periods: 2 # consecutive windows required
40
+
41
+ # ===========================
42
+ # Kalman Hedge Settings
43
+ # ===========================
44
+ kalman:
45
+ initial_state_cov: [[1e-4, 0], [0, 1e-4]] # small prior covariance for intercept & beta
46
+ transition_cov: [[1e-5, 0], [0, 1e-5]] # process noise; EM will refine
47
+ observation_cov: 1e-3 # observation noise; EM will refine
48
+ em_iterations: 20
49
+
50
+ # ===========================
51
+ # Signal Generator Settings
52
+ # ===========================
53
+ signal:
54
+ zscore_window: 20 # rolling window for spread mean/std
55
+ entry_z: 2.0 # base z-score for entry (will scale by vol)
56
+ exit_z: 0.5 # base z-score for exit
57
+ target_vol: 0.001 # target daily vol of spread (10 bps)
58
+ min_vol_percentile: 30 # only trade if spread vol rank < 30th percentile
59
+ momentum_filter: true # require spread momentum to point back to mean
60
+
61
+ # ===========================
62
+ # Transaction Cost Settings
63
+ # ===========================
64
+ costs:
65
+ fixed_per_trade: 0.000 # $0.005 per share
66
+ slippage_coefficient: 0.0000 # 1 bp slippage per 0.1% of ADV
67
+
68
+ # ===========================
69
+ # Risk Engine Settings
70
+ # ===========================
71
+ risk:
72
+ daily_var_window: 252
73
+ var_confidence: 0.95
74
+ max_drawdown_limit: 0.02 # 2% per day (hard stop)
75
+ worst_pair_dd: 0.05 # drop pair if drawdown > 5%
76
+
77
+ # ===========================
78
+ # Portfolio Optimizer Settings
79
+ # ===========================
80
+ portfolio:
81
+ min_weight: 0.0
82
+ max_weight: 0.1 # no single pair >10% of capital
Advance_version/data_loader.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import yfinance as yf
3
+ import logging
4
+ from typing import List, Tuple
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ class DataLoader:
9
+ """
10
+ Fetches and preprocesses price (and volume) data for a given universe.
11
+ Supports daily and intraday via yfinance.
12
+ """
13
+
14
+ def __init__(self, tickers: List[str], start_date: str, end_date: str, interval: str = "1d"):
15
+ """
16
+ :param tickers: List of ticker strings.
17
+ :param start_date: "YYYY-MM-DD"
18
+ :param end_date: "YYYY-MM-DD"
19
+ :param interval: "1d", "5m", etc.
20
+ """
21
+ self.tickers = tickers
22
+ self.start_date = start_date
23
+ self.end_date = end_date
24
+ self.interval = interval
25
+
26
+ def fetch_data(self) -> Tuple[pd.DataFrame, pd.DataFrame]:
27
+ """
28
+ Downloads Adj Close and Volume for all tickers between start_date and end_date.
29
+ :return: Tuple (prices_df, volume_df). Both are DataFrames with datetime index.
30
+ """
31
+ logger.info(f"Fetching data for {len(self.tickers)} tickers from {self.start_date} to {self.end_date} at interval {self.interval}.")
32
+
33
+ raw = yf.download(
34
+ tickers=self.tickers,
35
+ start=self.start_date,
36
+ end=self.end_date,
37
+ interval=self.interval,
38
+ auto_adjust=True,
39
+ progress=False
40
+ )
41
+
42
+ if raw.empty:
43
+ logger.error("No data fetched. Please check your tickers and date range.")
44
+ raise ValueError("Empty pricing data.")
45
+
46
+ # yfinance returns a MultiIndex with (Attribute, Ticker)
47
+ # We extract 'Close' (adjusted) and 'Volume'.
48
+ if "Close" in raw and "Volume" in raw:
49
+ prices = raw["Close"].copy()
50
+ volume = raw["Volume"].copy()
51
+ else:
52
+ # For some intervals, yfinance may label adjusted close as 'Adj Close'
53
+ if "Adj Close" in raw and "Volume" in raw:
54
+ prices = raw["Adj Close"].copy()
55
+ volume = raw["Volume"].copy()
56
+ else:
57
+ logger.error("Unexpected data format from yfinance.")
58
+ raise ValueError("Unexpected data format.")
59
+
60
+ # Drop rows where any ticker is missing (to align)
61
+ combined = pd.concat([prices, volume], axis=1, keys=["price", "volume"])
62
+ combined = combined.dropna()
63
+ prices = combined["price"]
64
+ volume = combined["volume"]
65
+
66
+ # Ensure columns are sorted alphabetically for consistency
67
+ prices = prices.sort_index(axis=1)
68
+ volume = volume[prices.columns]
69
+
70
+ logger.info(f"Downloaded price data with shape {prices.shape}, volume data with shape {volume.shape}.")
71
+ return prices, volume
72
+
Advance_version/execution_engine.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import logging
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ class ExecutionEngine:
8
+ """
9
+ Models realistic slippage based on notional vs. ADV.
10
+ """
11
+
12
+ def __init__(self, slippage_coefficient: float):
13
+ """
14
+ :param slippage_coefficient: e.g., 0.0001 (1 bp per 0.1% ADV)
15
+ """
16
+ self.slip_coeff = slippage_coefficient
17
+
18
+ def compute_slippage(
19
+ self,
20
+ notional: pd.Series,
21
+ volume: pd.Series,
22
+ price: pd.Series
23
+ ) -> pd.Series:
24
+ """
25
+ Computes slippage cost = slip_coeff * (notional / (ADV * price)).
26
+ :param notional: Series of absolute dollar notional traded.
27
+ :param volume: Series of share volume (ADV proxy).
28
+ :param price: Series of price to convert volume to ADV notional.
29
+ :return: Series of slippage costs (as fraction of capital).
30
+ """
31
+ # ADV dollar volume
32
+ adv_dollar = volume * price
33
+ adv_dollar = adv_dollar.replace(0, np.nan).fillna(method="ffill").fillna(1e9)
34
+ slip = self.slip_coeff * (notional / adv_dollar)
35
+ return slip
Advance_version/kalman_hedge.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from pykalman import KalmanFilter
4
+ import logging
5
+ from typing import Tuple
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ class KalmanHedge:
10
+ """
11
+ Runs a Kalman filter with an intercept and time‐varying hedge ratio (beta).
12
+ Allows EM estimation of Q and R.
13
+ """
14
+
15
+ def __init__(
16
+ self,
17
+ observation_series: pd.Series,
18
+ control_series: pd.Series,
19
+ initial_state_cov: np.ndarray,
20
+ transition_cov: np.ndarray,
21
+ observation_cov: float,
22
+ em_iterations: int = 20
23
+ ):
24
+ """
25
+ :param observation_series: Y_t series (e.g., prices of ticker1).
26
+ :param control_series: X_t series (e.g., prices of ticker2).
27
+ :param initial_state_cov: 2×2 covariance for [alpha, beta].
28
+ :param transition_cov: 2×2 process noise for [alpha, beta].
29
+ :param observation_cov: scalar observation noise variance.
30
+ :param em_iterations: number of EM iterations to refine Q & R.
31
+ """
32
+ # 强制数据为float类型
33
+ self.y = observation_series.astype(float).values
34
+ self.x = control_series.astype(float).values
35
+ self.dates = observation_series.index
36
+ self.initial_state_cov = np.array(initial_state_cov, dtype=float)
37
+ self.transition_cov = np.array(transition_cov, dtype=float)
38
+ self.observation_cov = float(observation_cov)
39
+ self.em_iterations = em_iterations
40
+
41
+ # Prepare structures to store results
42
+ n_points = len(self.y)
43
+ self.alpha = np.zeros(n_points)
44
+ self.beta = np.zeros(n_points)
45
+ self.spread = np.zeros(n_points)
46
+ self.state_covariances = np.zeros((n_points, 2, 2))
47
+
48
+ # Build the KalmanFilter object
49
+ self._build_filter()
50
+
51
+ def _build_filter(self):
52
+ """
53
+ Initializes a KalmanFilter with a 2D state: [alpha_t, beta_t].
54
+ Observation: y_t = [1, x_t] ⋅ [alpha_t, beta_t] + ε_t
55
+ State Evolution: [alpha_t, beta_t] = [alpha_{t-1}, beta_{t-1}] + η_t
56
+ """
57
+ n_timesteps = len(self.y)
58
+ # Transition matrix: identity (random walk for alpha & beta)
59
+ transition_matrices = np.eye(2, dtype=float)
60
+
61
+ # Observation matrices: time-varying (每步都不同)
62
+ observation_matrices = np.zeros((n_timesteps, 1, 2), dtype=float)
63
+ for t in range(n_timesteps):
64
+ observation_matrices[t, 0, 0] = 1.0
65
+ observation_matrices[t, 0, 1] = self.x[t]
66
+
67
+ initial_state_mean = np.zeros(2, dtype=float)
68
+ initial_state_covariance = self.initial_state_cov
69
+
70
+ self.kf = KalmanFilter(
71
+ transition_matrices=transition_matrices,
72
+ observation_matrices=observation_matrices,
73
+ initial_state_mean=initial_state_mean,
74
+ initial_state_covariance=initial_state_covariance,
75
+ transition_covariance=self.transition_cov,
76
+ observation_covariance=self.observation_cov
77
+ )
78
+
79
+ # Run EM to refine Q & R
80
+ try:
81
+ self.kf = self.kf.em(
82
+ X=None,
83
+ n_iter=self.em_iterations,
84
+ em_vars=["transition_covariance", "observation_covariance"]
85
+ )
86
+ logger.info("Kalman EM converged: Q and R estimated.")
87
+ except Exception as e:
88
+ logger.warning(f"Kalman EM failed or was skipped: {e}")
89
+
90
+ def run_filter(self):
91
+ """
92
+ Kalman filter main loop (predict-update per time step).
93
+ At each step t:
94
+ 1. Predict next state, using transition_matrix。
95
+ 2. Compute spread_t = y_t - [alpha_{t|t-1} + beta_{t|t-1} * x_t]
96
+ 3. Update with observation y_t and correct observation_matrix.
97
+ """
98
+ n = len(self.y)
99
+ state_mean = np.zeros((n, 2), dtype=float)
100
+ state_cov = np.zeros((n, 2, 2), dtype=float)
101
+
102
+ state_mean[0] = self.kf.initial_state_mean
103
+ state_cov[0] = self.kf.initial_state_covariance
104
+
105
+ for t in range(1, n):
106
+ # 预测(仅给出本步观测矩阵!——很重要)
107
+ mean_pred, cov_pred = self.kf.filter_update(
108
+ filtered_state_mean=state_mean[t - 1],
109
+ filtered_state_covariance=state_cov[t - 1],
110
+ observation=None,
111
+ # 必须指定 observation_matrix,每步都要
112
+ observation_matrix=self.kf.observation_matrices[t]
113
+ )
114
+
115
+ # 用预测state计算spread
116
+ a_pred, b_pred = mean_pred
117
+ self.spread[t] = self.y[t] - (a_pred + b_pred * self.x[t])
118
+
119
+ # 更新
120
+ mean_filt, cov_filt = self.kf.filter_update(
121
+ filtered_state_mean=mean_pred,
122
+ filtered_state_covariance=cov_pred,
123
+ observation=self.y[t],
124
+ observation_matrix=self.kf.observation_matrices[t]
125
+ )
126
+ state_mean[t] = mean_filt
127
+ state_cov[t] = cov_filt
128
+ self.alpha[t] = mean_filt[0]
129
+ self.beta[t] = mean_filt[1]
130
+ self.state_covariances[t] = cov_filt
131
+
132
+ # 初始点
133
+ self.spread[0] = self.y[0] - (state_mean[0][0] + state_mean[0][1] * self.x[0])
134
+ self.alpha[0] = state_mean[0][0]
135
+ self.beta[0] = state_mean[0][1]
136
+ self.state_covariances[0] = state_cov[0]
137
+
138
+ result = pd.DataFrame({
139
+ "alpha": self.alpha,
140
+ "beta": self.beta,
141
+ "spread": self.spread
142
+ }, index=self.dates)
143
+ logger.info("Kalman filter run completed.")
144
+ return result
Advance_version/logger.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import sys
3
+
4
+ def setup_logger(name: str) -> logging.Logger:
5
+ """
6
+ Sets up a root logger with INFO level, console handler,
7
+ and a consistent formatting style.
8
+ """
9
+ logger = logging.getLogger(name)
10
+ logger.setLevel(logging.INFO)
11
+ if not logger.handlers:
12
+ ch = logging.StreamHandler(sys.stdout)
13
+ ch.setLevel(logging.INFO)
14
+ formatter = logging.Formatter(
15
+ "%(asctime)s | %(name)s | %(levelname)s | %(message)s",
16
+ datefmt="%Y-%m-%d %H:%M:%S"
17
+ )
18
+ ch.setFormatter(formatter)
19
+ logger.addHandler(ch)
20
+ return logger
Advance_version/pair_selector.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import itertools
4
+ import logging
5
+ from utils import cluster_universe, rolling_cointegration_test, half_life
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ class PairSelector:
10
+ """
11
+ From a universe of assets, cluster similar ones, then within each cluster
12
+ run rolling cointegration tests. For stable pairs, compute static hedge ratio
13
+ via OLS and half‐life of the spread.
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ prices: pd.DataFrame,
19
+ cluster_size: int = 20,
20
+ coint_pval_threshold: float = 0.05,
21
+ rolling_window: int = 252,
22
+ rolling_step: int = 63,
23
+ min_valid_periods: int = 2
24
+ ):
25
+ """
26
+ :param prices: DataFrame of asset prices (aligned), columns = tickers.
27
+ """
28
+ self.prices = prices
29
+ self.returns = prices.pct_change().dropna()
30
+ self.cluster_size = cluster_size
31
+ self.pval_threshold = coint_pval_threshold
32
+ self.rolling_window = rolling_window
33
+ self.rolling_step = rolling_step
34
+ self.min_valid_periods = min_valid_periods
35
+
36
+ def select_pairs(self) -> pd.DataFrame:
37
+ """
38
+ Returns a DataFrame with columns: [ticker1, ticker2, beta_ols, half_life_days].
39
+ Only includes pairs that pass the rolling cointegration test.
40
+ """
41
+ # 1) Cluster the universe
42
+ clusters = cluster_universe(self.returns, self.cluster_size)
43
+
44
+ selected = []
45
+ for cluster_id, tickers in clusters.items():
46
+ if len(tickers) < 2:
47
+ continue
48
+ logger.info(f"Testing cluster {cluster_id} with {len(tickers)} tickers.")
49
+ # For each unique pair in that cluster:
50
+ for t1, t2 in itertools.combinations(tickers, 2):
51
+ s1 = self.prices[t1]
52
+ s2 = self.prices[t2]
53
+ # 2) Rolling cointegration test
54
+ try:
55
+ is_coint = rolling_cointegration_test(
56
+ s1, s2,
57
+ window=self.rolling_window,
58
+ step=self.rolling_step,
59
+ pval_threshold=self.pval_threshold,
60
+ min_valid_periods=self.min_valid_periods
61
+ )
62
+ except Exception as e:
63
+ logger.warning(f"Cointegration test failed for {t1}-{t2}: {e}")
64
+ continue
65
+
66
+ if not is_coint:
67
+ continue
68
+
69
+ # 3) Compute static OLS hedge ratio on full period
70
+ # Solve s1 = alpha + beta*s2 + eps
71
+ X = np.vstack([np.ones(len(s2)), s2.values]).T
72
+ y = s1.values
73
+ ols_beta = np.linalg.lstsq(X, y, rcond=None)[0][1]
74
+
75
+ # 4) Compute half-life of spread
76
+ spread = s1 - ols_beta * s2
77
+ hl = half_life(spread)
78
+
79
+ # 5) Save if half-life is finite and reasonable (< window)
80
+ if np.isfinite(hl) and hl > 0 and hl < self.rolling_window:
81
+ selected.append({
82
+ "ticker1": t1,
83
+ "ticker2": t2,
84
+ "beta_ols": ols_beta,
85
+ "half_life": hl
86
+ })
87
+ logger.info(f"Selected pair {t1}-{t2}: beta={ols_beta:.4f}, half-life={hl:.1f} days.")
88
+ if not selected:
89
+ logger.warning("No cointegrated pairs found in the universe.")
90
+ return pd.DataFrame(columns=["ticker1", "ticker2", "beta_ols", "half_life"])
91
+ return pd.DataFrame(selected)
Advance_version/portfolio_optimizer.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import cvxpy as cp
4
+ import logging
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ class PortfolioOptimizer:
9
+ """
10
+ Given a DataFrame of pair‐level returns (columns = pair names, rows = dates),
11
+ solves a minimum‐variance allocation (or any convex objective).
12
+ """
13
+
14
+ def __init__(
15
+ self,
16
+ pair_returns: pd.DataFrame,
17
+ min_weight: float = 0.0,
18
+ max_weight: float = 0.1
19
+ ):
20
+ """
21
+ :param pair_returns: DataFrame (T×N) of returns for N pairs.
22
+ :param min_weight: lower bound for each weight.
23
+ :param max_weight: upper bound for each weight.
24
+ """
25
+ self.returns = pair_returns.dropna(how="all")
26
+ self.N = self.returns.shape[1]
27
+ self.min_w = min_weight
28
+ self.max_w = max_weight
29
+
30
+ def min_variance(self) -> pd.Series:
31
+ """
32
+ Solve: minimize wᵀ Σ w subject to ∑w = 1, and min_w ≤ w_i ≤ max_w.
33
+ Returns a Series of weights indexed by pair names.
34
+ """
35
+ cov = self.returns.cov().values
36
+ cov += np.eye(self.N) * 1e-6
37
+
38
+ w = cp.Variable(self.N)
39
+ objective = cp.Minimize(cp.quad_form(w, cov))
40
+ constraints = [
41
+ cp.sum(w) == 1,
42
+ w >= self.min_w,
43
+ w <= self.max_w
44
+ ]
45
+ prob = cp.Problem(objective, constraints)
46
+ prob.solve(solver=cp.OSQP, verbose=False)
47
+
48
+ if w.value is None:
49
+ logger.error("Portfolio optimization failed.")
50
+ # Fallback: equal weights
51
+ w_opt = np.ones(self.N) / self.N
52
+ else:
53
+ w_opt = w.value
54
+
55
+ weights = pd.Series(w_opt, index=self.returns.columns)
56
+ logger.info(f"Min‐variance weights computed: {weights.to_dict()}")
57
+ return weights
Advance_version/risk_engine.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import logging
4
+ from scipy.stats import norm
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ class RiskEngine:
9
+ """
10
+ Computes risk metrics for a strategy or portfolio of pair returns.
11
+ Includes VaR (historical and parametric), max drawdown, and
12
+ placeholder for factor neutrality/regression.
13
+ """
14
+
15
+ def __init__(self, returns: pd.Series, config: dict):
16
+ """
17
+ :param returns: Series of daily strategy returns.
18
+ :param config: dict under key 'risk' from config.yaml.
19
+ """
20
+ self.returns = returns.dropna()
21
+ self.daily_var_window = config["daily_var_window"]
22
+ self.var_conf = config["var_confidence"]
23
+ self.max_dd_limit = config["max_drawdown_limit"]
24
+
25
+ def historical_var(self) -> float:
26
+ """
27
+ Historical VaR at confidence level.
28
+ """
29
+ window = min(self.daily_var_window, len(self.returns))
30
+ hist = self.returns.tail(window)
31
+ var_h = np.percentile(hist, (1 - self.var_conf) * 100)
32
+ logger.info(f"Historical VaR (window={window}, conf={self.var_conf}) = {var_h:.4%}")
33
+ return var_h
34
+
35
+ def parametric_var(self) -> float:
36
+ """
37
+ Parametric VaR assuming normality.
38
+ """
39
+ mean = self.returns.mean()
40
+ std = self.returns.std()
41
+ var_p = mean + std * norm.ppf(1 - self.var_conf)
42
+ logger.info(f"Parametric VaR (conf={self.var_conf}) = {var_p:.4%}")
43
+ return var_p
44
+
45
+ def max_drawdown(self) -> float:
46
+ """
47
+ Compute maximum drawdown.
48
+ """
49
+ cum = (1 + self.returns).cumprod()
50
+ peak = cum.cummax()
51
+ drawdown = (cum - peak) / peak
52
+ max_dd = drawdown.min()
53
+ logger.info(f"Maximum drawdown = {max_dd:.4%}")
54
+ return max_dd
55
+
56
+ def check_hard_limits(self) -> dict:
57
+ """
58
+ Checks if current drawdown or VaR breaches the configured limits.
59
+ """
60
+ dd = self.max_drawdown()
61
+ var_h = self.historical_var()
62
+ alerts = {}
63
+ if abs(dd) > self.max_dd_limit:
64
+ alerts["drawdown_breach"] = dd
65
+ if var_h < -self.max_dd_limit:
66
+ alerts["var_breach"] = var_h
67
+ return alerts
68
+
69
+ def stress_test_returns(self, stress_scenario: pd.Series) -> float:
70
+ """
71
+ Given a stress scenario of returns (Series aligned by date or simply
72
+ a vector of % shocks), compute expected P&L under that stress.
73
+ For simplicity, sum elementwise product with strategy exposure = 1.
74
+ """
75
+ # This is a placeholder: user should supply a scenario vector.
76
+ pnl = (self.returns * stress_scenario).sum()
77
+ logger.info(f"Stress test scenario P&L = {pnl:.4f}")
78
+ return pnl
79
+
80
+ def factor_neutrality(self, factor_returns: pd.DataFrame) -> dict:
81
+ """
82
+ Regress strategy returns on supplied factor returns to compute
83
+ betas and R². Returns a dict of factor exposures.
84
+ """
85
+ import statsmodels.api as sm
86
+
87
+ X = sm.add_constant(factor_returns.loc[self.returns.index])
88
+ y = self.returns
89
+ model = sm.OLS(y, X).fit()
90
+ exposures = model.params.to_dict()
91
+ r2 = model.rsquared
92
+ logger.info(f"Factor regression R² = {r2:.4f}, exposures = {exposures}")
93
+ return {"exposures": exposures, "r2": r2}
Advance_version/run_backtest.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yaml
2
+ import os
3
+ import logging
4
+ import pandas as pd
5
+ from logger import setup_logger
6
+
7
+ # Import modules
8
+ from data_loader import DataLoader
9
+ from pair_selector import PairSelector
10
+ from kalman_hedge import KalmanHedge
11
+ from signal_generator import SignalGenerator
12
+ from backtester import Backtester
13
+ from risk_engine import RiskEngine
14
+ from portfolio_optimizer import PortfolioOptimizer
15
+
16
+ # Set up root logger
17
+ logger = setup_logger("PairTradingStrategy")
18
+
19
+ def load_config(path: str) -> dict:
20
+ with open(path, "r") as f:
21
+ cfg = yaml.safe_load(f)
22
+ return cfg
23
+
24
+ def calc_portfolio_metrics(returns):
25
+ returns = returns.fillna(0)
26
+ ann_return = (1 + returns).prod() ** (252 / len(returns)) - 1
27
+ ann_vol = returns.std() * (252 ** 0.5)
28
+ sharpe = ann_return / ann_vol if ann_vol != 0 else float("nan")
29
+ cum = (1 + returns).cumprod()
30
+ peak = cum.cummax()
31
+ drawdown = (cum - peak) / peak
32
+ max_dd = drawdown.min()
33
+ return {
34
+ "annual_return": ann_return,
35
+ "annual_vol": ann_vol,
36
+ "sharpe": sharpe,
37
+ "max_drawdown": max_dd,
38
+ }
39
+
40
+ def main():
41
+ # 1) Load configuration
42
+ config_path = os.path.join(os.path.dirname(__file__), "../config.yaml")
43
+ cfg = load_config(config_path)
44
+ logger.info("Configuration loaded.")
45
+
46
+ # 2) Fetch data
47
+ data_cfg = cfg["data"]
48
+ dl = DataLoader(
49
+ tickers=data_cfg["tickers"],
50
+ start_date=data_cfg["start_date"],
51
+ end_date=data_cfg["end_date"],
52
+ interval=data_cfg["interval"]
53
+ )
54
+ prices, volume = dl.fetch_data()
55
+
56
+ # 3) Select pairs
57
+ ps_cfg = cfg["pair_selector"]
58
+ pair_selector = PairSelector(
59
+ prices=prices,
60
+ cluster_size=ps_cfg["cluster_size"],
61
+ coint_pval_threshold=ps_cfg["coint_pval_threshold"],
62
+ rolling_window=ps_cfg["rolling_window"],
63
+ rolling_step=ps_cfg["rolling_step"],
64
+ min_valid_periods=ps_cfg["min_valid_periods"]
65
+ )
66
+ pairs_df = pair_selector.select_pairs()
67
+ if pairs_df.empty:
68
+ logger.error("No suitable pairs found. Exiting.")
69
+ return
70
+ logger.info(f"Number of selected pairs: {len(pairs_df)}")
71
+
72
+ # 4) For each selected pair, run Kalman hedge, generate signals, backtest
73
+ all_pair_returns = {}
74
+ results_summary = []
75
+ for idx, row in pairs_df.iterrows():
76
+ t1 = row["ticker1"]
77
+ t2 = row["ticker2"]
78
+ logger.info(f"Processing pair {t1}-{t2}.")
79
+
80
+ s1 = prices[t1]
81
+ s2 = prices[t2]
82
+
83
+ # 4a) Kalman hedge
84
+ km_cfg = cfg["kalman"]
85
+ kh = KalmanHedge(
86
+ observation_series=s1,
87
+ control_series=s2,
88
+ initial_state_cov=km_cfg["initial_state_cov"],
89
+ transition_cov=km_cfg["transition_cov"],
90
+ observation_cov=km_cfg["observation_cov"],
91
+ em_iterations=km_cfg["em_iterations"]
92
+ )
93
+ kalman_df = kh.run_filter()
94
+
95
+ # 4b) Signal generation
96
+ sig_cfg = cfg["signal"]
97
+ sg = SignalGenerator(
98
+ price1=s1,
99
+ price2=s2,
100
+ kalman_df=kalman_df,
101
+ config=sig_cfg
102
+ )
103
+ trade_df = sg.generate(costs=cfg["costs"], volume=volume[[t1, t2]])
104
+
105
+ # 4c) Backtest
106
+ bt = Backtester(
107
+ trade_df=trade_df,
108
+ costs=cfg["costs"],
109
+ volume=volume[[t1, t2]],
110
+ ticker1=t1,
111
+ ticker2=t2,
112
+ )
113
+ bt_results = bt.run()
114
+ metrics = bt.performance_metrics(bt_results)
115
+ logger.info(f"Pair {t1}-{t2} metrics: {metrics}")
116
+
117
+ # Store returns series for portfolio optimization
118
+ all_pair_returns[f"{t1}/{t2}"] = bt_results["strategy_return"]
119
+
120
+ # Summarize
121
+ results_summary.append({
122
+ "pair": f"{t1}/{t2}",
123
+ **metrics,
124
+ "half_life": row["half_life"]
125
+ })
126
+
127
+ # 5) Aggregate pair returns into DataFrame
128
+ pair_returns_df = (
129
+ pd.DataFrame(all_pair_returns)
130
+ .dropna(how="all")
131
+ )
132
+
133
+ # 6) Save pair_summary.csv
134
+ summary_df = pd.DataFrame(results_summary)
135
+ output_dir = os.path.join(os.path.dirname(__file__), "../output")
136
+ os.makedirs(output_dir, exist_ok=True)
137
+ summary_path = os.path.join(output_dir, "pair_summary.csv")
138
+ summary_df.to_csv(summary_path, index=False)
139
+ logger.info(f"Saved pair summary to {summary_path}.")
140
+
141
+ # ====== 选取 Sharpe > 0 的配对 ======
142
+ selected_pairs = summary_df[summary_df["sharpe"] > 0]["pair"].tolist()
143
+ if not selected_pairs:
144
+ logger.warning("No pairs with Sharpe > 0 were found. Portfolio will not be constructed.")
145
+ return
146
+ pair_returns_df_selected = pair_returns_df[selected_pairs]
147
+ logger.info(f"Selected pairs with Sharpe > 0: {selected_pairs}")
148
+
149
+ # 7) Portfolio optimization只用Sharpe>0的pair
150
+ port_cfg = cfg["portfolio"]
151
+ po = PortfolioOptimizer(
152
+ pair_returns=pair_returns_df_selected,
153
+ min_weight=port_cfg["min_weight"],
154
+ max_weight=port_cfg["max_weight"]
155
+ )
156
+ weights = po.min_variance()
157
+
158
+ # 8) Compute portfolio P&L
159
+ portfolio_ret = (pair_returns_df_selected * weights).sum(axis=1)
160
+ re = RiskEngine(returns=portfolio_ret, config=cfg["risk"])
161
+ var_h = re.historical_var()
162
+ var_p = re.parametric_var()
163
+ max_dd = re.max_drawdown()
164
+ logger.info(f"Portfolio VaR (hist) = {var_h:.4%}, (param) = {var_p:.4%}, max DD = {max_dd:.4%}")
165
+
166
+ # 9) 计算并输出整体组合绩效
167
+ portfolio_metrics = calc_portfolio_metrics(portfolio_ret)
168
+ logger.info(
169
+ f"Portfolio annual_return={portfolio_metrics['annual_return']:.4%}, "
170
+ f"annual_vol={portfolio_metrics['annual_vol']:.4%}, "
171
+ f"sharpe={portfolio_metrics['sharpe']:.2f}, "
172
+ f"max_drawdown={portfolio_metrics['max_drawdown']:.2%}"
173
+ )
174
+
175
+ # 10) 保存 portfolio_weights.csv 和 portfolio_metrics.csv
176
+ weights_path = os.path.join(output_dir, "portfolio_weights.csv")
177
+ weights.to_csv(weights_path, header=True)
178
+ logger.info(f"Saved portfolio weights to {weights_path}.")
179
+
180
+ pd.DataFrame([portfolio_metrics]).to_csv(
181
+ os.path.join(output_dir, "portfolio_metrics.csv"),
182
+ index=False
183
+ )
184
+ logger.info(f"Saved portfolio metrics to {os.path.join(output_dir, 'portfolio_metrics.csv')}.")
185
+
186
+ logger.info("Backtest pipeline completed successfully.")
187
+
188
+ if __name__ == "__main__":
189
+ main()
Advance_version/scripts/run_backtest.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yaml
2
+ import os
3
+ import logging
4
+ from logger import setup_logger
5
+
6
+ # Import modules
7
+ from data_loader import DataLoader
8
+ from pair_selector import PairSelector
9
+ from kalman_hedge import KalmanHedge
10
+ from signal_generator import SignalGenerator
11
+ from backtester import Backtester
12
+ from risk_engine import RiskEngine
13
+ from portfolio_optimizer import PortfolioOptimizer
14
+
15
+ # Set up root logger
16
+ logger = setup_logger("PairTradingStrategy")
17
+
18
+ def load_config(path: str) -> dict:
19
+ with open(path, "r") as f:
20
+ cfg = yaml.safe_load(f)
21
+ return cfg
22
+
23
+ def main():
24
+ # 1) Load configuration
25
+ config_path = os.path.join(os.path.dirname(__file__), "../config.yaml")
26
+ cfg = load_config(config_path)
27
+ logger.info("Configuration loaded.")
28
+
29
+ # 2) Fetch data
30
+ data_cfg = cfg["data"]
31
+ dl = DataLoader(
32
+ tickers=data_cfg["tickers"],
33
+ start_date=data_cfg["start_date"],
34
+ end_date=data_cfg["end_date"],
35
+ interval=data_cfg["interval"]
36
+ )
37
+ prices, volume = dl.fetch_data()
38
+
39
+ # 3) Select pairs
40
+ ps_cfg = cfg["pair_selector"]
41
+ pair_selector = PairSelector(
42
+ prices=prices,
43
+ cluster_size=ps_cfg["cluster_size"],
44
+ coint_pval_threshold=ps_cfg["coint_pval_threshold"],
45
+ rolling_window=ps_cfg["rolling_window"],
46
+ rolling_step=ps_cfg["rolling_step"],
47
+ min_valid_periods=ps_cfg["min_valid_periods"]
48
+ )
49
+ pairs_df = pair_selector.select_pairs()
50
+ if pairs_df.empty:
51
+ logger.error("No suitable pairs found. Exiting.")
52
+ return
53
+ logger.info(f"Number of selected pairs: {len(pairs_df)}")
54
+
55
+ # 4) For each selected pair, run Kalman hedge, generate signals, backtest
56
+ all_pair_returns = {}
57
+ results_summary = []
58
+ for idx, row in pairs_df.iterrows():
59
+ t1 = row["ticker1"]
60
+ t2 = row["ticker2"]
61
+ logger.info(f"Processing pair {t1}-{t2}.")
62
+
63
+ s1 = prices[t1]
64
+ s2 = prices[t2]
65
+
66
+ # 4a) Kalman hedge
67
+ km_cfg = cfg["kalman"]
68
+ kh = KalmanHedge(
69
+ observation_series=s1,
70
+ control_series=s2,
71
+ initial_state_cov=km_cfg["initial_state_cov"],
72
+ transition_cov=km_cfg["transition_cov"],
73
+ observation_cov=km_cfg["observation_cov"],
74
+ em_iterations=km_cfg["em_iterations"]
75
+ )
76
+ kalman_df = kh.run_filter()
77
+
78
+ # 4b) Signal generation
79
+ sig_cfg = cfg["signal"]
80
+ sg = SignalGenerator(
81
+ price1=s1,
82
+ price2=s2,
83
+ kalman_df=kalman_df,
84
+ config=sig_cfg
85
+ )
86
+ trade_df = sg.generate(costs=cfg["costs"], volume=volume[[t1, t2]])
87
+
88
+ # 4c) Backtest
89
+ bt = Backtester(
90
+ trade_df=trade_df.rename(columns={"pos1": t1 + "_pos", "pos2": t2 + "_pos",
91
+ "price1": t1 + "_price", "price2": t2 + "_price"}),
92
+ costs=cfg["costs"],
93
+ volume=volume[[t1, t2]].rename(columns={t1: t1 + "_vol", t2: t2 + "_vol"})
94
+ )
95
+ bt_results = bt.run()
96
+ metrics = bt.performance_metrics(bt_results)
97
+ logger.info(f"Pair {t1}-{t2} metrics: {metrics}")
98
+
99
+ # Store returns series for portfolio optimization
100
+ all_pair_returns[f"{t1}/{t2}"] = bt_results["strategy_return"]
101
+
102
+ # Summarize
103
+ results_summary.append({
104
+ "pair": f"{t1}/{t2}",
105
+ **metrics,
106
+ "half_life": row["half_life"]
107
+ })
108
+
109
+ # 5) Aggregate pair returns into DataFrame
110
+ pair_returns_df = (
111
+ pd.DataFrame(all_pair_returns)
112
+ .dropna(how="all")
113
+ )
114
+
115
+ # 6) Portfolio optimization
116
+ port_cfg = cfg["portfolio"]
117
+ po = PortfolioOptimizer(
118
+ pair_returns=pair_returns_df,
119
+ min_weight=port_cfg["min_weight"],
120
+ max_weight=port_cfg["max_weight"]
121
+ )
122
+ weights = po.min_variance()
123
+
124
+ # 7) Compute portfolio P&L
125
+ portfolio_ret = (pair_returns_df * weights).sum(axis=1)
126
+ re = RiskEngine(returns=portfolio_ret, config=cfg["risk"])
127
+ var_h = re.historical_var()
128
+ var_p = re.parametric_var()
129
+ max_dd = re.max_drawdown()
130
+ logger.info(f"Portfolio VaR (hist) = {var_h:.4%}, (param) = {var_p:.4%}, max DD = {max_dd:.4%}")
131
+
132
+ # 8) Save summary to CSV
133
+ summary_df = pd.DataFrame(results_summary)
134
+ output_dir = os.path.join(os.path.dirname(__file__), "../output")
135
+ os.makedirs(output_dir, exist_ok=True)
136
+ summary_path = os.path.join(output_dir, "pair_summary.csv")
137
+ summary_df.to_csv(summary_path, index=False)
138
+ logger.info(f"Saved pair summary to {summary_path}.")
139
+
140
+ weights_path = os.path.join(output_dir, "portfolio_weights.csv")
141
+ weights.to_csv(weights_path, header=True)
142
+ logger.info(f"Saved portfolio weights to {weights_path}.")
143
+
144
+ logger.info("Backtest pipeline completed successfully.")
145
+
146
+ if __name__ == "__main__":
147
+ main()
Advance_version/signal_generator.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import logging
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ class SignalGenerator:
8
+ """
9
+ Given spread & dynamic betas, computes z-scores, applies adaptive thresholds,
10
+ volatility & momentum filters, and outputs daily position signals (signed, float).
11
+ """
12
+
13
+ def __init__(
14
+ self,
15
+ price1: pd.Series,
16
+ price2: pd.Series,
17
+ kalman_df: pd.DataFrame,
18
+ config: dict
19
+ ):
20
+ """
21
+ :param price1: Series of prices for ticker1.
22
+ :param price2: Series of prices for ticker2.
23
+ :param kalman_df: DataFrame with columns ['alpha', 'beta', 'spread'] indexed by date.
24
+ :param config: dictionary under key 'signal' from config.yaml.
25
+ """
26
+ self.price1 = price1
27
+ self.price2 = price2
28
+ self.alpha = kalman_df["alpha"]
29
+ self.beta = kalman_df["beta"]
30
+ self.spread = kalman_df["spread"]
31
+ self.dates = kalman_df.index
32
+ self.z_window = config["zscore_window"]
33
+ self.entry_z = config["entry_z"]
34
+ self.exit_z = config["exit_z"]
35
+ self.target_vol = config["target_vol"]
36
+ self.min_vol_pct = config["min_vol_percentile"]
37
+ self.momentum_filter = config["momentum_filter"]
38
+
39
+ # Placeholder for signals & positions
40
+ self.zscore = None
41
+ self.entry_thresh = None
42
+ self.exit_thresh = None
43
+ self.positions = None # will store a DataFrame with columns ['pos1', 'pos2']
44
+
45
+ def generate(self, costs: dict, volume: pd.DataFrame) -> pd.DataFrame:
46
+ """
47
+ 1. Compute rolling z-score of spread.
48
+ 2. Compute dynamic entry/exit thresholds (scaled by rolling vol).
49
+ 3. Apply volatility & momentum filters.
50
+ 4. Compute volatility‐normalized position sizing:
51
+ pos1 = +1 (long) or -1 (short) * (target_vol / spread_vol)
52
+ pos2 = -beta * pos1
53
+ 5. Return DataFrame with columns ['pos1', 'pos2'], indexed by date.
54
+ """
55
+ n = len(self.spread)
56
+ df = pd.DataFrame(index=self.dates)
57
+ # 1) Rolling mean & std of spread
58
+ rolling_mean = self.spread.rolling(self.z_window).mean()
59
+ rolling_std = self.spread.rolling(self.z_window).std()
60
+ self.zscore = (self.spread - rolling_mean) / rolling_std
61
+ df["zscore"] = self.zscore
62
+
63
+ # 2) Dynamic thresholds
64
+ self.entry_thresh = self.entry_z * rolling_std
65
+ self.exit_thresh = self.exit_z * rolling_std
66
+ df["entry_thresh"] = self.entry_thresh
67
+ df["exit_thresh"] = self.exit_thresh
68
+
69
+ # 3) Volatility filter: compute rolling volatility percentile rank
70
+ vol_rank = rolling_std.rank(pct=True) * 100
71
+ df["vol_rank"] = vol_rank
72
+
73
+ # 4) Momentum filter: Δspread
74
+ dspread = self.spread.diff()
75
+ df["dspread"] = dspread
76
+
77
+ # 5) Initialize positions
78
+ pos1 = np.zeros(n)
79
+ pos2 = np.zeros(n)
80
+ current_signal = 0 # +1 for long spread (long price1, short price2), -1 for short
81
+
82
+ for t in range(1, n):
83
+ # Check if volatility below threshold
84
+ if vol_rank.iloc[t] > self.min_vol_pct:
85
+ # Too volatile or not enough data
86
+ current_signal = 0
87
+ else:
88
+ z = self.zscore.iloc[t]
89
+ # Check existing position
90
+ if current_signal == 0:
91
+ # Look for entry
92
+ if z > self.entry_thresh.iloc[t]:
93
+ # Spread is high → short spread (sell price1, buy price2)
94
+ # Momentum filter: require Δspread < 0 (i.e., spread rolling down)
95
+ if not self.momentum_filter or dspread.iloc[t] < 0:
96
+ current_signal = -1
97
+ elif z < -self.entry_thresh.iloc[t]:
98
+ # Spread is low → long spread (buy price1, sell price2)
99
+ if not self.momentum_filter or dspread.iloc[t] > 0:
100
+ current_signal = +1
101
+ elif current_signal == +1:
102
+ # Already long spread; check exit when z ≥ -exit_thresh (close)
103
+ if z >= -self.exit_thresh.iloc[t]:
104
+ current_signal = 0
105
+ elif current_signal == -1:
106
+ # Already short spread; check exit when z ≤ exit_thresh (close)
107
+ if z <= self.exit_thresh.iloc[t]:
108
+ current_signal = 0
109
+
110
+ # 6) Position sizing based on volatility normalization
111
+ if current_signal != 0 and rolling_std.iloc[t] > 0:
112
+ # Dollar‐volatility of spread per unit of price1 = rolling_std / price1
113
+ # But simpler: scale pos1 so that spread vol = target_vol
114
+ scale = self.target_vol / rolling_std.iloc[t]
115
+ pos1[t] = current_signal * scale
116
+ pos2[t] = -current_signal * scale * self.beta.iloc[t]
117
+ else:
118
+ pos1[t] = 0.0
119
+ pos2[t] = 0.0
120
+
121
+ df["pos1"] = pos1
122
+ df["pos2"] = pos2
123
+
124
+ # Attach price series for later P&L calculations
125
+ df["price1"] = self.price1
126
+ df["price2"] = self.price2
127
+
128
+ logger.info("Signals generated.")
129
+ return df
Advance_version/utils.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from sklearn.cluster import AgglomerativeClustering
4
+ from statsmodels.tsa.stattools import coint
5
+ import logging
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ def half_life(spread: pd.Series) -> float:
10
+ """
11
+ Estimate the half-life of mean reversion for a spread series S_t
12
+ by fitting: ΔS_t = a + kappa * S_{t-1} + ε_t.
13
+ Returns: hl = -ln(2) / kappa.
14
+ """
15
+ spread_lag = spread.shift(1).dropna()
16
+ spread_ret = (spread - spread_lag).dropna()
17
+ spread_lag = spread_lag.loc[spread_ret.index]
18
+
19
+ # Add constant
20
+ X = np.vstack([np.ones(len(spread_lag)), spread_lag.values]).T
21
+ y = spread_ret.values
22
+
23
+ # OLS regression
24
+ beta = np.linalg.lstsq(X, y, rcond=None)[0]
25
+ kappa = beta[1]
26
+ if kappa >= 0:
27
+ return np.inf
28
+ hl = -np.log(2) / kappa
29
+ return hl
30
+
31
+
32
+ def zscore(series: pd.Series) -> pd.Series:
33
+ """
34
+ Compute z-score based on rolling mean/std.
35
+ Assumes 'series' has no NaN for window-sized segments.
36
+ """
37
+ mean = series.rolling(series.name + "_mean").mean() # placeholder
38
+ # But we prefer to pass rolling window explicitly, so this may not be used directly.
39
+
40
+
41
+ def compute_zscore(spread: pd.Series, window: int) -> pd.Series:
42
+ """
43
+ Compute rolling z-score over 'window' periods.
44
+ """
45
+ m = spread.rolling(window).mean()
46
+ s = spread.rolling(window).std()
47
+ return (spread - m) / s
48
+
49
+
50
+ def cluster_universe(returns: pd.DataFrame, cluster_size: int) -> dict:
51
+ """
52
+ Perform hierarchical agglomerative clustering on returns to group assets
53
+ into clusters of approximate size 'cluster_size'. Returns a dict mapping
54
+ cluster_label -> list of tickers.
55
+ """
56
+ n_assets = returns.shape[1]
57
+ # Compute pairwise distance as 1 - correlation
58
+ corr = returns.corr().fillna(0)
59
+ dist = 1 - corr.abs()
60
+ # Convert to condensed form for clustering if needed, but sklearn Agglomerative supports precomputed.
61
+ n_clusters = max(1, n_assets // cluster_size)
62
+ model = AgglomerativeClustering(
63
+ n_clusters=n_clusters, linkage="average", metric="precomputed"
64
+ )
65
+ labels = model.fit_predict(dist.values)
66
+ clusters = {}
67
+ tickers = returns.columns.tolist()
68
+ for i, lab in enumerate(labels):
69
+ clusters.setdefault(lab, []).append(tickers[i])
70
+ logger.info(f"Formed {n_clusters} clusters.")
71
+ return clusters
72
+
73
+
74
+ def rolling_cointegration_test(
75
+ series1: pd.Series,
76
+ series2: pd.Series,
77
+ window: int,
78
+ step: int,
79
+ pval_threshold: float,
80
+ min_valid_periods: int
81
+ ) -> bool:
82
+ """
83
+ Run rolling Engle‐Granger cointegration tests over consecutive windows.
84
+ Return True if at least 'min_valid_periods' consecutive windows have pval < threshold.
85
+ """
86
+ n = len(series1)
87
+ valid = 0
88
+ for start in range(0, n - window + 1, step):
89
+ seg1 = series1.iloc[start : start + window]
90
+ seg2 = series2.iloc[start : start + window]
91
+ score, pval, _ = coint(seg1, seg2)
92
+ if pval < pval_threshold:
93
+ valid += 1
94
+ if valid >= min_valid_periods:
95
+ return True
96
+ else:
97
+ valid = 0
98
+ return False
output/pair_summary.csv ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pair,annual_return,annual_vol,sharpe,max_drawdown,half_life
2
+ 005810.KS/3N4.SG,0.0,0.0,,0.0,69.89134265705191
3
+ 005810.KS/9CM0.F,0.0,0.0,,0.0,41.83425338360788
4
+ 005810.KS/ARREF,0.0,0.0,,0.0,32.13116349951154
5
+ 005810.KS/BHAGYANGR.NS,0.0,0.0,,0.0,74.93174990279714
6
+ 005810.KS/CUBEXTUB.NS,0.0,0.0,,0.0,78.616169063629
7
+ 005810.KS/FDY.TO,0.0,0.0,,0.0,37.934485267520856
8
+ 005810.KS/GRX.L,0.0,0.0,,0.0,63.274106994412925
9
+ 005810.KS/HINDCOPPER.NS,0.0,0.0,,0.0,85.08157376122398
10
+ 005810.KS/JIX.F,0.0,0.0,,0.0,51.60848998374307
11
+ 005810.KS/MTJ3.F,0.0,0.0,,0.0,41.559572435658886
12
+ 005810.KS/OUW0.F,0.0,0.0,,0.0,69.49905471320476
13
+ 2009.TW/9CM0.F,0.0015379683024434598,0.013866530810193085,0.11091226230232884,-0.021404924568302307,36.45085847767775
14
+ 2009.TW/ATYM.L,2.2086948121335936e-05,0.0002737536008921058,0.08068185422715606,-0.000924767795943129,33.14600025115992
15
+ 2009.TW/CUBEXTUB.NS,0.00016970114358705324,0.0003105846147590616,0.5463926270742683,-0.0006140813909702956,111.29149639797315
16
+ 2009.TW/MTJ3.F,-0.0009624965054081391,0.003769537532899947,-0.2553354349194342,-0.012749500002018684,117.8922602920659
17
+ 2009.TW/OUW0.F,0.008679668544795627,0.00807960775157276,1.0742685550676716,-0.01643492715817114,39.72993107682057
18
+ 2009.TW/RE8.F,0.0014093521632039252,0.007366838829065429,0.1913103022755716,-0.01505594784051718,94.74302958043734
19
+ 2009.TW/SFR.AX,0.000104417903831866,0.0009819877561163303,0.10633320342488693,-0.0012578764214811159,120.1390203977421
20
+ 3N4.SG/9CM0.F,2.8987950810066963,71.85231668778763,0.040343794252348575,-154.10616875700134,242.65941495753827
21
+ 3N4.SG/ARREF,0.2995852352905628,6.0534022666034355,0.049490389387034754,-0.7519215927748252,103.56924279210467
22
+ 3N4.SG/RE8.F,1.4069783664689646,29.229876467895537,0.0481349405637862,-58.34256154333586,70.2851958509006
23
+ 9CM0.F/ARREF,0.020923271238472596,0.09319695228763693,0.22450595995775047,-0.08714316707490799,18.936737605822337
24
+ 9CM0.F/ATYM.L,-0.007306943916109754,0.04824493966184529,-0.15145513637958763,-0.1349914136257513,15.799100864512194
25
+ 9CM0.F/BHAGYANGR.NS,0.0660025567021083,0.07181790076192135,0.9190265379784478,-0.11963854656971595,49.013472541787415
26
+ 9CM0.F/CUBEXTUB.NS,0.08416347778181765,0.07927215497488543,1.061702912056344,-0.04684297884964142,63.98739503536009
27
+ 9CM0.F/FDY.TO,0.04251903531427881,0.08612845163691686,0.49367003012572513,-0.05936287611549328,1.6622221263419488
28
+ 9CM0.F/HINDCOPPER.NS,0.00884256658845528,0.04893411161646993,0.18070352758747346,-0.1329083093955279,59.27821905145623
29
+ 9CM0.F/JIX.F,0.046107376456388405,0.09382954568836062,0.49139507303516594,-0.07141317069741386,72.83614052376302
30
+ 9CM0.F/MTJ3.F,0.033289223403817125,0.09226784423892787,0.360789001611597,-0.07141298265884881,47.8306364618964
31
+ 9CM0.F/PUCOBRE.SN,0.051261099430377266,0.05680058376299433,0.9024748696997363,-0.04894630374447549,28.099354514019833
32
+ 9CM0.F/RE8.F,0.02900050584965297,0.09399063418967529,0.30854676212875926,-0.07939818590197838,28.675231823192284
33
+ ARREF/ATYM.L,0.0037633568393642403,0.028708754219775777,0.1310874310516715,-0.05008849350184719,20.286772076201153
34
+ ARREF/CUBEXTUB.NS,0.0024948307834449235,0.022787597062696785,0.10948195970732486,-0.06250663175970615,64.37950748503815
35
+ ARREF/FDY.TO,-0.021233110164099234,0.02314828699304472,-0.9172648572431761,-0.12805478466341516,20.53548141479908
36
+ ARREF/OUW0.F,-0.015477774449879966,0.023435157478104332,-0.6604510536931951,-0.09505692175817171,28.231379537957697
37
+ ARREF/RE8.F,-0.0035045189420866985,0.025326914883228396,-0.13837133177272246,-0.06557218853931879,5.999667008278748
38
+ ARREF/SFR.AX,-0.022230191649560083,0.03523261016328443,-0.6309550029513837,-0.1409957452957015,45.14644359217902
39
+ ATYM.L/CS.TO,0.0,0.0,,0.0,33.516715432823155
40
+ ATYM.L/FDY.TO,0.0,0.0,,0.0,17.69026387464004
41
+ ATYM.L/GRX.L,0.0,0.0,,0.0,105.10435295463033
42
+ ATYM.L/JIX.F,0.0,0.0,,0.0,73.59510974256123
43
+ ATYM.L/OUW0.F,0.0,0.0,,0.0,25.977190637745423
44
+ ATYM.L/RE8.F,0.0,0.0,,0.0,29.44341876789875
45
+ ATYM.L/SFR.AX,0.0,0.0,,0.0,62.05631321652151
46
+ BHAGYANGR.NS/CS.TO,-8.876559449988441e-05,0.0010920247313968073,-0.0812853335165262,-0.0024916594820197533,28.962437832974977
47
+ BHAGYANGR.NS/CUBEXTUB.NS,4.2282180329200614e-05,9.822323565167935e-05,0.43047024513774207,-0.00012514096629827033,27.925111599290567
48
+ BHAGYANGR.NS/FDY.TO,9.911246990657041e-05,0.002455826086957325,0.040358098007406945,-0.004730781288453918,62.91333379646588
49
+ BHAGYANGR.NS/GRX.AX,-0.00028971644498221316,0.0027666816044103855,-0.10471622196076855,-0.004754839723490601,58.5688555418701
50
+ BHAGYANGR.NS/GRX.L,-4.830143746636928e-05,0.00016255117534607288,-0.29714603640075254,-0.0004534759599134583,70.16643742811367
51
+ BHAGYANGR.NS/HINDCOPPER.NS,-3.8906339715483185e-06,5.3084088097616206e-05,-0.07329190555922974,-0.00010590328464739472,14.298136259522273
52
+ BHAGYANGR.NS/JIX.F,0.00021248348827240804,0.0008360393411925331,0.2541548917654041,-0.001573780458168519,82.86601697948797
53
+ BHAGYANGR.NS/MTJ3.F,0.0010953382058949135,0.0029114438939769065,0.3762182084844262,-0.003879630758871827,44.02024694727368
54
+ BHAGYANGR.NS/OUW0.F,0.0002688760548834601,0.002906038105831274,0.0925232378556674,-0.00512370528019637,30.059580022493094
55
+ BHAGYANGR.NS/PUCOBRE.SN,1.0853064599913864e-05,9.517074745370657e-05,0.11403782034172913,-0.0001502581670337344,65.54660043248278
56
+ BHAGYANGR.NS/RE8.F,-0.0001648495804892347,0.0028389424813802687,-0.05806724918536789,-0.006427505868697349,46.54475715603291
57
+ BHAGYANGR.NS/SARKY.IS,1.152373992097111e-05,0.0003076963931195794,0.037451657473581965,-0.0011547569680025978,49.75643015271566
58
+ BHAGYANGR.NS/SFR.AX,5.148194635107295e-05,0.00023199920393676454,0.2219057025950195,-0.0003673161103447137,46.41425765070565
59
+ CS.TO/OUW0.F,0.006187800697393442,0.011450643773166767,0.5403888916616045,-0.010711454829312204,1.6029516630222154
60
+ CUBEXTUB.NS/FDY.TO,0.0007845263421744075,0.00149862588500968,0.5234971249474581,-0.001508410754706569,108.85442303098509
61
+ CUBEXTUB.NS/GRX.AX,6.36384739103324e-05,0.0030177910306884094,0.021087766933887194,-0.008873880414873359,88.17099292025958
62
+ CUBEXTUB.NS/GRX.L,0.0,0.0,,0.0,111.26334875320688
63
+ CUBEXTUB.NS/HINDCOPPER.NS,2.1590568998197668e-05,4.805911155933034e-05,0.44925027320872335,0.0,26.31800953856392
64
+ CUBEXTUB.NS/JIX.F,6.993202933047726e-05,0.0006040330998564552,0.11577516090938757,-0.0010356158396423942,24.488841933734584
65
+ CUBEXTUB.NS/MTJ3.F,0.0004744674348713396,0.0008331120468301126,0.5695121522688682,-0.0009682388753128803,71.39234518921627
66
+ CUBEXTUB.NS/OUW0.F,-0.000529896113936057,0.002003546866609874,-0.26447902106361715,-0.004676234619514956,60.82984989421814
67
+ CUBEXTUB.NS/PUCOBRE.SN,1.702947541759592e-05,8.20094476946929e-05,0.20765260462421029,-0.0001521841752243347,121.81500189351588
68
+ CUBEXTUB.NS/RE8.F,0.0013420286969336725,0.0025721291554915045,0.5217578962037878,-0.00374363280468474,50.295751753165455
69
+ CUBEXTUB.NS/SARKY.IS,8.817683939099652e-05,0.00042747308157015535,0.2062746011213463,-0.0008173960233719408,105.67658869939382
70
+ CUBEXTUB.NS/SFR.AX,-2.096582469846009e-05,0.0005353518793677406,-0.039162699350604825,-0.0014792863446207276,29.143035344954246
71
+ FDY.TO/GRX.AX,0.03439703967170815,0.040228115273470505,0.8550497441373345,-0.07067463276570908,83.37890978249656
72
+ FDY.TO/GRX.L,0.03221525812505788,0.02856757983020966,1.1276859403746504,-0.0264660912702098,90.3190850219358
73
+ FDY.TO/HINDCOPPER.NS,0.029843026681218632,0.02606342493930019,1.1450155438404912,-0.028939678849369387,64.9646934714888
74
+ FDY.TO/JIX.F,0.03662617136257906,0.04142029319458316,0.8842566900846791,-0.06823372195345995,68.30254918328009
75
+ FDY.TO/MTJ3.F,0.043489900843854734,0.04060907095061916,1.0709405516008648,-0.06920837368805552,52.65188014940165
76
+ FDY.TO/OUW0.F,0.04134423179278279,0.03929824006617014,1.0520631896789177,-0.05680185812103446,20.34109050555137
77
+ FDY.TO/PUCOBRE.SN,0.031150896643225456,0.028719725752592056,1.084651605366182,-0.02383241147450124,29.69317449514897
78
+ FDY.TO/RE8.F,0.03852685628627506,0.04167859449359142,0.9243799306187982,-0.060438420765762196,24.87211352505537
79
+ GRX.AX/GRX.L,0.036849859888825165,0.0375898423162381,0.9803142981769498,-0.027466995669377794,2.137919235933928
80
+ GRX.AX/HINDCOPPER.NS,0.012865011490230671,0.023730905530123896,0.5421205471447302,-0.05062274662696435,82.1427350570934
81
+ GRX.AX/JIX.F,0.01566849916564017,0.03303988678568906,0.4742298079673459,-0.05384346927344101,96.9863284772213
82
+ GRX.AX/MTJ3.F,0.022513800480160384,0.034772512438693344,0.6474597002403543,-0.048067964931316605,23.8286308823473
83
+ GRX.AX/OUW0.F,0.03296054738584675,0.03480105648583718,0.9471134130442432,-0.0532757434592191,84.7114907644092
84
+ GRX.AX/PUCOBRE.SN,0.022388696356388627,0.03916873670884552,0.5715960798738899,-0.03835050678554284,93.87755243063428
85
+ GRX.AX/RE8.F,0.019196722316995762,0.04069770262865231,0.47169056426002626,-0.05270274959090142,77.00619129671291
86
+ GRX.AX/SARKY.IS,0.039963876009710075,0.03344178625800246,1.19502815134903,-0.030603297577380766,30.766531733933597
87
+ GRX.AX/SFR.AX,0.031333332577252015,0.037561451620305525,0.8341885423915134,-0.038559708139174684,72.3670527555053
88
+ JIX.F/SFR.AX,0.015151394990011946,0.04746400657228732,0.31921862658046973,-0.08521344096114344,37.210056047668964
89
+ MTJ3.F/RE8.F,0.015277409029052613,0.02963431947212822,0.5155309553648221,-0.0856450808450801,51.31666799334718
90
+ MTJ3.F/SFR.AX,-0.010076787153644795,0.024376770054227493,-0.41337663403430464,-0.08978013192865307,79.00933735832268
91
+ PUCOBRE.SN/SARKY.IS,0.0,0.0,,0.0,126.22931397278033
92
+ RE8.F/SFR.AX,-0.013851531714805354,0.05638419622891655,-0.24566337096602286,-0.1474315665002387,44.75423200487218
output/portfolio_metrics.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ annual_return,annual_vol,sharpe,max_drawdown
2
+ 0.017780666121420152,0.01101873703285444,1.6136755118489303,-0.008674351588195456
output/portfolio_weights.csv ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ,0
2
+ 2009.TW/9CM0.F,0.019356938303344905
3
+ 2009.TW/ATYM.L,0.019276209356947783
4
+ 2009.TW/CUBEXTUB.NS,0.019276647446920484
5
+ 2009.TW/OUW0.F,0.019265760341899654
6
+ 2009.TW/RE8.F,0.019302079382489568
7
+ 2009.TW/SFR.AX,0.01927866704138942
8
+ 3N4.SG/9CM0.F,1.600026089701147e-05
9
+ 3N4.SG/ARREF,-1.4033629405966763e-08
10
+ 3N4.SG/RE8.F,2.776962026905125e-07
11
+ 9CM0.F/ARREF,0.01683404735011321
12
+ 9CM0.F/BHAGYANGR.NS,0.017710650821087238
13
+ 9CM0.F/CUBEXTUB.NS,0.017252421447959645
14
+ 9CM0.F/FDY.TO,0.01696192143711173
15
+ 9CM0.F/HINDCOPPER.NS,0.018922788182741408
16
+ 9CM0.F/JIX.F,0.016824229933070544
17
+ 9CM0.F/MTJ3.F,0.016832237280803984
18
+ 9CM0.F/PUCOBRE.SN,0.019035491677081465
19
+ 9CM0.F/RE8.F,0.01671660866888466
20
+ ARREF/ATYM.L,0.01919393506512004
21
+ ARREF/CUBEXTUB.NS,0.019268867373268328
22
+ BHAGYANGR.NS/CUBEXTUB.NS,0.0192767066786576
23
+ BHAGYANGR.NS/FDY.TO,0.019278384220307747
24
+ BHAGYANGR.NS/JIX.F,0.01927673216947256
25
+ BHAGYANGR.NS/MTJ3.F,0.019273899481384575
26
+ BHAGYANGR.NS/OUW0.F,0.0192806434608896
27
+ BHAGYANGR.NS/PUCOBRE.SN,0.019276740189728896
28
+ BHAGYANGR.NS/SARKY.IS,0.01927643334278014
29
+ BHAGYANGR.NS/SFR.AX,0.019276583462850962
30
+ CS.TO/OUW0.F,0.019219583853766795
31
+ CUBEXTUB.NS/FDY.TO,0.0192742692579241
32
+ CUBEXTUB.NS/GRX.AX,0.019271860877920412
33
+ CUBEXTUB.NS/HINDCOPPER.NS,0.01927667384870885
34
+ CUBEXTUB.NS/JIX.F,0.0192822843975036
35
+ CUBEXTUB.NS/MTJ3.F,0.019274920210791805
36
+ CUBEXTUB.NS/PUCOBRE.SN,0.019276659462253796
37
+ CUBEXTUB.NS/RE8.F,0.019269532749390687
38
+ CUBEXTUB.NS/SARKY.IS,0.01927701639747627
39
+ FDY.TO/GRX.AX,0.018795273835669365
40
+ FDY.TO/GRX.L,0.019161403617310207
41
+ FDY.TO/HINDCOPPER.NS,0.019201626745230304
42
+ FDY.TO/JIX.F,0.018764988751327354
43
+ FDY.TO/MTJ3.F,0.01880835759194311
44
+ FDY.TO/OUW0.F,0.01885245862626124
45
+ FDY.TO/PUCOBRE.SN,0.01911990767601962
46
+ FDY.TO/RE8.F,0.018782827094670183
47
+ GRX.AX/GRX.L,0.01900340047400452
48
+ GRX.AX/HINDCOPPER.NS,0.01913912361141376
49
+ GRX.AX/JIX.F,0.019020941561484168
50
+ GRX.AX/MTJ3.F,0.018993074243052094
51
+ GRX.AX/OUW0.F,0.018949323808203217
52
+ GRX.AX/PUCOBRE.SN,0.019163099561725568
53
+ GRX.AX/RE8.F,0.018970021501792528
54
+ GRX.AX/SARKY.IS,0.019008665335682448
55
+ GRX.AX/SFR.AX,0.018963413787314264
56
+ JIX.F/SFR.AX,0.019117617799609916
57
+ MTJ3.F/RE8.F,0.019219786903504947
trade_details.csv ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Date,V_Price,MA_Price,Beta,Spread,Z-Score,Position
2
+ 2022-02-01,385.1221618652344,226.6815948486328,1.698997462238565,-0.009292518783354353,-0.8713897237619049,0.0
3
+ 2022-02-24,362.8435974121094,212.33453369140625,1.708769658946882,0.012788693599929957,1.6541589842934814,-1.0
4
+ 2022-02-25,362.5587463378906,214.25950622558594,1.692183822482254,-0.007723910081722352,-1.0506848483260303,1.0
5
+ 2022-03-02,338.0011291503906,203.716064453125,1.6591728826121726,0.000959257292095117,0.3169645002202774,0.0
6
+ 2022-03-11,319.0426940917969,192.2150115966797,1.6597907892569284,0.005988286714284641,1.0820874131932998,-1.0
7
+ 2022-03-15,329.0719299316406,201.42953491210938,1.6337199966045473,-0.007529161026241127,-1.1657623950867881,1.0
8
+ 2022-03-16,338.58062744140625,207.0286102294922,1.6354251976640835,0.0008216347184770711,0.3682846009231695,0.0
9
+ 2022-03-18,343.89495849609375,214.1031494140625,1.606266767052406,-0.011815128970681599,-1.7301559150902894,1.0
10
+ 2022-03-23,336.1249084472656,209.77435302734375,1.6023300948467785,-0.0028505354596859434,-0.15922090692229954,0.0
11
+ 2022-03-24,343.16802978515625,212.34429931640625,1.616062115411025,0.006452236412883394,1.696741088575966,-1.0
12
+ 2022-03-25,342.8439025878906,213.4386749267578,1.6063089884619992,-0.004559432379210193,-0.4967617367767362,0.0
13
+ 2022-03-29,361.04595947265625,222.90725708007812,1.6196662227320948,0.010604378194102537,2.191600264918986,-1.0
14
+ 2022-03-31,351.0559997558594,216.70237731933594,1.620004249029402,-0.002772276237578808,-0.35807215326871655,0.0
15
+ 2022-04-12,340.1522521972656,206.56932067871094,1.6466309021390433,0.00882533383048667,1.6556254496612903,-1.0
16
+ 2022-04-18,350.97265625,208.29888916015625,1.6849652119108185,-0.003725664530747963,-1.0176329684611791,1.0
17
+ 2022-04-21,358.48779296875,211.50393676757812,1.694931778741407,0.0030492124687384603,0.15526813873362297,0.0
18
+ 2022-04-26,338.4898986816406,196.50473022460938,1.7224959264975666,0.011301332247739992,1.5466823971462649,-1.0
19
+ 2022-04-27,355.66473388671875,209.2174072265625,1.7000279755795624,-0.01071137665923061,-2.16250218073127,1.0
20
+ 2022-04-28,372.642822265625,215.6177215576172,1.7281964821250637,0.013034385929472592,1.6609387370301136,-1.0
21
+ 2022-04-29,357.44512939453125,208.25982666015625,1.71636941200485,-0.005666834393139197,-1.2256617891172599,1.0
22
+ 2022-05-04,362.50115966796875,209.6180419921875,1.7293359352714737,0.0011469696341350755,-0.23861776732149803,0.0
23
+ 2022-05-06,341.45074462890625,198.18540954589844,1.7229115509604658,-0.005186709552731372,-1.0801055355571185,1.0
24
+ 2022-05-13,327.3645935058594,195.0492401123047,1.6783314417449464,0.0073211369187902164,1.0658109967579399,-1.0
25
+ 2022-05-16,324.3447265625,193.65904235839844,1.6748328632364742,-0.0018018422500745146,-0.20071102435017932,0.0
26
+ 2022-05-18,330.41400146484375,195.7932891845703,1.687517288181404,0.009441055980232704,1.2907520682269953,-1.0
27
+ 2022-05-24,335.125732421875,198.37789916992188,1.6893233234540768,0.0013204963048565332,0.317910262297382,0.0
28
+ 2022-06-01,351.2283630371094,205.52468872070312,1.7089016329953104,0.006886861446957937,1.2638101351013376,-1.0
29
+ 2022-06-08,356.4122619628906,209.01980590820312,1.7051601331790787,2.188339379927129e-05,-0.05644141721841759,0.0
30
+ 2022-06-10,329.2827453613281,195.3233642578125,1.6858742852930837,-0.007891757852178216,-1.73843943442919,1.0
31
+ 2022-06-14,316.8786926269531,189.45909118652344,1.6725398748674623,0.0008079613421045906,0.17824890597167806,0.0
32
+ 2022-06-16,303.7369079589844,185.0828399658203,1.6411606183339826,-0.013760122330836566,-2.3679495060793565,1.0
33
+ 2022-06-17,305.61572265625,186.02272033691406,1.6428896176998418,0.0009267584526924111,0.4203095274464105,0.0
34
+ 2022-06-23,311.5865783691406,192.51361083984375,1.6185718579540374,-0.010534409345780205,-1.5873846851052007,1.0
35
+ 2022-06-24,325.1021423339844,201.1974639892578,1.6158429067767806,-0.0013527145346188263,0.16171254543539496,0.0
36
+ 2022-06-27,323.4594421386719,199.28839111328125,1.623054061376715,0.0036095570295060497,1.007168175757446,-1.0
37
+ 2022-06-28,313.0915832519531,193.96253967285156,1.6142092818595024,-0.004548621005824316,-0.4903142951727661,0.0
38
+ 2022-06-29,317.3213806152344,195.31358337402344,1.6246491620163739,0.005331056212014573,1.3354470297807317,-1.0
39
+ 2022-07-01,313.0423889160156,195.00027465820312,1.60535542505928,-0.002359894580422406,0.008911272349719201,0.0
40
+ 2022-07-07,319.26580810546875,198.54432678222656,1.608011357379714,0.004275696339107071,1.3782762472485337,-1.0
41
+ 2022-07-12,318.0737609863281,200.52195739746094,1.5862406788498085,-0.0023248401126920726,0.057621582992309704,0.0
42
+ 2022-07-13,318.5762023925781,199.86598205566406,1.5939298996672235,0.003837667702384806,1.2084711792217937,-1.0
43
+ 2022-07-14,320.2115173339844,201.58908081054688,1.5884502647453211,-0.0027114492947362123,-0.10823739805409809,0.0
44
+ 2022-07-18,326.1029357910156,202.86180114746094,1.6074784361704821,0.006964923767782238,1.7704559006923328,-1.0
45
+ 2022-07-19,335.33404541015625,209.1764373779297,1.603125693681451,-0.002075863151901558,-0.23520523924680745,0.0
46
+ 2022-07-27,338.18115234375,206.0533905029297,1.6411720421429,0.012088661588450123,2.4856951609432287,-1.0
47
+ 2022-07-29,348.54522705078125,207.65895080566406,1.67844929981724,0.0002064702317170486,-0.2571156402891086,0.0
48
+ 2022-08-01,345.3434143066406,206.92469787597656,1.6689549173571432,-0.0045777361116847715,-1.0769100297524834,1.0
49
+ 2022-08-02,343.8360900878906,201.9317169189453,1.7026519992064635,0.016648572654730742,2.17972537849096,-1.0
50
+ 2022-08-04,350.7913818359375,208.9904022216797,1.6785749231209075,-0.014666506326022954,-2.1803234503995075,1.0
51
+ 2022-08-18,352.0622863769531,211.10630798339844,1.6676928378548015,0.0018085270696701627,0.06095102554861629,0.0
52
+ 2022-09-07,323.7483825683594,196.56179809570312,1.6470353605213508,0.0041505770780077,1.0781302732716491,-1.0
53
+ 2022-09-12,333.4030456542969,202.65225219726562,1.6451951737454968,0.0005383907002283195,0.4765621898360632,0.0
54
+ 2022-09-13,320.61553955078125,195.82623291015625,1.63726572380837,-0.00403941553219056,-1.104522737490833,1.0
55
+ 2022-09-16,310.4582824707031,189.57884216308594,1.637599055977204,0.004149511182220067,1.5005166920930897,-1.0
56
+ 2022-09-19,309.3746032714844,189.4121551513672,1.633352615231713,-0.0022357016762271087,-0.3983450009368775,0.0
57
+ 2022-09-20,308.6258850097656,188.37254333496094,1.6383663209773272,0.0026542129235735956,1.0212210358208584,-1.0
58
+ 2022-09-21,299.98590087890625,183.41976928710938,1.635524062072271,-0.001545249905689161,-0.33290163361032404,0.0
59
+ 2022-09-22,293.9368591308594,182.21340942382812,1.6132131453322827,-0.012208207473406674,-2.755845144457649,1.0
60
+ 2022-09-26,285.8091735839844,177.11354064941406,1.6136724175616397,0.005938261342635087,1.5108100982330033,-1.0
61
+ 2022-09-29,282.5187072753906,176.59373474121094,1.5999087885006382,-0.015160931223249463,-2.4970290313955736,1.0
62
+ 2022-10-04,296.80377197265625,182.07614135742188,1.630036730404185,0.012973829794077574,2.043838964797215,-1.0
63
+ 2022-10-05,299.6903381347656,184.0572509765625,1.6282504716636348,-0.000967580934286616,-0.07556540812973683,0.0
64
+ 2022-10-17,291.1351318359375,181.68382263183594,1.6023916298638752,0.0064951690106909155,1.1358144865770117,-1.0
65
+ 2022-10-19,293.819091796875,182.82151794433594,1.6071586389486536,-0.004090153070819724,-0.49237682474029887,0.0
66
+ 2022-10-20,292.3586730957031,183.61590576171875,1.5922735800095655,-0.008082518207800149,-1.174378848232363,1.0
67
+ 2022-10-24,301.5553283691406,187.0387420654297,1.612220933572808,0.007553022129968667,1.1893081737032174,-1.0
68
+ 2022-10-26,315.2812194824219,199.41578674316406,1.5811015977965515,-0.015399563051175846,-1.9972352273197413,1.0
69
+ 2022-11-01,328.7801208496094,202.94647216796875,1.6199704842305895,0.012826058775203819,2.031531122672483,-1.0
70
+ 2022-11-02,315.58709716796875,197.0816192626953,1.6013493493574906,-0.009425608669062058,-1.2732445913651174,1.0
71
+ 2022-11-04,314.1563415527344,193.18801879882812,1.626091852298869,0.014878222199229185,1.9365682898407368,-1.0
72
+ 2022-11-14,334.87835693359375,203.33128356933594,1.646994282269107,-0.0071045115409447135,-1.0494715613821142,1.0
73
+ 2022-11-22,340.3944091796875,206.74209594726562,1.6464672317442657,0.0003227803857157596,-0.07213585495381308,0.0
74
+ 2022-11-28,340.0293273925781,207.65623474121094,1.63749055698827,-0.005796095894311293,-1.0766660222795783,1.0
75
+ 2022-11-30,351.6830139160156,213.2982940673828,1.6487824712515218,0.0005255098623706544,-0.03690346798938799,0.0
76
+ 2022-12-01,356.02471923828125,213.2982940673828,1.6690954719175388,0.00950244267698963,1.3262464600366217,-1.0
77
+ 2022-12-14,352.7782897949219,209.6811065673828,1.6824526167287452,-0.00023662795024392835,-0.27325445147569744,0.0
78
+ 2022-12-15,341.66729736328125,204.36337280273438,1.6718869482903826,-0.005158334212126192,-1.3129400999762781,1.0
79
+ 2022-12-16,341.26275634765625,203.3607635498047,1.678100054589528,0.0030479333609036985,0.41239471703467173,0.0
80
+ 2022-12-28,337.42425537109375,201.49322509765625,1.6746426643049293,-0.004895945838143234,-1.384479218994223,1.0
81
+ 2022-12-29,343.6014099121094,204.5108184814453,1.680100594342152,0.0026622320331171068,0.47822859085398794,0.0
82
+ 2023-01-06,363.3927001953125,214.0355224609375,1.6977604985121424,0.011644882724397121,2.87224874024429,-1.0
83
+ 2023-01-10,366.69378662109375,217.3185577392578,1.687396162117543,-0.008713665049583597,-2.066274564239814,1.0
84
+ 2023-01-11,373.4640808105469,218.31134033203125,1.7106461477298303,0.010627465821698934,2.0080584976337903,-1.0
85
+ 2023-01-12,375.3913879394531,219.80538940429688,1.7078410246225804,-0.0012735183465224509,-0.37773082695781596,0.0
86
+ 2023-01-13,371.1513366699219,219.25491333007812,1.6928157721823813,-0.006838743715434248,-1.375623858467934,1.0
87
+ 2023-01-30,366.8024597167969,225.19190979003906,1.6288365843502401,0.0016385510822374272,0.33066667686555223,0.0
88
+ 2023-03-03,357.29443359375,220.38363647460938,1.6212542394102907,-0.003471337366818261,-1.0381443760644253,1.0
89
+ 2023-03-13,340.6997375488281,211.22439575195312,1.6129724024016827,0.0006164869565168374,0.2967598574750179,0.0
90
+ 2023-03-14,348.71539306640625,215.35098266601562,1.6192750485478886,0.0029201550582911295,1.1482527927038366,-1.0
91
+ 2023-03-16,343.95147705078125,214.15928649902344,1.6060726904056573,-0.003904392061258477,-1.302002989229021,1.0
92
+ 2023-03-17,345.5921936035156,214.10018920898438,1.614143515776242,0.0037614653669493237,1.655574248623593,-1.0
93
+ 2023-03-20,345.256103515625,214.84869384765625,1.6069887149743203,-0.0033229245312895728,-1.279277256731132,1.0
94
+ 2023-03-27,350.4944152832031,218.45330810546875,1.6044196322685884,0.0036390247703366185,1.6399152074292744,-1.0
95
+ 2023-04-03,362.20660400390625,225.53451538085938,1.6060146175336325,-0.0051244561177554715,-1.7091647144032622,1.0
96
+ 2023-04-13,365.9227600097656,229.1686553955078,1.5967390426060775,0.0002205982203804524,0.2223392030038708,0.0
97
+ 2023-04-19,369.04095458984375,229.0504913330078,1.6111599095760176,0.003985685412487783,1.4712008690482106,-1.0
98
+ 2023-04-26,363.06195068359375,224.69735717773438,1.6157773367298176,0.0010533327255188851,0.4148465888237753,0.0
99
+ 2023-04-27,369.90228271484375,225.54434204101562,1.6399948816015522,0.010716193388361717,2.975960523583482,-1.0
100
+ 2023-05-01,376.0298156738281,228.99134826660156,1.6421120771809472,0.0003571152933545818,-0.05235487257484481,0.0
101
+ 2023-05-02,372.23846435546875,223.54507446289062,1.665114719543511,0.010270385859371345,2.4033766836987365,-1.0
102
+ 2023-05-03,371.1198425292969,222.56019592285156,1.6674984135943536,0.0010688986933473643,-0.08899787209200058,0.0
103
+ 2023-05-05,380.78143310546875,228.27244567871094,1.66811531425513,-0.0033293536612291064,-1.210602735868505,1.0
104
+ 2023-05-11,379.5242614746094,227.9576416015625,1.664884900495458,0.0010260196127092058,-0.11509805195247924,0.0
105
+ 2023-05-12,378.069091796875,228.32275390625,1.6558710230451887,-0.003940298362067551,-1.1778282557153885,1.0
106
+ 2023-05-16,376.40594482421875,227.4247589111328,1.6550732923711053,0.0013003264652979851,0.025913580838604223,0.0
107
+ 2023-05-17,383.09783935546875,229.57595825195312,1.6686935379247532,0.005921357551642359,1.02986622965584,-1.0
108
+ 2023-05-19,381.6822204589844,230.22726440429688,1.6578979247478065,-0.011083417263932915,-2.2487593342202077,1.0
109
+ 2023-05-23,369.98138427734375,221.6125946044922,1.6694929031247197,0.0007303420885023115,-0.0976187082728893,0.0
110
+ 2023-06-01,367.1403503417969,223.50723266601562,1.642661022539504,-0.006269014335202883,-1.2073102150204904,1.0
111
+ 2023-06-05,366.7839660644531,223.77366638183594,1.6390838068728015,0.00017309342922544602,0.17929006526321933,0.0
112
+ 2023-06-06,376.1288146972656,225.2045135498047,1.6701044829003096,0.01374704835330931,2.4432659214975327,-1.0
113
+ 2023-06-07,367.6452331542969,222.29347229003906,1.653905992109082,-0.007272672932913338,-1.3185583497282485,1.0
114
+ 2023-06-09,365.4971008300781,220.60609436035156,1.6567788084127906,0.0015986871352424714,0.33061114091715815,0.0
115
+ 2023-06-14,370.9812316894531,220.48765563964844,1.6825182723057237,0.006722257892477046,1.0964661382332492,-1.0
116
+ 2023-06-15,375.2181091308594,223.18157958984375,1.6812260565223036,-0.0005778113923042838,-0.15637522854656752,0.0
117
+ 2023-06-16,372.7333984375,225.88539123535156,1.650160383308101,-0.013725347128115573,-2.137878384874019,1.0
118
+ 2023-06-22,373.9906005859375,225.3722686767578,1.6594368173799132,-0.00043967271221845294,-0.038568404934278856,0.0
119
+ 2023-07-20,394.6161804199219,236.45384216308594,1.6688724706641183,0.00487265118920277,1.4201448371701,-1.0
120
+ 2023-07-21,394.05108642578125,236.0887908935547,1.6690796599521671,8.760264870488754e-05,-0.03913377317079649,0.0
121
+ 2023-07-24,401.28790283203125,237.55906677246094,1.6891776147109354,0.008445068369837827,2.0714113109040126,-1.0
122
+ 2023-07-25,397.80828857421875,235.53616333007812,1.6889482284457165,-9.72170176396503e-05,-0.11982246554262932,0.0
123
+ 2023-07-26,398.92852783203125,233.96719360351562,1.705032485355222,0.006862230642639133,1.7418320012391706,-1.0
124
+ 2023-07-27,391.0869445800781,231.3423309326172,1.6905388504410124,-0.006253613092781052,-1.7375221496842947,1.0
125
+ 2023-08-03,389.6098327636719,235.605224609375,1.653647662160239,0.0018038956409327511,0.4315900088013289,0.0
126
+ 2023-08-22,394.3980407714844,237.83773803710938,1.6582445140834419,0.00491642943302395,1.46646916785896,-1.0
127
+ 2023-08-31,409.07000732421875,242.88967895507812,1.684182652458312,-0.0005764330925330796,-0.47807769746031864,0.0
128
+ 2023-09-01,411.9746398925781,245.29209899902344,1.679534454379057,-0.0018917632403372409,-1.085954588762225,1.0
129
+ 2023-09-05,407.93988037109375,242.5535430908203,1.6818510324600322,0.0009534969586866282,0.12923903277053178,0.0
130
+ 2023-09-11,413.0849609375,244.4121856689453,1.6901027493718126,0.0032539584415758327,1.1298533341289927,-1.0
131
+ 2023-09-13,412.6983642578125,245.01527404785156,1.6843839073192315,-0.0014203957999825434,-1.0061732992676327,1.0
132
+ 2023-09-14,409.7639465332031,238.75717163085938,1.7161815407049197,0.013295869405965277,3.386738267373946,-1.0
133
+ 2023-09-18,413.52117919921875,241.8812713623047,1.7096273232062695,-0.0056512936475314746,-1.833987988138692,1.0
134
+ 2023-09-25,399.0077819824219,230.70960998535156,1.729454682422577,0.005966713369105037,1.1837976706056528,-1.0
135
+ 2023-10-02,392.42529296875,228.64332580566406,1.716339212543432,-0.0042127978548478495,-1.2478352524411938,1.0
136
+ 2023-10-06,395.0988464355469,232.37051391601562,1.7002879081926865,0.0020714036251092693,0.3943303582986671,0.0
137
+ 2023-10-13,395.1584167480469,234.9706573486328,1.6817609081397857,-0.006049340792287694,-1.5182760086126854,1.0
138
+ 2023-10-23,380.9020080566406,228.90037536621094,1.6640324936901674,0.004345629389263195,1.8972652094319884,-1.0
139
+ 2023-10-25,383.5229797363281,234.1599884033203,1.6378998624536432,-0.00763306161690025,-1.723754886591619,1.0
140
+ 2023-10-27,361.45330810546875,226.6660614013672,1.594628831493994,0.005071473660677839,1.2850045983754101,-1.0
141
+ 2023-11-15,393.967041015625,245.81430053710938,1.6027198962464777,-0.004429237111423845,-0.47187932041490727,0.0
142
+ 2023-11-27,406.01953125,251.7884979248047,1.6125622773163302,-0.00510236568112532,-1.590237528780358,1.0
143
+ 2023-12-01,411.3705749511719,254.07713317871094,1.619072085312121,0.0013811053908625581,0.2115065096454037,0.0
144
+ 2023-12-04,405.2848815917969,252.08572387695312,1.6077442310925305,-0.0044867121590641545,-1.7378501039327083,1.0
145
+ 2023-12-06,407.41937255859375,251.93711853027344,1.6171334277860407,0.003436483194604989,1.043888094830782,-1.0
146
+ 2023-12-12,417.71453857421875,257.15838623046875,1.6243466509968976,0.0001751249901644769,-0.0027225700360828118,0.0
147
+ 2023-12-18,421.36798095703125,255.9793701171875,1.6460699926537061,0.008021068732091408,2.3335483519063738,-1.0
148
+ 2023-12-26,420.6134338378906,256.7620544433594,1.6381543343295613,-0.002438539861316258,-1.0308447599350001,1.0
149
+ 2023-12-27,421.2984619140625,256.5341491699219,1.6422642506145397,0.001599670482221427,0.4182501857200979,0.0
150
+ 2024-01-02,418.8462829589844,256.4747619628906,1.633102542756725,-0.0033029555380608144,-1.245399642333756,1.0
151
+ 2024-01-10,425.8503723144531,262.1120910644531,1.6246676688156183,0.005332356381018144,1.8416081181238526,-1.0
152
+ 2024-01-11,424.3091735839844,261.58697509765625,1.6220615275688748,-0.0009948350411264073,-0.3279064354243026,0.0
153
+ 2024-01-16,425.929931640625,262.7857971191406,1.6208391166185407,-0.0035676218619755673,-1.1547012483304182,1.0
154
+ 2024-01-19,434.31231689453125,268.3934020996094,1.6181846229135608,0.0022407254871836813,1.0144634894294242,-1.0
155
+ 2024-01-23,436.2811584472656,268.7500915527344,1.6233767360605325,-0.0014879935815770295,-0.4578111742474664,0.0
156
+ 2024-01-25,434.3321838378906,270.08758544921875,1.608133430952922,-0.00469160835200455,-1.5106158463332637,1.0
157
+ 2024-01-26,436.05242919921875,265.4608154296875,1.642575653689146,0.012956765946057658,3.194444263549746,-1.0
158
+ 2024-01-29,438.0908203125,271.12786865234375,1.6158452007281603,-0.009845033044655338,-2.0309471388606246,1.0
159
+ 2024-01-31,446.6919860839844,270.7315979003906,1.6498926279697408,0.013918549661752877,2.4385096159755455,-1.0
160
+ 2024-02-02,457.9778747558594,274.6153259277344,1.6677095319732367,-0.0007219197603944849,-0.28095128645096684,0.0
161
+ 2024-02-20,449.19775390625,273.1124267578125,1.644787520734429,-0.014157382495739057,-2.2463600283303236,1.0
162
+ 2024-02-26,471.82916259765625,282.0457458496094,1.6728809135279743,0.0002176240828362097,-0.0568458765807258,0.0
163
+ 2024-03-04,465.8431396484375,278.45257568359375,1.6729882515608747,-0.004748087080145069,-1.1575693258045445,1.0
164
+ 2024-03-05,464.87860107421875,277.3111267089844,1.6763747886975895,0.0012196339545766932,0.2388647559444203,0.0
165
+ 2024-03-22,478.94873046875,281.162353515625,1.7034373876277566,0.0062654968219248985,2.4665706015814823,-1.0
166
+ 2024-03-25,473.35052490234375,279.1275329589844,1.695831440726785,-0.0027214620038762405,-1.2862579964546386,1.0
167
+ 2024-03-27,475.24969482421875,276.9537048339844,1.7159717490915911,0.00496152285035123,1.6403750929502,-1.0