Repository Analysis

kernc/backtesting.py

🔎 📈 🐍 💰 Backtest trading strategies in Python.

19.0 Moderate AI signal View on GitHub

Analysis Overview

This report presents the forensic synthetic code analysis of kernc/backtesting.py, a Python project with 8,748 GitHub stars. SynthScan v2.0 examined 8,328 lines of code across 37 source files, recording 98 pattern matches distributed across 13 syntactic categories. The overall adjusted score of 19.0 places this repository in the Moderate AI signal band.

The scanner applied 160+ deterministic lexical heuristics, multi-line block detectors, abstract syntax tree depth profilers, and a cross-file Jaccard similarity matrix to construct a statistically normalised synthetic code estimate. All matches are individually weighted by severity coefficient and contextual multiplier before summation, and the resulting headline score is temporally discounted to account for the repository's development history relative to the commercial emergence of large language model coding tooling (November 2022 onward).

19.0
Adjusted Score
19.0
Raw Score
100%
Time Factor
2026-07-22
Last Push
8.7K
Stars
Python
Language
8.3K
Lines of Code
37
Files
98
Pattern Hits
2026-08-02
Scan Date
0.24
HC Hit Rate

What These Metrics Mean

Adjusted Score
Primary synthetic code indicator. Raw score normalised per 1,000 lines of code and multiplied by the temporal discount factor. This is the definitive comparative metric — use it to rank repositories by AI authorship density.
Raw Score
The unmodified sum of all severity-weighted, context-multiplied pattern match scores before temporal discounting. Reflects the absolute signal strength independent of when the repository was last active.
Time Factor
The temporal discount multiplier (0–100%) applied to the raw score. Repositories last updated before ChatGPT's launch (Nov 2022) receive a 5% factor. Full signal is only assigned to repositories active in the post-adoption era (Jan 2024+).
Pattern Hits
Total count of individual pattern matches across all files and categories. A high hit count with a low score may indicate a very large codebase with isolated AI snippets; a low count with a high score indicates dense, concentrated AI signatures.
HC Hit Rate
High+Critical pattern hits per file, averaged across the repository. This orthogonal signal catches repositories where a few files are densely packed with high-severity AI tells — a strong indicator even when the normalised score appears moderate due to codebase size.
Lines of Code / Files
Total lines and files analysed. The scanner examines 94 file extensions. These denominators are used to normalise the score, enabling fair comparison between repositories of vastly different sizes.

Score History

Longitudinal tracking requires multiple scan runs. Once this repository is re-scanned after new commits land, this chart will visualise how the synthetic code signal evolves over time — enabling you to detect whether AI authorship is growing, stabilising, or being actively corrected by human engineers.

No multi-scan history yet — run the scanner again to build trend data.

Severity Breakdown

Classifies detected patterns by their diagnostic confidence and structural impact. CRITICAL patterns (coefficient 10) represent definitive synthetic signatures — hallucinated imports, explicit LLM attribution metadata — virtually never produced by human authors. HIGH (5) indicates strong structural tells such as cross-file repetition or cross-linguistic idioms. MEDIUM (2) covers recognisable conversational padding and AI-specific vocabulary. LOW (1) captures subtle indicators like tautological comments and generic boilerplate that require density to carry independent signal.

CRITICAL 0HIGH 9MEDIUM 9LOW 80

Directory Score Breakdown

This horizontal bar chart decomposes the repository's raw synthetic code score by top-level directory, allowing you to pinpoint precisely which modules or components carry the highest AI authorship density. Directories with disproportionately high scores relative to their size warrant targeted manual review: concentrated AI signatures often trace back to mass-generated configuration layers, auto-ported test suites, LLM-scaffolded boilerplate classes, or entire subsystems authored under heavy copilot assistance. Use this view to prioritise your human code-review effort.

Pattern Findings

The scanner identified 98 distinct pattern matches across 13 syntactic categories. Each entry below represents a discrete location in the source code where the engine recorded a statistically significant AI authorship indicator. Expand any category row to inspect the individual file paths, line numbers, code snippets, and the lexical context (CODE, COMMENT, or STRING) in which each match was detected.

Reading the findings table: The Severity column indicates the diagnostic confidence level (CRITICAL / HIGH / MEDIUM / LOW). The Context column identifies whether the match occurred inside executable code, an inline comment, or a string literal — comment-context matches receive a ×1.5 weight because LLMs systematically over-annotate. The ⚡ bolt icon marks clustered matches: three or more patterns within a 10-line window, each receiving an additional ×1.5 density multiplier as dense clusters constitute far stronger evidence of synthetic authorship than isolated hits.

Cross-Language Confusion9 hits · 52 pts
SeverityFileLineSnippetContext
HIGHbacktesting/_plotting.py160 assert not indicators or indicators[0].df.index.equals(df.index)CODE
HIGHbacktesting/_plotting.py163 assert equity_data.index.equals(df.index)CODE
HIGHbacktesting/_plotting.py221 assert df.index.equals(results['_equity_curve'].index)CODE
HIGHbacktesting/_plotting.py289this.labels = this.labels || formatter.doFormat(ticksCODE
HIGHbacktesting/_plotting.py291 .filter(t => t !== undefined));CODE
HIGHbacktesting/_plotting.py361 assert equity.index.equals(equity_data.index)STRING
HIGHbacktesting/test/_test.py1124 assert close.s.equals(pd.Series(close, index=index))CODE
HIGHbacktesting/test/_test.py1130 assert close.s.equals(pd.Series(close, index=index))CODE
HIGHbacktesting/test/_test.py309 self.assertTrue(df.equals(EURUSD))CODE
Over-Commented Block24 hits · 24 pts
SeverityFileLineSnippetContext
LOWbacktesting/lib.py261 # Let's convert closing prices back to pandas Series.COMMENT
LOWdoc/examples/Strategies Library.py1# ---COMMENT
LOWdoc/examples/Strategies Library.py21# [basic package usage](https://kernc.github.io/backtesting.py/doc/examples/Quick%20Start%20User%20Guide.html).COMMENT
LOWdoc/examples/Strategies Library.py101# For other strategies of the sort, and other reusable utilities in general, seeCOMMENT
LOWdoc/examples/Quick Start User Guide.py1# ---COMMENT
LOWdoc/examples/Quick Start User Guide.py21# _Backtesting.py_ is a small and lightweight, blazing fast backtesting framework that uses state-of-the-art Python struCOMMENT
LOWdoc/examples/Quick Start User Guide.py41# DataFrame should ideally be indexed with a _datetime index_ (convert it with [`pd.to_datetime()`](https://pandas.pydatCOMMENT
LOWdoc/examples/Quick Start User Guide.py121# [`self.data`](https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.StrategyCOMMENT
LOWdoc/examples/Quick Start User Guide.py141# self.position.close()COMMENT
LOWdoc/examples/Quick Start User Guide.py161from backtesting import BacktestCOMMENT
LOWdoc/examples/Quick Start User Guide.py201# %%COMMENT
LOWdoc/examples/Quick Start User Guide.py221# The columns should be self-explanatory.COMMENT
LOWdoc/examples/Parameter Heatmap & Optimization.py1# -*- coding: utf-8 -*-COMMENT
LOWdoc/examples/Parameter Heatmap & Optimization.py21# It is assumed you're already familiar withCOMMENT
LOWdoc/examples/Parameter Heatmap & Optimization.py121# It makes the function return a heatmap series along with the usual stats of the best run.COMMENT
LOWdoc/examples/Parameter Heatmap & Optimization.py161)COMMENT
LOWdoc/examples/Parameter Heatmap & Optimization.py181# ## Model-based optimizationCOMMENT
LOWdoc/examples/Trading with Machine Learning.py1# ---COMMENT
LOWdoc/examples/Trading with Machine Learning.py21# [basic framework usage](https://kernc.github.io/backtesting.py/doc/examples/Quick%20Start%20User%20Guide.html)COMMENT
LOWdoc/examples/Trading with Machine Learning.py261bt.plot()COMMENT
LOWdoc/examples/Trading with Machine Learning.py281# by increasing the conviction needed and imposing extra domain expertise and discretionary limitations before enterinCOMMENT
LOWdoc/examples/Multiple Time Frames.py1# ---COMMENT
LOWdoc/examples/Multiple Time Frames.py21# [pandas resampling](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling).COMMENT
LOWdoc/examples/Multiple Time Frames.py141# In conclusion, to test strategies on multiple time frames, you need to pass in OHLC data in the lowest time frame, theCOMMENT
Hyper-Verbose Identifiers24 hits · 22 pts
SeverityFileLineSnippetContext
LOWbacktesting/_stats.py14def compute_drawdown_duration_peaks(dd: pd.Series):CODE
LOWbacktesting/test/_test.py1136 def test_indicators_picklable(self):CODE
LOWbacktesting/test/_test.py100 def test_data_missing_columns(self):CODE
LOWbacktesting/test/_test.py238 def test_absolute_size_order_warns_on_insufficient_margin(self):CODE
LOWbacktesting/test/_test.py393 def test_compute_stats_bordercase(self):CODE
LOWbacktesting/test/_test.py426 def test_trade_enter_hit_sl_on_same_day(self):CODE
LOWbacktesting/test/_test.py444 def test_stop_price_between_sl_tp(self):CODE
LOWbacktesting/test/_test.py453 def test_position_close_portion(self):CODE
LOWbacktesting/test/_test.py468 def test_close_orders_from_last_strategy_iteration(self):CODE
LOWbacktesting/test/_test.py480 def test_check_adjusted_price_when_placing_order(self):CODE
LOWbacktesting/test/_test.py533 def test_broker_exclusive_orders(self):CODE
LOWbacktesting/test/_test.py545 def test_trade_multiple_close(self):CODE
LOWbacktesting/test/_test.py566 def test_stop_limit_order_price_is_stop_price(self):CODE
LOWbacktesting/test/_test.py575 def test_autoclose_trades_on_finish(self):CODE
LOWbacktesting/test/_test.py659 def test_optimize_invalid_param(self):CODE
LOWbacktesting/test/_test.py807 def test_resample_trades_vectorized(self):CODE
LOWbacktesting/test/_test.py1160 def test_backtest_run_docstring_contains_stats_keys(self):CODE
LOWbacktesting/test/_test.py1165 def test_readme_contains_stats_keys(self):CODE
LOWbacktesting/test/_test.py1204 def test_trade_on_close_closes_trades_on_close(self):CODE
LOWbacktesting/test/_test.py1239 def test_trades_dates_match_prices(self):CODE
LOWbacktesting/test/_test.py1259 def test_stop_entry_and_tp_in_same_bar(self):CODE
LOWbacktesting/test/_test.py1270 def test_optimize_datetime_index_with_timezone(self):CODE
LOWbacktesting/test/_test.py1276 def test_sl_tp_values_in_trades_df(self):CODE
LOWbacktesting/test/_test.py1287 def test_sl_value_in_trades_df_when_gapped_through(self):CODE
Decorative Section Separators4 hits · 12 pts
SeverityFileLineSnippetContext
MEDIUMdoc/examples/Strategies Library.py17# ======================COMMENT
MEDIUMdoc/examples/Quick Start User Guide.py17# =======================COMMENT
MEDIUMdoc/examples/Parameter Heatmap & Optimization.py18# ==========COMMENT
MEDIUMdoc/examples/Multiple Time Frames.py17# ============COMMENT
AI Slop Vocabulary4 hits · 12 pts
SeverityFileLineSnippetContext
MEDIUMdoc/examples/Strategies Library.py20# It is, henceforth, assumed you're already familiar withCOMMENT
MEDIUMdoc/examples/Quick Start User Guide.py21# _Backtesting.py_ is a small and lightweight, blazing fast backtesting framework that uses state-of-the-art Python struCOMMENT
MEDIUMdoc/examples/Parameter Heatmap & Optimization.py91# It's not a robust strategy, but we can optimize it.COMMENT
MEDIUMdoc/examples/Trading with Machine Learning.py151# Let's backtest a simple strategy that buys the asset for 20% of available equity with 20:1 leverage whenever the forecCOMMENT
Unused Imports10 hits · 10 pts
SeverityFileLineSnippetContext
LOWbacktesting/backtesting.py9CODE
LOWbacktesting/lib.py14CODE
LOWbacktesting/__init__.py68CODE
LOWbacktesting/__init__.py69CODE
LOWbacktesting/__init__.py71CODE
LOWbacktesting/__init__.py71CODE
LOWbacktesting/_plotting.py1CODE
LOWbacktesting/_util.py1CODE
LOWbacktesting/_stats.py1CODE
LOWbacktesting/test/__init__.py3CODE
Deep Nesting9 hits · 9 pts
SeverityFileLineSnippetContext
LOWbacktesting/backtesting.py765CODE
LOWbacktesting/backtesting.py875CODE
LOWbacktesting/backtesting.py1271CODE
LOWbacktesting/backtesting.py1386CODE
LOWbacktesting/backtesting.py1513CODE
LOWbacktesting/lib.py427CODE
LOWbacktesting/_plotting.py198CODE
LOWbacktesting/_plotting.py535CODE
LOWbacktesting/_stats.py37CODE
AI Structural Patterns4 hits · 4 pts
SeverityFileLineSnippetContext
LOWbacktesting/backtesting.py1195CODE
LOWbacktesting/backtesting.py1658CODE
LOWbacktesting/lib.py330CODE
LOWbacktesting/_plotting.py198CODE
Excessive Try-Catch Wrapping3 hits · 4 pts
SeverityFileLineSnippetContext
LOWbacktesting/backtesting.py145 except Exception as e:CODE
LOWbacktesting/_plotting.py152 except Exception:CODE
LOWbacktesting/_util.py304 except Exception:CODE
Redundant / Tautological Comments3 hits · 4 pts
SeverityFileLineSnippetContext
LOWbacktesting/backtesting.py887 # Check if stop condition was hitCOMMENT
LOWbacktesting/backtesting.py899 # Check if limit order can be filled.COMMENT
LOWbacktesting/_plotting.py495 # Check if resampling was downsampling; error on upsamplingSTRING
Self-Referential Comments1 hit · 3 pts
SeverityFileLineSnippetContext
MEDIUMdoc/examples/Quick Start User Guide.py95 # Define the two MA lags as *class variables*COMMENT
Modern Structural Boilerplate2 hits · 2 pts
SeverityFileLineSnippetContext
LOWbacktesting/backtesting.py1772__all__ = [getattr(v, '__name__', k)CODE
LOWbacktesting/lib.py640__all__ = [getattr(v, '__name__', k)CODE
Slop Phrases1 hit · 2 pts
SeverityFileLineSnippetContext
LOWdoc/examples/Trading with Machine Learning.py283# Also make sure to familiarize yourself with the fullCOMMENT