{"id":28487632,"url":"https://github.com/logarithm-labs/fractal-defi","last_synced_at":"2026-05-01T06:01:17.533Z","repository":{"id":246388607,"uuid":"820989741","full_name":"Logarithm-Labs/fractal-defi","owner":"Logarithm-Labs","description":"The ultimate DeFi research Python library for strategy building.","archived":false,"fork":false,"pushed_at":"2025-05-15T15:33:14.000Z","size":1678,"stargazers_count":31,"open_issues_count":8,"forks_count":8,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-06-22T15:05:22.192Z","etag":null,"topics":["aiagents","backtesting","defi","python","python3","uniswap"],"latest_commit_sha":null,"homepage":"https://logarithm-labs.gitbook.io/fractal","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Logarithm-Labs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-06-27T15:25:24.000Z","updated_at":"2025-06-08T04:26:55.000Z","dependencies_parsed_at":"2024-07-08T19:52:51.123Z","dependency_job_id":"2f4f5950-a294-4f44-95e0-7b17bdc23551","html_url":"https://github.com/Logarithm-Labs/fractal-defi","commit_stats":null,"previous_names":["logarithm-labs/fractal-defi","logarithm-labs/fractal"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Logarithm-Labs/fractal-defi","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Logarithm-Labs%2Ffractal-defi","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Logarithm-Labs%2Ffractal-defi/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Logarithm-Labs%2Ffractal-defi/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Logarithm-Labs%2Ffractal-defi/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Logarithm-Labs","download_url":"https://codeload.github.com/Logarithm-Labs/fractal-defi/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Logarithm-Labs%2Ffractal-defi/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":261311751,"owners_count":23139482,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aiagents","backtesting","defi","python","python3","uniswap"],"created_at":"2025-06-08T04:32:19.382Z","updated_at":"2026-05-01T06:01:17.524Z","avatar_url":"https://github.com/Logarithm-Labs.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Fractal\n\n[![CI](https://github.com/Logarithm-Labs/fractal-defi/actions/workflows/ci.yml/badge.svg)](https://github.com/Logarithm-Labs/fractal-defi/actions/workflows/ci.yml)\n[![PyPI version](https://badge.fury.io/py/fractal-defi.svg)](https://badge.fury.io/py/fractal-defi)\n[![Python Versions](https://img.shields.io/pypi/pyversions/fractal-defi.svg)](https://pypi.org/project/fractal-defi/)\n[![License: BSD 3-Clause](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)\n[![Downloads](https://pepy.tech/badge/fractal-defi)](https://pepy.tech/project/fractal-defi)\n[![Downloads](https://pepy.tech/badge/fractal-defi/month)](https://pepy.tech/project/fractal-defi)\n\n**Fractal** — open-source Python research library for DeFi strategies.\nCompose protocol-agnostic entities (lending, perps, DEX and LP) into\ntyped strategies; backtest, simulate, track experiments.\n\n## Why Fractal\n\nMost DeFi backtesters are product-shaped: pick a protocol, run a\nstrategy, get a P\u0026L curve. Fractal is library-shaped — small primitives\nwith a big composition surface. You write a strategy once against the\ngeneric `BasePerpEntity` / `BaseLendingEntity` / `BasePoolEntity` /\n`BaseSpotEntity` contracts and swap concrete implementations\n(Hyperliquid, Aave, Uniswap V3, GMX, your own) without touching the\nstrategy code.\n\n## Features\n\n- **Protocol-agnostic entities.** Concrete implementations for Aave V3\n  lending, Hyperliquid perps, Uniswap V2/V3 LP and spot, Lido stETH,\n  plus generic `Simple*` building blocks. Each entity is a typed state\n  machine with `update_state` for accruals and protocol-correct\n  `action_*` methods.\n- **Composable strategies.** Register any number of entities under\n  named slots, return `ActionToTake` from a single `predict()` hook,\n  get a typed `StrategyResult` with metrics and a flat DataFrame.\n- **Live + synthetic data.** Loaders for Binance public REST,\n  Hyperliquid info API, Aave V3 GraphQL, GMX, TheGraph (Uniswap V2/V3,\n  Lido), plus log-normal GBM and bootstrap simulators for offline\n  stress tests.\n- **Experiment tracking.** `DefaultPipeline` runs your strategy across\n  a parameter grid, logs metrics + artifacts per run via MLflow, and\n  supports sliding-window scenarios for stability analysis.\n- **Type-safe and dev-friendly.** `BaseStrategy[Params]` generic +\n  dataclass coercion, atomic per-action validation, delegate-resolved\n  action arguments, deterministic replay.\n- **Battle-tested.** 1100+ unit / invariant / real-data / integration\n  tests, plus a Docker-based end-to-end MLflow harness in\n  `tests/mlflow_tests/`.\n\n## Structure\n\n```\nfractal/\n├── core/\n│   ├── base/           # Entity / Strategy / Observation contracts\n│   ├── entities/       # Aave, Hyperliquid, Uniswap V2/V3, stETH, simple/*\n│   └── pipeline.py     # MLflow grid-search pipelines\n├── loaders/            # Binance / Hyperliquid / Aave / GMX / TheGraph / sims\n└── strategies/         # BasisTrading, HyperliquidBasis, TauReset\nexamples/               # quick_start, basis, tau_reset, holder, agentic_trader\ndocs/                   # Sphinx site (make html)\ntests/\n├── core/               # offline unit + invariant + e2e synthetic\n├── loaders/            # real-API loader tests\n└── mlflow_tests/       # Docker MLflow + end-to-end pipeline scripts\n```\n\n## Install\n\n```bash\npip install fractal-defi\n```\n\nOr from source (latest unreleased ``dev`` branch):\n\n```bash\ngit clone https://github.com/Logarithm-Labs/fractal-defi.git\ncd fractal-defi\npip install .\n```\n\nRequires Python 3.10–3.13.\n\nContributors and anyone running the test suite want the editable\ninstall with the dev extras (pulls in pytest, pylint, flake8, isort,\npre-commit, sphinx). See [`CONTRIBUTING.md`](CONTRIBUTING.md):\n\n```bash\npip install -e \".[dev]\"\npre-commit install\n```\n\n## Quick start\n\nA passive Aave-style lender accruing 5% APY for a year, no network or\nMLflow needed. After installing, write the file below as\n`quick_start.py` and run it:\n\n```python\nfrom dataclasses import dataclass\nfrom datetime import UTC, datetime, timedelta\nfrom typing import List\n\nfrom fractal.core.base import (Action, ActionToTake, BaseStrategy,\n                               BaseStrategyParams, NamedEntity, Observation)\nfrom fractal.core.entities import SimpleLendingEntity, SimpleLendingGlobalState\n\n\n@dataclass\nclass LendingParams(BaseStrategyParams):\n    INITIAL_BALANCE: float = 10_000.0\n    LENDING_APY: float = 0.05\n\n\nclass PassiveLender(BaseStrategy[LendingParams]):\n    def set_up(self) -\u003e None:\n        self.register_entity(NamedEntity(\"LENDING\", SimpleLendingEntity()))\n        self._funded = False\n\n    def predict(self) -\u003e List[ActionToTake]:\n        if self._funded:\n            return []\n        self._funded = True\n        return [ActionToTake(\"LENDING\", Action(\n            \"deposit\", {\"amount_in_notional\": self._params.INITIAL_BALANCE},\n        ))]\n\n\nhours = 365 * 24\nstart = datetime(2024, 1, 1, tzinfo=UTC)\nobservations = [\n    Observation(timestamp=start + timedelta(hours=i), states={\n        \"LENDING\": SimpleLendingGlobalState(\n            collateral_price=1.0, debt_price=1.0,\n            lending_rate=0.05 / hours, borrowing_rate=0.0,\n        ),\n    })\n    for i in range(hours + 1)\n]\n\nresult = PassiveLender(params=LendingParams()).run(observations)\nprint(result.get_default_metrics())\n```\n\n```\nStrategyMetrics(accumulated_return=0.05127, apy=0.05127, sharpe=0.0, max_drawdown=0.0)\n```\n\nThe same script lives at [`examples/quick_start.py`](examples/quick_start.py)\nin the repo. The repo also ships heavier examples covering basis trading,\nLP rebalancing, agentic trading and a toy hodler — see below.\n\n## Examples\n\n| Path | What it shows |\n|---|---|\n| [`examples/quick_start.py`](examples/quick_start.py) | Hello-Fractal: passive lending with hourly compounding |\n| [`examples/holder/`](examples/holder/) | Toy spot HODL with simple buy / sell triggers |\n| [`examples/basis/`](examples/basis/) | Hyperliquid basis trade — perp short hedged against spot long |\n| [`examples/tau_reset/`](examples/tau_reset/) | Active Uniswap V3 LP with τ-reset rebalancing |\n| [`examples/agentic_trader/`](examples/agentic_trader/) | LLM-driven trading agent over historical klines |\n\nAfter cloning the repo and installing the package, run an example\ndirectly:\n\n```bash\npython examples/quick_start.py\npython examples/basis/backtest.py\npython examples/tau_reset/backtest.py\n```\n\nThe grid-search variants (`examples/\u003cname\u003e/grid.py`) log results to\nMLflow. The repo ships a self-contained Docker MLflow stack — bring it\nup, point your shell at it, run the grid:\n\n```bash\nbash tests/mlflow_tests/scripts/start_mlflow.sh   # MLflow on :5500\nexport MLFLOW_URI=http://localhost:5500\npython examples/basis/grid.py\n```\n\n## Documentation\n\n- [`ARCHITECTURE.md`](ARCHITECTURE.md) — entity-as-state-machine\n  semantics, the `InternalState` / `GlobalState` split,\n  delegate-resolved actions, notional accounting, pipeline internals.\n- [`CHANGELOG.md`](CHANGELOG.md) — release notes.\n- [`CONTRIBUTING.md`](CONTRIBUTING.md) — setup, branching, the\n  testing pyramid, the pre-commit / CI pipeline. Required reading\n  before opening a PR.\n- Sphinx API reference can be built locally from the repo\n  (`make docs`); a hosted version is on the project's docs site.\n\n## License\n\nBSD 3-Clause. See [`LICENSE`](LICENSE).\n\nBuilt by [Logarithm Labs](https://github.com/Logarithm-Labs).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flogarithm-labs%2Ffractal-defi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flogarithm-labs%2Ffractal-defi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flogarithm-labs%2Ffractal-defi/lists"}