{"id":45764001,"url":"https://github.com/ts-kontakt/antback","last_synced_at":"2026-03-11T07:00:49.219Z","repository":{"id":306896160,"uuid":"1026880567","full_name":"ts-kontakt/antback","owner":"ts-kontakt","description":"Fast, Transparent Backtesting","archived":false,"fork":false,"pushed_at":"2025-10-11T15:20:32.000Z","size":2247,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-10-11T16:27:43.614Z","etag":null,"topics":["algorithmic-trading","backtesting","event-driven","finance","interactive-reports","trading-strategies"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ts-kontakt.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-07-26T20:15:33.000Z","updated_at":"2025-10-11T15:20:35.000Z","dependencies_parsed_at":"2025-09-08T15:23:02.192Z","dependency_job_id":"e71e6363-d239-4bad-8d6f-89a8576befd2","html_url":"https://github.com/ts-kontakt/antback","commit_stats":null,"previous_names":["ts-kontakt/antback"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ts-kontakt/antback","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-kontakt%2Fantback","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-kontakt%2Fantback/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-kontakt%2Fantback/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-kontakt%2Fantback/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ts-kontakt","download_url":"https://codeload.github.com/ts-kontakt/antback/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-kontakt%2Fantback/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30373505,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-11T06:09:32.197Z","status":"ssl_error","status_checked_at":"2026-03-11T06:09:17.086Z","response_time":84,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["algorithmic-trading","backtesting","event-driven","finance","interactive-reports","trading-strategies"],"created_at":"2026-02-26T00:00:28.306Z","updated_at":"2026-03-11T07:00:49.200Z","avatar_url":"https://github.com/ts-kontakt.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":["Trading \u0026 Backtesting"],"readme":"# Antback\n[![PyPI version](https://img.shields.io/pypi/v/antback.svg)](https://pypi.org/project/antback/)\n\n**Antback: Fast, Transparent, and Debuggable Backtesting**\n\nA lightweight, event-loop-style backtest engine that allows a function-driven imperative style using efficient stateful helper functions and data containers.\n\n## Key Features\n- **Transparency**: Every step is visible and debuggable. No black-box logic.\n- **Balances simplicity with robustness** - ideal for rapid strategy prototyping.\n- **Interactive HTML Reports**: Detailed reports with sorting and filtering capabilities via DataTables.\n- **High Performance**: Optimized data structures for speed - very fast.\n- **Easy to use with different data sources** - only needs `date` and `price` values.\n-  **Avoids Lookahead Bias**: by processing data sequentially. Use wait functions to enforce delays between signals.\n\n\n## Installation\n\nA key feature is the generation of interactive HTML reports, which allow for easy inspection of trades. The lightweight [df2tables](https://github.com/ts-kontakt/df2tables) module is used for this purpose. For Excel reports, [xlreport](https://github.com/ts-kontakt/xlreport) is used.\n\nSo the full install command is:\n```bash\npip install antback\n```\n\n### Demo\n```python\nimport antback as ab\nab.demo()\n```\nThe demo feature generates random trades of several stocks at random prices and generates an interactive report. A profit is slightly more likely than a loss - *it's a demo, after all*.\n\n## Quick Start\n\n### Simple SMA Crossover Strategy\n\n```python\nimport yfinance as yf\nimport antback as ab\n\nsymbol = \"QQQ\"\nfast_period, slow_period = 10, 30\n\n# Download historical data\ndata = yf.Ticker(symbol).history(period=\"10y\")\n\nport = ab.Portfolio(10_000, single=True)\n\n# Initialize rolling price list to store recent prices\nprices = ab.RollingList(maxlen=slow_period)\n\n# Create crossover detection function\ncross = ab.new_cross_func()\n\n# Main trading loop - iterate through historical prices\nfor date, price in data[\"Close\"].items():\n\n    prices.append(price)\n    price_history = prices.values()\n    signal = \"update\" # Default signal: just update portfolio position with current price\n    \n    # Only calculate moving averages once we have enough data\n    if len(price_history) == slow_period:\n        \n        # moving averages using built-in functions only\n        fast_ma = sum(price_history[-fast_period:]) / fast_period\n        # No need for slicing since price_history maxlen equals slow_period\n        slow_ma = sum(price_history) / slow_period\n        \n        # Detect crossover: returns \"up\" when fast crosses above slow, \"down\" when below\n        direction = cross(fast_ma, slow_ma)\n\n        if direction == \"up\":\n            signal = \"buy\"   # Fast MA crossed above slow MA (bullish)\n        elif direction == \"down\":\n            signal = \"sell\"  # Fast MA crossed below slow MA (bearish)\n    \n    # Execute trading signal (buy, sell, or update position)\n    port.process(signal, symbol, date, price)\n\n# Display basic performance metrics in console\nport.basic_report(show=True)\n\n# Generate detailed HTML report\nport.full_report(outfile=f\"Portfolio_report.html\", title=f\"SMA Crossover on {symbol}\")\n\n```\n### Full report screenshot (html)\n*Excel version is also avaliable*\n\n![Report](https://github.com/ts-kontakt/antback/blob/main/antback-report.png?raw=true)\n\n**Interactive filtering trades** (default html report)\n\n\u003cimg src=\"https://github.com/ts-kontakt/antback/blob/main/filter_trades.gif?raw=true\" alt=\"Interactive trade filtering demo\" width=\"600\" height=\"auto\"\u003e\n\n### Generate excel report\n```\nport.full_report('excel', outfile=f'{descr}_report.xlsx', title=descr)\n```\nSee detailed [excel report](https://github.com/ts-kontakt/antback/blob/main/examples/portfolio-report.xlsx) generated with above example.\n\n\u003e **Optimization**: In fact, the average lengths in this case are slightly optimized; see: [examples/08_optimization.py](https://github.com/ts-kontakt/antback/blob/main/examples/08_optimization.py).\n\u003e The results may be even better if [trailing ATR stop](https://github.com/ts-kontakt/antback/blob/main/examples/04_atr_stop.py) is used for the sell signal instead of the averages.\n\n## Core Components\n### Portfolio Class\n\nThe main trading engine that handles position management, trade execution, and performance tracking:\n\n```python\nport = ab.Portfolio(\n    cash=10_000,              \n    single=True,     # Single asset mode - default\n    warn=False,               \n    allow_fractional=False,   \n    fees=0.0015              \n)\n```\n\n**Trading Patterns:**\n- ```port.process(signal, symbol, date, price)```\n\nSignal can be `buy`, `sell` or `None` (also explicit `update`)\n\nExample:\n```python\n...\nif direction == \"up\":\n    signal = 'buy'\nelif direction == \"down\":\n    signal = 'sell'\nport.process(signal, symbol, date, price)\n```\nMethods can be also called directly: `port.buy()`, `port.sell()`, `port.update()` \n\nSee [06_simple_2_assets_rotation.py](https://github.com/ts-kontakt/antback/blob/main/examples/06_simple_2_assets_rotation.py).\n\n**Important Notes**\n- **No re-buying or re-selling**: Duplicate signals are ignored (set `warn=True` to see warnings)\n- **Multi-position support** - Currently supported with manual trade sizing via `fixed_val` parameter. (set single=False, [example](https://github.com/ts-kontakt/antback/blob/main/examples/07_faber_assets_rotation.py) ). \n- **Long-only**: Currently, only long positions are possible.\n\n### CFDAccount Class\n\nTrading engine for CFD  and FX trading with margin requirements, leverage, and both long/short positions:\n\n```python\ncfd = ab.CFDAccount(\n    cash=50_000,              \n    margin_requirement=0.1,   # Required margin as fraction (0.1 = 10%)\n    leverage=2,               \n    warn=False,               \n    allow_fractional=True,    \n    fees=0.00015,           \n    margin_call_level=0.5 \n)\n```\n [long/short example - intraday BTC 15min](https://github.com/ts-kontakt/antback/blob/main/examples/09_intraday_long_short_btc.py)\n\n\n**CFD Trading Patterns:**\n```python\n# Long position\ncfd.process(\"long\", symbol, date, price)\n\n# Short position  \ncfd.process(\"short\", symbol, date, price)\n\n# Close current position\ncfd.process(\"close\", symbol, date, price)\n\n# Update position value\ncfd.process(None, symbol, date, price)  # or \"update\"\n```\n**Key CFD Features:**\n- **Long and short positions**\n- **Only single position at time is supported**\n- **Margin trading**: backtest with leverage while managing margin requirements\n\n## More Examples \u0026 Use Cases\nExplore the [examples](examples/) to see Antback in action - from basic strategies to  multi-asset rotations.\n\n## Useful functions\n### Cross Function\n\n```new_cross_func()``` returns a stateful crossover detector function that tracks when one time series crosses another.\n\n\u003e **ℹ️ Note:** In most cases, the **active** series is a *shorter time frame* indicator compared to the **passive** series. This means it reacts faster to changes, making crossovers more responsive.\n\nThe returned function compares an **active** and **passive** series value at each call and returns:\n- **`up`** when the **active** value moves from below to above the **passive** value\n- **`down`** when the **active** value moves from above to below the **passive** value\n- `None` if there's no crossover or insufficient data\n\n### Wait Functions - Preventing Lookahead Bias\n\nExample use of a wait function.\n\n```python\nsell_timer = ab.new_wait_n_bars(4) # wait 4 bars, then sell\n\nfor date, price in data:\n    signal = None\n    ready_to_sell = sell_timer(bar=date)\n    if ready_to_sell:\n        signal = 'sell'\n    if buy_conditon:\n        signal = 'buy'\n        sell_timer(start=True)\n    port.process(signal, symbol, date, price)\n```\nSee examples [05_easter_effect_test.py](https://github.com/ts-kontakt/antback/blob/main/examples/05_easter_effect_test.py).\n\nThere is also a per-ticker wait version (new_multi_ticker_wait) that creates separate functions for each symbol:\n[wait demo](https://github.com/ts-kontakt/antback/blob/main/examples/12_wait_example.py)\n\n\n### Optimized Data Structures\n\n#### RollingArray\nFast numpy-based rolling window  (Uses manual slice assignment ([:] = [...])\tIn-place operation; avoids temporary memory allocations. \ncan be 2 to 10 times faster than np.roll. Best suited for numeric data.\n```python\nprices = ab.RollingArray(window_size=50)\nprices.append(new_price)\nprice_history = prices.values()\n```\n\n#### RollingList  \nAn efficient, deque-based container for arbitrary objects (e.g., candle objects):\n```python\nprices = ab.RollingList(maxlen=30)\nprices.append(price_data)\nrecent_prices = prices.values()\n```\n#### Multi-ticker strategies\n\nFor more advanced multi-ticker strategies or those using machine learning, it's often necessary to track more than a few dozen rolling features. The ```NamedRollingArrays``` and ```PerTickerNamedRollingArrays``` classes are available for this purpose ([rolling demo](https://github.com/ts-kontakt/antback/blob/main/examples/13_demo_rolling.py)).\n\n\n### Performance \u0026 Technical Indicators\n\nAntback does not include its own indicators (except for clousure based SMA and ATR functions), but you can use any technical analysis (TA) library. Antback is most suitable with event-driven technical indicators. For optimal performance, [talipp](https://github.com/nardew/talipp) indicators, which is designed for streaming data may be used:\n\n```python\nfrom talipp.indicators import SMA\n\nfast_sma, slow_sma = SMA(period=10), SMA(period=30)\n\nfor date, price in data.items():\n    fast_sma.add(price)\n    slow_sma.add(price)\n    \n    if fast_sma[-1] and slow_sma[-1]:  # Check if indicators have valid data\n        signal = determine_signal(fast_sma[-1], slow_sma[-1])\n```\n### Performance\n\nAlthough Antback was not specifically designed for speed, it is **surprisingly fast**. Run the benchmark included with the examples (30-year SPY moving average crossover and BTC-USD intraday 10min).\n\n- [benchmark EOD](https://github.com/ts-kontakt/antback/blob/main/examples/10_simple_benchmark.py) \n- [benchmark intraday](https://github.com/ts-kontakt/antback/blob/main/examples/11_intraday_benchmark_vectorbt.py)\n\n### Disclaimer \u0026 Warning\n\nThis library is provided for educational and research purposes only. It is not intended for live trading or financial advice.\n\n**Backtesting results are hypothetical and do not guarantee future performance.** Markets are unpredictable, and using this library may result in financial losses.\n\nUse this library at your own risk — the author is not responsible for any losses or damages.\n\n\n## License\nMIT\n\n---\n*Perfect for teaching, prototyping, and production backtesting. Excellent clarity and control per bar.*\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fts-kontakt%2Fantback","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fts-kontakt%2Fantback","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fts-kontakt%2Fantback/lists"}