### Installing ArbitrageLab Package Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/getting_started/installation.rst This command installs the ArbitrageLab library using `pip`, the Python package installer. It fetches the latest version from PyPI and installs it into the active `conda` environment or directly into a Google Colab session, making the library available for import and use in Python scripts or notebooks. ```Shell pip install arbitragelab ``` -------------------------------- ### Installing CMake with Homebrew on Apple Silicon Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/getting_started/installation.rst This command installs `cmake` using Homebrew, a popular package manager for macOS. `cmake` is a cross-platform build system generator that is often a prerequisite for compiling certain Python packages, particularly on Apple Silicon architectures, ensuring necessary build tools are available. ```Shell brew install cmake ``` -------------------------------- ### Creating New Conda Environment for Python 3.8 Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/getting_started/installation.rst This command creates a new `conda` environment named `` and specifies Python version 3.8 for that environment. This practice isolates project dependencies, preventing conflicts with other Python projects or the system's default Python installation, and is recommended for Linux and MacOS setups. ```Shell conda create -n python=3.8 ``` -------------------------------- ### Implementing Regime-Switching Arbitrage Strategy in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/time_series_approach/regime_switching_arbitrage_rule.rst This example demonstrates the full workflow of applying the `RegimeSwitchingArbitrageRule` for statistical arbitrage. It covers downloading financial data, constructing a spread series, initializing the arbitrage rule, generating trading signals, deciding on trades, plotting results, and dynamically changing the trading strategy rules. It requires `matplotlib`, `yfinance`, and `arbitragelab`. ```Python import matplotlib.pyplot as plt import yfinance as yf from arbitragelab.time_series_approach.regime_switching_arbitrage_rule import ( RegimeSwitchingArbitrageRule, ) data = yf.download("CL=F NG=F", start="2015-01-01", end="2020-01-01", progress=False)[ "Adj Close" ] # Construct spread series ratt = data["NG=F"] / data["CL=F"] rsar = RegimeSwitchingArbitrageRule(delta=1.5, rho=0.6) window_size = 60 # Get the current signal signal = rsar.get_signal( ratt[-window_size:], switching_variance=False, silence_warnings=True ) # [Open long, close long, open short, close short] list(signal) # doctest: +NORMALIZE_WHITESPACE [True, False, False, True] signals = rsar.get_signals( ratt, window_size, switching_variance=True, silence_warnings=True ) signals # doctest: +ELLIPSIS array(...) signals.shape (1256, 4) # Decide on trades based on the signals trades = rsar.get_trades(signals) trades # doctest: +ELLIPSIS array(...) trades.shape (1256, 4) # Plot trades rsar.plot_trades(ratt, trades) # doctest: +ELLIPSIS # Changing rules cl_rule = lambda Xt, mu, delta, sigma: Xt >= mu cs_rule = lambda Xt, mu, delta, sigma: Xt <= mu rsar.change_strategy("High", "Long", "Open", cl_rule) rsar.change_strategy("High", "Short", "Close", cs_rule) # Get signals on a rolling basis signals = rsar.get_signals( ratt, window_size, switching_variance=True, silence_warnings=True ) signals # doctest: +ELLIPSIS array(...) signals.shape (1256, 4) # Deciding the trades based on the signals trades = rsar.get_trades(signals) trades # doctest: +ELLIPSIS array(...) trades.shape (1256, 4) # Plotting trades rsar.plot_trades(ratt, trades) # doctest: +ELLIPSIS ``` -------------------------------- ### Activating Conda Environment Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/getting_started/installation.rst This command activates a previously created `conda` environment. It is a crucial step after creating an environment (e.g., with `conda create`) to ensure that subsequent commands operate within the isolated environment, making its installed packages and Python interpreter available for use on Windows, Linux, and MacOS. ```Shell conda activate ``` -------------------------------- ### Scaling Model Results with description() in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/optimal_mean_reversion/heat_potentials.rst This snippet calls the `description()` method on an `example` object. As indicated by the comment, this method is specifically used to scale the results of a model back to its initial state, making them comparable or interpretable within the original context. ```Python example.description() ``` -------------------------------- ### Initializing CoxIngersollRoss Class (Python) Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/optimal_mean_reversion/cir_model.rst This snippet refers to the __init__ constructor of the CoxIngersollRoss class. It is responsible for instantiating a new CIR model object, allowing for the setup of initial conditions and internal parameters necessary for the model's operation. This is the first step before fitting the model to data or performing calculations. ```Python CoxIngersollRoss.__init__ ``` -------------------------------- ### Implementing PCA Strategy and Individual Steps in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/other_approaches/pca_approach.rst This Python code demonstrates how to use the `PCAStrategy` class from `arbitragelab` to generate target weights for a portfolio. It shows both the direct application of `get_signals` with predefined parameters and the individual steps involved, including data standardization, calculating factor weights, determining factor returns, computing residuals, and generating S-scores for eigen portfolios. The example uses a CSV file for input data and illustrates the flow of the PCA approach. ```Python # Importing packages import pandas as pd import numpy as np from arbitragelab.other_approaches.pca_approach import PCAStrategy # Getting the dataframe with time series of asset returns data = pd.read_csv('X_FILE_PATH.csv', index_col=0, parse_dates = [0]) # The PCA Strategy class that contains all needed methods pca_strategy = PCAStrategy() # Simply applying the PCAStrategy with standard parameters target_weights = pca_strategy.get_signals(data, k=8.4, corr_window=252, residual_window=60, sbo=1.25, sso=1.25, ssc=0.5, sbc=0.75, size=1) # Or we can do individual actions from the PCA approach # Standardizing the dataset data_standardized, data_std = pca_strategy.standardize_data(data) # Getting factor weights using the first 252 observations data_252days = data[:252] factorweights = pca_strategy.get_factorweights(data_252days) # Calculating factor returns for a 60-day window from our factor weights data_60days = data[(252-60):252] factorret = pd.DataFrame(np.dot(data_60days, factorweights.transpose()), index=data_60days.index) # Calculating residuals for a set 60-day window residual, coefficient = pca_strategy.get_residuals(data_60days, factorret) # Calculating S-scores for each eigen portfolio for a set 60-day window s_scores = pca_strategy.get_sscores(residual, k=8) ``` -------------------------------- ### Implementing Minimum Profit Trading Rule in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/trading/minimum_profit.rst This Python example demonstrates how to use the `MinimumProfitTradingRule` class from ArbitrageLab to implement a pair trading strategy. It shows the initialization of the strategy with optimal levels and shares, and then iteratively updates the spread value, checks for entry signals, adds trades, and updates (closes) existing trades. It also shows how to access open and closed trades. ```Python # Importing packages import pandas as pd import numpy as np # Importing ArbitrageLab tools from arbitragelab.cointegration_approach.minimum_profit import MinimumProfit from arbitragelab.trading import MinimumProfitTradingRule # Using MinimumProfit as optimizer ... # Generate optimal trading levels and number of shares to trade num_of_shares, optimal_levels = optimizer.get_optimal_levels(optimal_ub, minimum_profit, beta_eg, epsilon_t_eg) # Calculating spread spread = optimizer.construct_spread(data, beta_eg) # Creating a strategy strategy = MinimumProfitTradingRule(num_of_shares, optimal_levels) # Adding initial spread value strategy.update_spread_value(spread[0]) # Feeding spread values to the strategy one by one for time, value in spread.iteritems(): strategy.update_spread_value(value) # Checking if logic for opening a trade is triggered trade, side = strategy.check_entry_signal() # Adding a trade if we decide to trade signal if trade: strategy.add_trade(start_timestamp=time, side_prediction=side) # Update trades, close if logic is triggered close = strategy.update_trades(update_timestamp=time) # Checking currently open trades open_trades = strategy.open_trades # Checking all closed trades closed_trades = strategy.closed_trades ``` -------------------------------- ### Estimating OU Model Parameters and Calculating Optimal Portfolio Weights (Python) Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/stochastic_control_approach/ou_model_jurek.rst This example initializes the `OUModelJurek` class, fits the model using training data to estimate Ornstein-Uhlenbeck process parameters, and then prints these parameters using the `describe` method. Finally, it calculates and plots the optimal portfolio weights for the out-of-sample test data, specifying `beta`, `gamma`, and `utility_type` parameters for the investor's utility function. ```Python from arbitragelab.stochastic_control_approach.ou_model_jurek import OUModelJurek sc = OUModelJurek() sc.fit(data_train_dataframe) print(sc.describe()) plt.plot(sc.optimal_portfolio_weights(data_test_dataframe, beta=0.01, gamma=0.5, utility_type=1)) plt.show() ``` -------------------------------- ### Performing Pair Formation with DistanceStrategy in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/distance_approach/distance_approach.rst This snippet illustrates how to initialize the `DistanceStrategy` and perform the pair formation stage. It shows examples of basic pair formation, industry-based selection, and selection based on the number of zero-crossings, specifying parameters like `num_top` and `skip_top` to refine pair selection. ```Python # Performing the pairs formation stage of the DistanceStrategy # Choosing pairs 5-25 from top pairs to construct portfolios strategy = DistanceStrategy() strategy.form_pairs(data_pairs_formation, num_top=20, skip_top=5) # Adding an industry-based selection criterion to The DistanceStrategy strategy_industry = DistanceStrategy() strategy_industry.form_pairs(data_pairs_formation, industry_dict=industry_dict, num_top=20, skip_top=5) # Using the number of zero-crossing for pair selection after industry-based selection strategy_zero_crossing = DistanceStrategy() strategy_zero_crossing.form_pairs(data_pairs_formation, method='zero_crossing', industry_dict=industry_dict, num_top=20, skip_top=5) ``` -------------------------------- ### Estimating OU Model Parameters and Calculating Stabilization Region (Python) Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/stochastic_control_approach/ou_model_jurek.rst This example initializes the `OUModelJurek` class, fits the model using training data, and prints the estimated Ornstein-Uhlenbeck parameters. It then calculates the stabilization region for the spread on the out-of-sample test data, returning the spread `S` and its `min_bound` and `max_bound` based on specified `beta`, `gamma`, and `utility_type` parameters. ```Python from arbitragelab.stochastic_control_approach.ou_model_jurek import OUModelJurek sc = OUModelJurek() sc.fit(data_train_dataframe) print(sc.describe()) S, min_bound, max_bound = sc.stabilization_region(data_test_dataframe, beta=0.01, gamma=0.5, utility_type=1) ``` -------------------------------- ### Implementing C-Vine Copula Strategy in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/copula_approach/cvine_copula_strategy.rst This comprehensive example demonstrates the application of a C-Vine Copula strategy for statistical arbitrage. It covers importing required libraries, loading and preparing historical stock returns and prices, fitting a C-vine copula model to training data, instantiating the `CVineCopStrat` class, generating trading positions using Bollinger bands on test data, and converting these positions into tradeable units against an index. The `to_quantile` function is used for data transformation, and positions are shifted to prevent look-back bias. ```Python # Importing the module and other libraries import pandas as pd import numpy as np from arbitragelab.copula_approach.vinecop_generate import CVineCop from arbitragelab.copula_approach.vinecop_strategy import CVineCopStrat from arbitragelab.copula_approach.copula_calculation import to_quantile # Loading stocks data. Use 1 cohort for example: suppose stocks 'AAPL', 'MSFT', 'AMZN', 'FB' # form the cohort, and 'AAPL' is the target stock. sp500_returns = pd.read_csv('all_sp500_returns.csv', index_col='Dates', parse_dates=True) returns_train = sp500_returns[['AAPL', 'MSFT', 'AMZN', 'FB']][:800] returns_test = sp500_returns[['AAPL', 'MSFT', 'AMZN', 'FB']][800:1100] prices_aapl_spy = pd.read_csv('all_sp500_prices.csv', index_col='Dates', parse_dates=True)[['AAPL', 'SPY']][800:1100] rts_train_quantiles, cdfs = to_quantile(returns_train) rts_test_quantiles, _ = to_quantile(returns_train) # Instantiate a CVineCop (C-vine copula) class to fit cvinecop = CVineCop() # Fit C-vine automatically, 'AAPL' is the target stock # Note that pv_target_idx is indexed from 1 vinecop_structure = cvinecop.fit_auto(data=rts_train_quantiles, pv_target_idx=1, if_renew=True) # Print the vine copula structure as a sanity check. You can directly fit internally by just # using cvinecop.fit_auto(data=rts_train_quantiles, pv_target_idx=1, if_renew=True) if you # do not want to print structures. print(vinecop_structure) # Instantiate a CVineCopStrat (trading) class from the fitted C-vine copula cvstrat = CVineCopStrat(cvinecop) # Generate positions over the test data, return the Bollinger band for sanity check # Note that the cdfs should be from the training set. positions, bband = cvstrat.get_positions_bollinger(returns=returns_test, cdfs=cdfs, if_return_bollinger_band=True) positions = positions.shift(1) # Avoid look-back bias # Formulate units from the positions against the SPY index, with 100,000 dollar investment units = cvstrat.positions_to_units_against_index(target_stock_prices=prices_aapl_spy['AAPL'], index_prices=prices_aapl_spy['SPY'], positions=positions, multiplier=100000) ``` -------------------------------- ### Demonstrating Hedge Ratio Calculations with ArbitrageLab in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/hedge_ratios/hedge_ratios.rst This comprehensive example demonstrates how to fetch financial time series data and apply various hedge ratio calculation methods provided by the ArbitrageLab library. It showcases the usage of `get_ols_hedge_ratio`, `get_tls_hedge_ratio`, `get_johansen_hedge_ratio`, `get_box_tiao_hedge_ratio`, and `get_minimum_hl_hedge_ratio` to determine hedge ratios for a GLD/GDX spread, printing the results for each method. ```Python import pandas as pd import numpy as np from arbitragelab.hedge_ratios import ( get_ols_hedge_ratio, get_tls_hedge_ratio, get_johansen_hedge_ratio, get_box_tiao_hedge_ratio, get_minimum_hl_hedge_ratio, get_adf_optimal_hedge_ratio, ) # Fetch time series of asset prices url = "https://raw.githubusercontent.com/hudson-and-thames/example-data/main/arbitrage_lab_data/gld_gdx_data.csv" data = pd.read_csv(url, index_col=0, parse_dates=[0]) ols_hedge_ratio, _, _, _ = get_ols_hedge_ratio( data, dependent_variable="GLD", add_constant=False ) print(f"OLS hedge ratio for GLD/GDX spread is {ols_hedge_ratio}") tls_hedge_ratio, _, _, _ = get_tls_hedge_ratio(data, dependent_variable="GLD") print(f"TLS hedge ratio for GLD/GDX spread is {tls_hedge_ratio}") joh_hedge_ratio, _, _, _ = get_johansen_hedge_ratio(data, dependent_variable="GLD") print( f"Johansen hedge ratio for GLD/GDX spread is {joh_hedge_ratio}" ) box_tiao_hedge_ratio, _, _, _ = get_box_tiao_hedge_ratio(data, dependent_variable="GLD") print( f"Box-Tiao hedge ratio for GLD/GDX spread is {box_tiao_hedge_ratio}" ) hl_hedge_ratio, _, _, _, opt_object = get_minimum_hl_hedge_ratio( data, dependent_variable="GLD" ) print( f"Minimum HL hedge ratio for GLD/GDX spread is {hl_hedge_ratio}" ) ``` -------------------------------- ### Selecting Pairs with HSelection based on H-inversion in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/time_series_approach/h_strategy.rst This example illustrates the usage of the `HSelection` class to identify optimal pairs for trading. It involves fetching historical adjusted close prices for multiple tickers, initializing `HSelection` with the dataset, calculating H-inversion statistics for all possible pairs, and then retrieving the top N pairs based on the highest H-inversion values. The structure of the returned pair information, including H-inversion, threshold, and asset names, is also demonstrated. ```Python import pandas as pd import numpy as np import matplotlib.pyplot as plt import yfinance as yf from arbitragelab.time_series_approach.h_strategy import HSelection # Fetch data tickers = "AAPL MSFT AMZN META GOOGL GOOG TSLA NVDA JPM" data = yf.download(tickers, start="2019-01-01", end="2020-12-31", progress=False)[ "Adj Close" ] hs = HSelection(data) hs.select() # Calculate H-inversion statistic pairs = hs.get_pairs(5, "highest", False) # Inspect the first pair # Each pair contains [H-inversion statistic, H-construction threshold, Asset pair] ``` -------------------------------- ### Calculating Optimal OU Process Trading Thresholds and Metrics in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/time_series_approach/ou_optimal_threshold_bertram.rst This example demonstrates how to initialize an Ornstein-Uhlenbeck (OU) process model, calculate optimal entry and exit thresholds by maximizing either expected return or Sharpe ratio, and then compute associated performance metrics like expected return, return variance, and Sharpe ratio. It requires the `arbitragelab` library and uses `numpy` and `matplotlib` for potential future plotting. The `c` parameter represents transaction cost, and `rf` is the risk-free rate. ```Python import numpy as np import matplotlib.pyplot as plt from arbitragelab.time_series_approach.ou_optimal_threshold_bertram import ( OUModelOptimalThresholdBertram, ) OUOTB = OUModelOptimalThresholdBertram() # Init the OU-process parameter OUOTB.construct_ou_model_from_given_parameters(theta=0, mu=180.9670, sigma=0.1538) # Get optimal thresholds by maximizing the expected return a, m = OUOTB.get_threshold_by_maximize_expected_return(c=0.001) # Threshold when we enter a trade a # Threshold when we exit the trade m # Get the expected return and the variance expected_return = OUOTB.expected_return(a=a, m=m, c=0.001) expected_return return_variance = OUOTB.return_variance(a=a, m=m, c=0.001) return_variance # Get optimal thresholds by maximizing the Sharpe ratio a, m = OUOTB.get_threshold_by_maximize_sharpe_ratio(c=0.001, rf=0.01) a m # Get the Sharpe ratio S = OUOTB.sharpe_ratio(a=a, m=m, c=0.001, rf=0.01) S # Set an array of transaction costs ``` -------------------------------- ### Cloning ArbitrageLab Repository - Bash Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/CONTRIBUTING.md This command clones the forked ArbitrageLab repository from GitHub to your local machine and then navigates into the newly cloned directory, preparing it for local development. Replace 'your_username' with your actual GitHub username. ```bash git clone https://github.com/your_username/arbitragelab.git cd arbitragelab ``` -------------------------------- ### Importing Libraries and Initializing OUModelOptimalThresholdZeng in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/time_series_approach/ou_optimal_threshold_zeng.rst This snippet imports necessary libraries like numpy, matplotlib, and the `OUModelOptimalThresholdZeng` class from `arbitragelab`. It then initializes an instance of `OUModelOptimalThresholdZeng` to prepare for OU-process parameter construction and subsequent threshold calculations. ```Python import numpy as np import matplotlib.pyplot as plt from arbitragelab.time_series_approach.ou_optimal_threshold_zeng import ( OUModelOptimalThresholdZeng, ) ouotz = OUModelOptimalThresholdZeng() ``` -------------------------------- ### Opening OU Process Article Link with JavaScript Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/cointegration_approach/minimum_profit_simulation.rst This JavaScript snippet is triggered by a button click and opens a new browser tab/window to the 'Caveats in Calibrating the OU Process' article on the Hudson & Thames website. It uses `window.open` to navigate to the specified URL. ```JavaScript window.open('https://hudsonthames.org/caveats-in-calibrating-the-ou-process/','_blank') ``` -------------------------------- ### Initializing, Fitting, and Evaluating OU Model Mudchanatongsuk (Python) Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/stochastic_control_approach/ou_model_mudchanatongsuk.rst This code initializes the `OUModelMudchanatongsuk` class, then fits the model using the training dataframe (`data_train_dataframe`). It prints the estimated model parameters using the `describe()` method and finally plots the optimal portfolio weights calculated from the out-of-sample test data. ```Python from arbitragelab.stochastic_control_approach.ou_model_mudchanatongsuk import OUModelMudchanatongsuk sc = OUModelMudchanatongsuk() sc.fit(data_train_dataframe) print(sc.describe()) plt.plot(sc.optimal_portfolio_weights(data_test_dataframe)) plt.show() ``` -------------------------------- ### Example Usage of ExponentialOrnsteinUhlenbeck Model in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/optimal_mean_reversion/xou_model.rst This example demonstrates the end-to-end usage of the `ExponentialOrnsteinUhlenbeck` class. It covers simulating an Ornstein-Uhlenbeck process, fitting the model to the simulated data, and then calculating and displaying optimal liquidation, entry, and switching levels. It showcases how to use `xou_optimal_liquidation_level`, `xou_optimal_entry_interval`, `optimal_switching_levels`, `xou_plot_levels`, and `xou_description` methods. ```Python import numpy as np from arbitragelab.optimal_mean_reversion import ExponentialOrnsteinUhlenbeck example = ExponentialOrnsteinUhlenbeck() # We establish our training sample delta_t = 1/252 np.random.seed(30) xou_example = example.ou_model_simulation(n=1000, theta_given=1, mu_given=0.6, sigma_given=0.2, delta_t_given=delta_t) # Model fitting example.fit(xou_example, data_frequency="D", discount_rate=0.05, transaction_cost=[0.02, 0.02]) # You can separately solve optimal stopping # and optimal switching problems # Solving the optimal stopping problem b = example.xou_optimal_liquidation_level() a,d = example.xou_optimal_entry_interval() # Solving the optimal switching problem d_switch, b_switch = example.optimal_switching_levels() # You can display the results using the plot fig = example.xou_plot_levels(np.exp(xou_example), switching=True) # Or you can view the model statistics example.xou_description(switching=True) ``` -------------------------------- ### Loading Data and Initializing SparseMeanReversionPortfolio in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/cointegration_approach/sparse_mr_portfolio.rst This snippet demonstrates how to load financial time series data using pandas and initialize the SparseMeanReversionPortfolio class from the arbitragelab library. It imports essential packages, reads a CSV file into a DataFrame, sets the 'Date' column as the index, and then creates an instance of the portfolio optimization class with the prepared data. ```Python # Importing packages import pandas as pd import networkx as nx import numpy as np import matplotlib.pyplot as plt from arbitragelab.cointegration_approach.sparse_mr_portfolio import SparseMeanReversionPortfolio # Read price series data, set date as index data = pd.read_csv('X_FILE_PATH.csv', parse_dates=['Date']) data.set_index('Date', inplace=True) # Initialize the sparse mean-reverting portfolio searching class sparse_portf = SparseMeanReversionPortfolio(data) ``` -------------------------------- ### Inspecting DataFrame Head in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/time_series_approach/quantile_time_series_strategy.rst This snippet demonstrates how to view the first few rows of a Pandas Series or DataFrame named `positions` in a Python interactive session, often used for quick data inspection. The `[:3]` slice retrieves the first three elements, and the surrounding context indicates it's part of a testable example. ```Python positions[:3] ``` -------------------------------- ### Applying VolatilityFilter in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/ml_approach/filters.rst This snippet demonstrates how to import necessary packages, load time series data from a CSV, initialize the `VolatilityFilter` with a specified lookback period, apply the filter to a spread series using `fit_transform`, and then plot the results. It showcases the typical workflow for using the `VolatilityFilter` class. ```Python # Importing packages import pandas as pd from arbitragelab.ml_approach.filters import VolatilityFilter # Getting the dataframe with time series of asset returns data = pd.read_csv('X_FILE_PATH.csv', index_col=0, parse_dates = [0]) spread_series = data['spread'] # Initialize VolatilityFilter a 30 period lookback parameter. vol_filter = VolatilityFilter(lookback=30) vol_events = vol_filter.fit_transform(spread_series) # Plotting results vol_filter.plot() ``` -------------------------------- ### Fitting and Using OUModelJurek for Portfolio Weights (Python) Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/stochastic_control_approach/ou_model_jurek.rst This code initializes the `OUModelJurek` class, fits the model to training data, prints a description of the estimated parameters, and then plots the optimal portfolio weights calculated using out-of-sample test data with specified fund flow parameters. ```Python from arbitragelab.stochastic_control_approach.ou_model_jurek import OUModelJurek sc = OUModelJurek() sc.fit(data_train_dataframe) print(sc.describe()) plt.plot(sc.optimal_portfolio_weights_fund_flows(data_test_dataframe, f=0.05, gamma=0.5)) plt.show() ``` -------------------------------- ### Example Usage of Cox-Ingersoll-Ross Model Functions - Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/optimal_mean_reversion/cir_model.rst This snippet demonstrates the end-to-end usage of the `CoxIngersollRoss` class, including simulating CIR data, fitting the model, solving for optimal stopping and switching levels, plotting results, and viewing model statistics. It showcases how to apply the theoretical concepts in a practical Python environment. ```Python import numpy as np from arbitragelab.optimal_mean_reversion import CoxIngersollRoss example = CoxIngersollRoss() # We establish our training sample delta_t = 1/252 np.random.seed(30) cir_example = example.cir_model_simulation(n=1000, theta_given=0.2, mu_given=0.2, sigma_given=0.3, delta_t_given=delta_t) # Model fitting example.fit(cir_example, data_frequency="D", discount_rate=0.05, transaction_cost=[0.001, 0.001]) # You can separately solve optimal stopping # and optimal switching problems # Solving the optimal stopping problem b = example.optimal_liquidation_level() d = example.optimal_entry_level() # Solving the optimal switching problem d_switch, b_switch = example.optimal_switching_levels() # You can display the results using the plot fig = example.cir_plot_levels(cir_example, switching=True) # Or you can view the model statistics example.cir_description(switching=True) ``` -------------------------------- ### Opening Raw Documentation PDF - JavaScript Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/developer/debugging.rst This JavaScript snippet is triggered on button click and opens the raw documentation PDF file in a new browser tab. It uses the `window.open()` method, specifying the PDF URL and `_blank` to ensure it opens in a new window. ```JavaScript window.open('https://hudsonthames.org/other/arbitragelab_raw_docs.pdf','_blank') ``` -------------------------------- ### Opening UML Diagram Zip - JavaScript Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/developer/debugging.rst This JavaScript snippet is triggered on button click and opens the UML diagram zip file in a new browser tab. It uses the `window.open()` method, specifying the zip URL and `_blank` to ensure it opens in a new window. ```JavaScript window.open('https://hudsonthames.org/other/arbitragelab_uml.zip','_blank') ``` -------------------------------- ### Applying Crude Oil Futures Rollover in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/data/futures_rollover.rst This snippet demonstrates how to use the CrudeOilFutureRoller from arbitragelab to create a continuous futures price series. It shows fitting the roller to historical data, transforming it to get gaps, and then adjusting the original series. It also illustrates how to handle negative rolled contract values and how to use the diagnostic_summary function for verification. ```Python # Importing packages from arbitragelab.util.rollers import * # Getting the dataframe with time series of continous future prices. data = pd.read_csv('X_FILE_PATH.csv', index_col=0, parse_dates = [0]) # Fit corresponding roller and retrieve gaps. wti_roller = CrudeOilFutureRoller().fit(data) wti_gaps = wti_roller.transform() # Store forward rolled series. rolled_contract = cl_df['PX_LAST'] - wti_gaps # Sometimes rolled contracts dip into negative territory. This # can cause problems when used for ml models, thus there is the # ability to use the parameter 'handle_negative_roll', which # will process the price data into positive returns data. non_negative_contract = wti_roller.transform(handle_negative_roll=True) # The diagnostic summary is a helper function to help the user # easily double-check expiration dates and their respective gap # calculations. wti_diag_frame = wti_roller.diagnostic_summary() wti_diag_frame.head(10) ``` -------------------------------- ### HTML Buttons for Notebook and Sample Data Download Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/time_series_approach/ou_optimal_threshold_bertram.rst This HTML snippet provides two buttons for users to download a research notebook and sample data related to the OU model. Each button is styled with inline CSS for margin control. ```HTML ``` -------------------------------- ### Fitting OrnsteinUhlenbeck Model with DataFrame and Stop-Loss - Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/optimal_mean_reversion/ou_model.rst This example demonstrates fitting the OrnsteinUhlenbeck model using a pd.DataFrame (data_train_dataframe) for training. It configures data frequency, transaction costs, discount rates, and a stop-loss level. The model's fit is checked, and optimal levels are plotted against an out-of-sample dataset (data_oos), explicitly showing the stop-loss effect. ```python from arbitragelab.optimal_mean_reversion import OrnsteinUhlenbeck # Create the class object example = OrnsteinUhlenbeck() # Fit the model to the training data and allocate data frequency, # transaction costs, discount rates and stop-loss level # Chosen data type can be pd.DataFrame example.fit(data_train_dataframe, data_frequency="D", discount_rate=[0.05, 0.05], transaction_cost=[0.02, 0.02], stop_loss=0.2) # Check the model fit print(example.check_fit()) # Showcase the data for both variations of the problem on the out of sample data fig = example.plot_levels(data_oos, stop_loss=True) fig.set_figheight(15) fig.set_figwidth(10) ``` -------------------------------- ### Calculating Dependence and Distance Matrices with ArbitrageLab in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/codependence/codependence_matrix.rst This Python example illustrates the usage of `arbitragelab.codependence` functions to compute financial asset relationships. It demonstrates how to load asset returns using `pandas`, calculate a distance correlation matrix with `get_dependence_matrix`, and derive an absolute angular distance matrix from a standard Pearson correlation, showcasing the module's capabilities for advanced quantitative analysis. ```Python import pandas as pd from arbitragelab.codependence import (get_dependence_matrix, get_distance_matrix) # Import dataframe of returns for assets in a portfolio asset_returns = pd.read_csv(DATA_PATH, index_col='Date', parse_dates=True) # Calculate distance correlation matrix distance_corr = get_dependence_matrix(asset_returns, dependence_method='distance_correlation') # Calculate Pearson correlation matrix pearson_corr = asset_returns.corr() # Calculate absolute angular distance from a Pearson correlation matrix abs_angular_dist = absolute_angular_distance(pearson_corr) ``` -------------------------------- ### Calculating Optimal Transport Dependence in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/codependence/optimal_transport.rst This Python example demonstrates how to use the `arbitragelab.codependence` module to calculate optimal copula transport dependence. It shows how to compute dependence between two specific assets using different target copulas (Gaussian, comonotonicity) and how to generate a full dependence matrix for all assets using a positive-negative target copula. It requires a pandas DataFrame of time series returns as input. ```Python import pandas as pd from arbitragelab.codependence import (optimal_transport_dependence, get_dependence_matrix) # Getting the dataframe with time series of returns data = pd.read_csv('X_FILE_PATH.csv', index_col=0, parse_dates = [0]) element_x = 'SPY' element_y = 'TLT' # Calculating the optimal copula transport dependence between chosen assets # using Gaussian target copula with correlation 0.6 ot_gaussian = optimal_transport_dependence(data[element_x], data[element_y], target_dependence='gaussian', gaussian_corr=0.7) # Calculating the optimal copula transport dependence between chosen assets # using comonotonicity target copula with correlation 0.6 ot_comonotonicity = optimal_transport_dependence(data[element_x], data[element_y], target_dependence='comonotonicity', gaussian_corr=0.7) # Calculating the optimal copula transport dependence between all assets # using positive-negative target copula ot_matrix_posneg = get_dependence_matrix(data, dependence_method='optimal_transport', target_dependence='positive_negative') ``` -------------------------------- ### Styling Download Button for Raw Documentation - CSS Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/developer/debugging.rst This CSS defines the visual appearance and interactive hover effects for the 'Download Raw Documentation' button. It styles the button's background, text, font, padding, and width, and includes an arrow animation on hover to enhance user experience. ```CSS .special { display: inline-block; background-color: #0399AB; color: #eeeeee; text-align: center; font-size: 180%; padding: 15px; width: 100%; transition: all 0.5s; cursor: pointer; font-family: 'Josefin Sans'; } .special span { cursor: pointer; display: inline-block; position: relative; transition: 0.5s; } .special span:after { content: '\00bb'; position: absolute; opacity: 0; top: 0; right: -20px; transition: 0.5s; } .special:hover { background-color: #e7f2fa; color: #000000; } .special:hover span { padding-right: 25px; } .special:hover span:after { opacity: 1; right: 0; } ``` -------------------------------- ### Retraining OrnsteinUhlenbeck Model with Time-Sliced DataFrame - Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/optimal_mean_reversion/ou_model.rst This example illustrates fitting the OrnsteinUhlenbeck model using a pd.DataFrame (data_train_dataframe) but specifying a training time interval. It demonstrates how to dynamically change model parameters like the stop-loss level (example.L) after initial fitting. The description() function is used to inspect model parameters, and the model is retrained on a new time slice using fit_to_assets(). ```python from arbitragelab.optimal_mean_reversion import OrnsteinUhlenbeck # Create the class object example = OrnsteinUhlenbeck() # Fit the model to the training data and allocate data frequency, # transaction costs, discount rates and stop-loss level # We can specify the interval we want to use for training example.fit(data_train_dataframe, data_frequency="D", discount_rate=[0.05, 0.05], start="2012-03-27", end="2013-12-08", transaction_cost=[0.02, 0.02], stop_loss=0.2) # Check the model fit print(example.check_fit(),"\n") # Stop-loss level, transaction costs and discount rates # can be changed along the way example.L = 0.3 # Call the description function to see all the model's parameters and optimal levels print("Model description:\n",example.description()) # Retrain the model # By changing the training interval example.fit_to_assets(start="2015-08-25", end="2016-12-09") ``` -------------------------------- ### Preparing Financial Data for Mean Reversion Model - Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/optimal_mean_reversion/ou_model.rst This snippet demonstrates how to download historical stock data for GLD and GDX using yfinance and prepare it for mean reversion analysis. It creates both pandas DataFrames (data_train_dataframe) and NumPy arrays (data_train) from the 'Adj Close' prices, along with a separate out-of-sample dataset (data_oos). These prepared datasets are essential inputs for the OrnsteinUhlenbeck model examples. ```python data1 = yf.download("GLD GDX", start="2012-03-25", end="2016-01-09") data2 = yf.download("GLD GDX", start="2016-02-21", end="2020-08-15") # You can use the pd.DataFrame of two asset prices data_train_dataframe = data1["Adj Close"][["GLD", "GDX"]] # And also we can create training dataset as an array of two asset prices data_train = np.array(data1["Adj Close"][["GLD", "GDX"]]) # Create an out-of-sample dataset data_oos = data2["Adj Close"][["GLD", "GDX"]] ``` -------------------------------- ### Demonstrating Gumbel and Student Copula Usage in Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/copula_approach/copula_deeper_intro.rst This snippet imports Gumbel and Student copula classes, initializes a Gumbel copula, and demonstrates its core methods like `describe`, `get_cop_density`, `get_cop_eval`, `get_condi_prob`, `sample`, and `fit`. It also shows how to fit the `nu` parameter for a Student copula using `fit_nu_for_t_copula` and then initialize and fit a Student copula. ```Python # Importing the functionality from arbitragelab.copula_approach.archimedean import Gumbel from arbitragelab.copula_approach.elliptical import StudentCopula, fit_nu_for_t_copula cop = Gumbel(theta=2) # Check copula description descr = cop.describe() # Get cdf, pdf, conditional cdf cdf = cop.get_cop_density(0.5, 0.7) pdf = cop.get_cop_eval(0.5, 0.7) cond_cdf = cop.get_condi_prob(0.5, 0.7) # Sample from copula sample = cop.sample(num=100) # Fit copula to some data cop.fit([0.5, 0.2, 0.3, 0.2, 0.1, 0.99], [0.1, 0.02, 0.9, 0.22, 0.11, 0.79]) print(cop.theta) # Generate copula plots cop.plot_scatter(200) cop.plot_pdf('3d') cop.plot_pdf('contour') cop.plot_cdf('3d') cop.plot_cdf('contour') # Creating Student copula nu = fit_nu_for_t_copula([0.5, 0.2, 0.3, 0.2, 0.1, 0.99], [0.1, 0.02, 0.9, 0.22, 0.11, 0.79]) student_cop = StudentCopula(nu=nu, cov=None) student_cop.fit([0.5, 0.2, 0.3, 0.2, 0.1, 0.99], [0.1, 0.02, 0.9, 0.22, 0.11, 0.79]) ``` -------------------------------- ### Fitting and Retraining OrnsteinUhlenbeck Model with NumPy Array - Python Source: https://github.com/hudson-and-thames/arbitragelab/blob/master/docs/source/optimal_mean_reversion/ou_model.rst This example demonstrates fitting the OrnsteinUhlenbeck model using a np.array (data_train) as input, without explicitly setting a stop-loss level during initial fit. It shows how to calculate various optimal levels (entry, liquidation, with stop-loss considerations) and inspect model parameters using description(). The model is then retrained using an out-of-sample dataset (data_oos) to demonstrate dynamic data input changes. ```python from arbitragelab.optimal_mean_reversion import OrnsteinUhlenbeck # Create the class object example = OrnsteinUhlenbeck() # Fit the model to the training data and allocate data frequency, # transaction costs, discount rates and stop-loss level # You can input the np.array as data example.fit(data_train, data_frequency="D", discount_rate=[0.05, 0.05], transaction_cost=[0.02, 0.02], stop_loss=0.2) # Check the model fit print(example.check_fit(),"\n") # Calculate the optimal liquidation level b = example.optimal_entry_level() # Calculate the optimal entry level d = example.optimal_entry_level() # Calculate the optimal liquidation level accounting for stop-loss b_L = example.optimal_liquidation_level_stop_loss() # Calculate the optimal entry interval accounting for stop-loss d_L = example.optimal_entry_interval_stop_loss() # Call the description function to see all the model's parameters and optimal levels print("Model description:\n",example.description()) # Showcase the data for both variations of the problem on the out of sample data fig = example.plot_levels(data_oos) fig.set_figheight(15) fig.set_figwidth(10) # Retrain the model # By changing the input data example.fit_to_assets(data=data_oos) # Check the model fit print(example.check_fit(),"\n") ```