|
| 1 | +import numpy as np |
| 2 | +import pandas as pd |
| 3 | + |
| 4 | +from typing import List |
| 5 | +from datetime import datetime, UTC |
| 6 | +from sklearn.model_selection import ParameterGrid |
| 7 | + |
| 8 | +from fractal.loaders import PriceHistory, RateHistory |
| 9 | +from fractal.loaders import HyperliquidFundingRatesLoader, HyperLiquidPerpsPricesLoader |
| 10 | + |
| 11 | +from fractal.core.base import Observation |
| 12 | +from fractal.core.pipeline import ( |
| 13 | + DefaultPipeline, MLFlowConfig, ExperimentConfig) |
| 14 | +from fractal.core.entities import UniswapV3LPGlobalState, HyperLiquidGlobalState |
| 15 | + |
| 16 | +from fractal.strategies.hyperliquid_basis import HyperliquidBasis |
| 17 | + |
| 18 | + |
| 19 | +def get_observations( |
| 20 | + rate_data: RateHistory, price_data: PriceHistory, |
| 21 | + start_time: datetime = None, end_time: datetime = None |
| 22 | + ) -> List[Observation]: |
| 23 | + """ |
| 24 | + Get observations from the pool and price data for the ManagedBasisStrategy. |
| 25 | +
|
| 26 | + Returns: |
| 27 | + List[Observation]: The observation list for ManagedBasisStrategy. |
| 28 | + """ |
| 29 | + observations_df: pd.DataFrame = price_data.join(rate_data) |
| 30 | + observations_df['rate'] = observations_df['rate'].fillna(0) |
| 31 | + observations_df = observations_df.loc[start_time:end_time] |
| 32 | + observations_df = observations_df.dropna() |
| 33 | + start_time = observations_df.index.min() |
| 34 | + if end_time is None: |
| 35 | + end_time = observations_df.index.max() |
| 36 | + observations_df = observations_df.sort_index() |
| 37 | + return [ |
| 38 | + Observation( |
| 39 | + timestamp=timestamp, |
| 40 | + states={ |
| 41 | + 'SPOT': UniswapV3LPGlobalState(price=price, tvl=0, volume=0, fees=0, liquidity=0), # we need only spot price |
| 42 | + 'HEDGE': HyperLiquidGlobalState(mark_price=price, funding_rate=rate) |
| 43 | + } |
| 44 | + ) for timestamp, (price, rate) in observations_df.iterrows() |
| 45 | + ] |
| 46 | + |
| 47 | + |
| 48 | +def build_observations( |
| 49 | + ticker: str, start_time: datetime = None, end_time: datetime = None, |
| 50 | + ) -> List[Observation]: |
| 51 | + """ |
| 52 | + Build observations for the ManagedBasisStrategy from the given start and end time. |
| 53 | + """ |
| 54 | + rate_data: RateHistory = HyperliquidFundingRatesLoader( |
| 55 | + ticker, start_time=start_time, end_time=end_time).read(with_run=True) |
| 56 | + prices: PriceHistory = HyperLiquidPerpsPricesLoader( |
| 57 | + ticker, interval='1h', start_time=start_time, end_time=end_time).read(with_run=True) |
| 58 | + return get_observations(rate_data, prices, start_time, end_time) |
| 59 | + |
| 60 | + |
| 61 | +def build_grid(): |
| 62 | + raw_grid = ParameterGrid({ |
| 63 | + 'MIN_LEVERAGE': np.arange(1, 12, 1).tolist(), |
| 64 | + 'TARGET_LEVERAGE': np.arange(1, 12, 1).tolist(), |
| 65 | + 'MAX_LEVERAGE': np.arange(1, 12, 1).tolist(), |
| 66 | + 'INITIAL_BALANCE': [1_000_000] |
| 67 | + }) |
| 68 | + |
| 69 | + valid_grid = [ |
| 70 | + params for params in raw_grid |
| 71 | + if round(params['MIN_LEVERAGE'], 1) < round(params['TARGET_LEVERAGE'], 1) < round(params['MAX_LEVERAGE'], 1) |
| 72 | + ] |
| 73 | + return valid_grid |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == '__main__': |
| 77 | + # Strategy environment |
| 78 | + ticker: str = 'BTC' |
| 79 | + start_time = datetime(2025, 1, 1, tzinfo=UTC) |
| 80 | + end_time = datetime(2025, 3, 1, tzinfo=UTC) |
| 81 | + experiment_name = f'hl_basis_{ticker}_{start_time.strftime("%Y-%m-%d")}_{end_time.strftime("%Y-%m-%d")}' |
| 82 | + HyperliquidBasis.MAX_LEVERAGE = 45 |
| 83 | + |
| 84 | + # Mlflow setup |
| 85 | + mlflow_config: MLFlowConfig = MLFlowConfig( |
| 86 | + mlflow_uri='http://127.0.01:8080', |
| 87 | + experiment_name=experiment_name, |
| 88 | + ) |
| 89 | + |
| 90 | + # Load data and build observations |
| 91 | + observations = build_observations(ticker, start_time, end_time) |
| 92 | + assert len(observations) > 0 |
| 93 | + |
| 94 | + # Experiment setup |
| 95 | + experiment_config: ExperimentConfig = ExperimentConfig( |
| 96 | + strategy_type=HyperliquidBasis, |
| 97 | + backtest_observations=observations, |
| 98 | + window_size=24, # number of scenarios from history |
| 99 | + params_grid=build_grid(), |
| 100 | + debug=True, |
| 101 | + ) |
| 102 | + |
| 103 | + # Run the DefualtPipeline |
| 104 | + pipeline: DefaultPipeline = DefaultPipeline( |
| 105 | + experiment_config=experiment_config, |
| 106 | + mlflow_config=mlflow_config |
| 107 | + ) |
| 108 | + pipeline.run() |
0 commit comments