Skip to content

Commit 8d5d7c5

Browse files
feat: optimised volatility benchmark performance
* feat: optimize idiosyncratic volatility factor using vectorized covariance operations * feat: Reorder imports in benchmark_factors.py * feat: refactor volatility factors for production readiness Enhanced volatility factor implementations for production use, including improved initialization, handling of edge cases, and consistent DataFrame outputs. Closes issue #15
1 parent f981e2c commit 8d5d7c5

File tree

4 files changed

+420
-108
lines changed

4 files changed

+420
-108
lines changed

src/quant_research_starter.egg-info/PKG-INFO

Lines changed: 159 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -43,24 +43,43 @@ Dynamic: license-file
4343

4444
# QuantResearchStarter
4545

46-
A modular, open-source quantitative research and backtesting framework designed for clarity and extensibility. Perfect for researchers, students, and developers interested in quantitative finance.
47-
48-
![Python Version](https://img.shields.io/badge/python-3.10%2B-blue)
49-
![License](https://img.shields.io/badge/license-MIT-green)
46+
[![Python Version](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/)
47+
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)
5048
[![CI](https://github.com/username/QuantResearchStarter/actions/workflows/ci.yml/badge.svg)](https://github.com/username/QuantResearchStarter/actions)
5149

52-
## Features
50+
A modular, open-source quantitative research and backtesting framework built for clarity, reproducibility, and extensibility. Ideal for researchers, students, and engineers building and testing systematic strategies.
51+
52+
---
53+
54+
## Why this project
55+
56+
QuantResearchStarter aims to provide a clean, well-documented starting point for quantitative research and backtesting. It focuses on:
57+
58+
* **Readability**: idiomatic Python, type hints, and small modules you can read and change quickly.
59+
* **Testability**: deterministic vectorized backtests with unit tests and CI.
60+
* **Extensibility**: plug-in friendly factor & data adapters so you can try new ideas fast.
61+
62+
---
63+
64+
## Key features
5365

54-
- **Data Management**: Download real data or generate synthetic data for testing
55-
- **Factor Library**: Implement momentum, value, size, and volatility factors
56-
- **Backtesting Engine**: Vectorized backtester with transaction costs and constraints
57-
- **Risk Metrics**: Comprehensive performance and risk analytics
58-
- **Modular Design**: Easy to extend with new factors and strategies
59-
- **Production Ready**: Type hints, tests, CI/CD, and documentation
66+
* **Data management** — download market data or generate synthetic price series for experiments.
67+
* **Factor library** — example implementations of momentum, value, size, and volatility factors.
68+
* **Vectorized backtesting engine** — supports transaction costs, slippage, and portfolio constraints.
69+
* **Risk & performance analytics** — returns, drawdowns, Sharpe, turnover, and other risk metrics.
70+
* **CLI & scripts** — small tools to generate data, compute factors, and run backtests from the terminal.
71+
* **Production-ready utilities** — type hints, tests, continuous integration, and documentation scaffolding.
6072

61-
## Quick Start
73+
---
6274

63-
### Installation
75+
## Quick start
76+
77+
### Requirements
78+
79+
* Python 3.10+
80+
* pip
81+
82+
### Install locally
6483

6584
```bash
6685
# Clone the repository
@@ -70,5 +89,131 @@ cd QuantResearchStarter
7089
# Install package in development mode
7190
pip install -e .
7291

73-
# Install development dependencies
92+
# Install development dependencies (tests, linters, docs)
7493
pip install -e ".[dev]"
94+
95+
# Optional UI dependencies
96+
pip install streamlit plotly
97+
```
98+
99+
### Demo (one-line)
100+
101+
```bash
102+
make demo
103+
```
104+
105+
### Step-by-step demo
106+
107+
```bash
108+
# generate synthetic sample price series
109+
qrs generate-data -o data_sample/sample_prices.csv -s 5 -d 365
110+
111+
# compute example factors
112+
qrs compute-factors -d data_sample/sample_prices.csv -f momentum -f value -o output/factors.csv
113+
114+
# run a backtest
115+
qrs backtest -d data_sample/sample_prices.csv -s output/factors.csv -o output/backtest_results.json
116+
117+
# optional: start the Streamlit dashboard
118+
streamlit run src/quant_research_starter/dashboard/streamlit_app.py
119+
```
120+
121+
---
122+
123+
## Example: small strategy (concept)
124+
125+
```python
126+
from quant_research_starter.backtest import Backtester
127+
from quant_research_starter.data import load_prices
128+
from quant_research_starter.factors import Momentum
129+
130+
prices = load_prices("data_sample/sample_prices.csv")
131+
factor = Momentum(window=63)
132+
scores = factor.compute(prices)
133+
134+
bt = Backtester(prices, signals=scores, capital=1_000_000)
135+
results = bt.run()
136+
print(results.performance.summary())
137+
```
138+
139+
> The code above is illustrative—see `examples/` for fully working notebooks and scripts.
140+
141+
---
142+
143+
## CLI reference
144+
145+
Run `qrs --help` or `qrs <command> --help` for full usage. Main commands include:
146+
147+
* `qrs generate-data` — create synthetic price series or download data from adapters
148+
* `qrs compute-factors` — calculate and export factor scores
149+
* `qrs backtest` — run the vectorized backtest and export results
150+
151+
---
152+
153+
## Project structure (overview)
154+
155+
```
156+
QuantResearchStarter/
157+
├─ src/quant_research_starter/
158+
│ ├─ data/ # data loaders & adapters
159+
│ ├─ factors/ # factor implementations
160+
│ ├─ backtest/ # backtester & portfolio logic
161+
│ ├─ analytics/ # performance and risk metrics
162+
│ ├─ cli/ # command line entry points
163+
│ └─ dashboard/ # optional Streamlit dashboard
164+
├─ examples/ # runnable notebooks & example strategies
165+
├─ tests/ # unit + integration tests
166+
└─ docs/ # documentation source
167+
```
168+
169+
---
170+
171+
## Tests & CI
172+
173+
We include unit tests and a CI workflow (GitHub Actions). Run tests locally with:
174+
175+
```bash
176+
pytest -q
177+
```
178+
179+
The CI pipeline runs linting, unit tests, and builds docs on push/PR.
180+
181+
---
182+
183+
## Contributing
184+
185+
Contributions are very welcome. Please follow these steps:
186+
187+
1. Fork the repository
188+
2. Create a feature branch
189+
3. Add tests for new behavior
190+
4. Open a pull request with a clear description and rationale
191+
192+
Please review `CONTRIBUTING.md` and the `CODE_OF_CONDUCT.md` before submitting.
193+
194+
---
195+
196+
## AI policy — short & practical
197+
198+
**Yes — you are allowed to use AI tools** (ChatGPT, Copilot, Codeium, etc.) to help develop, prototype, or document code in this repository.
199+
200+
A few friendly guidelines:
201+
202+
* **Be transparent** when a contribution is substantially generated by an AI assistant — add a short note in the PR or commit message (e.g., "Generated with ChatGPT; reviewed and adapted by <your-name>").
203+
* **Review and test** all AI-generated code. Treat it as a helpful draft, not final production-quality code.
204+
* **Follow licensing** and attribution rules for any external snippets the AI suggests. Don’t paste large verbatim copyrighted material.
205+
* **Security & correctness**: double-check numerical logic, data handling, and anything that affects trading decisions.
206+
207+
This policy is intentionally permissive: we want the community to move fast while keeping quality and safety in mind.
208+
209+
---
210+
211+
## License
212+
213+
This project is licensed under the MIT License — see the `LICENSE` file for details.
214+
215+
---
216+
217+
## Acknowledgements
218+
219+
Built with inspiration from open-source quant libraries and the research community. If you use this project in papers or public work, a short citation or mention is appreciated.

src/quant_research_starter.egg-info/SOURCES.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,16 @@ src/quant_research_starter.egg-info/requires.txt
1212
src/quant_research_starter.egg-info/top_level.txt
1313
src/quant_research_starter/backtest/__init__.py
1414
src/quant_research_starter/backtest/vectorized.py
15+
src/quant_research_starter/dashboard/streamlit_app.py
1516
src/quant_research_starter/data/__init__.py
1617
src/quant_research_starter/data/downloaders.py
1718
src/quant_research_starter/data/init.py
1819
src/quant_research_starter/data/sample_loader.py
1920
src/quant_research_starter/data/synthetic.py
21+
src/quant_research_starter/examples/benchmark/benchmark_factors.py
2022
src/quant_research_starter/factors/__init__.py
2123
src/quant_research_starter/factors/base.py
24+
src/quant_research_starter/factors/bollinger.py
2225
src/quant_research_starter/factors/init.py
2326
src/quant_research_starter/factors/momentum.py
2427
src/quant_research_starter/factors/size.py
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
Benchmark script to compare performance of factor computations.
3+
4+
Usage:
5+
python examples/benchmarks/benchmark_factors.py
6+
"""
7+
8+
import time
9+
10+
import numpy as np
11+
import pandas as pd
12+
13+
from quant_research_starter.factors import (
14+
BollingerBandsFactor,
15+
IdiosyncraticVolatility,
16+
MomentumFactor,
17+
SizeFactor,
18+
ValueFactor,
19+
VolatilityFactor,
20+
)
21+
22+
23+
def generate_synthetic_prices(
24+
n_assets: int = 500, n_days: int = 252 * 3
25+
) -> pd.DataFrame:
26+
"""Generate synthetic random walk price data for testing."""
27+
np.random.seed(42)
28+
returns = np.random.normal(0, 0.01, size=(n_days, n_assets))
29+
prices = 100 * np.exp(np.cumsum(returns, axis=0))
30+
dates = pd.date_range(end=pd.Timestamp.today(), periods=n_days, freq="B")
31+
tickers = [f"Stock_{i:03d}" for i in range(n_assets)]
32+
return pd.DataFrame(prices, index=dates, columns=tickers)
33+
34+
35+
def benchmark_factor(factor, prices: pd.DataFrame):
36+
"""Benchmark runtime of a given factor."""
37+
start = time.time()
38+
_ = factor.compute(prices)
39+
end = time.time()
40+
elapsed = end - start
41+
print(
42+
f"{factor.name:<25} | Lookback: {factor.lookback:<5} | Time: {elapsed:.3f} sec"
43+
)
44+
45+
46+
def main():
47+
print("Generating synthetic data...")
48+
prices = generate_synthetic_prices(n_assets=500, n_days=252 * 3)
49+
print(f"Data shape: {prices.shape}")
50+
51+
print("\nRunning factor benchmarks...\n")
52+
53+
factors = [
54+
MomentumFactor(lookback=63),
55+
ValueFactor(),
56+
SizeFactor(),
57+
VolatilityFactor(lookback=21),
58+
IdiosyncraticVolatility(lookback=63),
59+
BollingerBandsFactor(lookback=20),
60+
]
61+
62+
for factor in factors:
63+
benchmark_factor(factor, prices)
64+
65+
66+
if __name__ == "__main__":
67+
main()

0 commit comments

Comments
 (0)