initial import: etf strategy project

This commit is contained in:
2026-03-13 17:10:49 +08:00
commit 79ea983ca3
123 changed files with 6398 additions and 0 deletions

0
web/db.sqlite3 Normal file
View File

23
web/django.log Normal file
View File

@@ -0,0 +1,23 @@
[06/Mar/2026 16:51:04] "GET /lab/top-trials?limit=3 HTTP/1.1" 200 5202
[06/Mar/2026 16:51:04] "GET /lab/best-artifacts?limit=1 HTTP/1.1" 200 5103
[06/Mar/2026 16:52:31] "GET /lab/top-trials HTTP/1.1" 200 22279
Not Found: /favicon.ico
[06/Mar/2026 16:52:32] "GET /favicon.ico HTTP/1.1" 404 2643
[06/Mar/2026 16:53:04] "GET / HTTP/1.1" 200 395
[06/Mar/2026 16:53:06] "GET /lab/best-artifacts HTTP/1.1" 200 5103
[06/Mar/2026 16:53:09] "GET / HTTP/1.1" 200 395
[06/Mar/2026 16:53:11] "GET /lab/top-trials HTTP/1.1" 200 22279
[06/Mar/2026 16:53:40] "GET / HTTP/1.1" 200 395
[06/Mar/2026 16:53:42] "GET /lab/top-trials HTTP/1.1" 200 22279
[06/Mar/2026 16:53:43] "GET / HTTP/1.1" 200 395
[06/Mar/2026 16:53:44] "GET /lab/best-artifacts HTTP/1.1" 200 5103
[06/Mar/2026 16:54:01] "GET / HTTP/1.1" 200 395
[07/Mar/2026 08:00:05] "GET / HTTP/1.1" 200 395
[07/Mar/2026 08:06:46] "GET / HTTP/1.1" 200 395
[07/Mar/2026 08:07:44] "GET / HTTP/1.1" 200 395
[07/Mar/2026 08:08:43] "GET /lab/top-trials HTTP/1.1" 200 22445
[07/Mar/2026 08:09:07] "GET / HTTP/1.1" 200 395
[07/Mar/2026 08:24:56] "GET / HTTP/1.1" 200 395
[09/Mar/2026 16:39:05] "GET / HTTP/1.1" 200 395
[09/Mar/2026 16:39:08] "GET / HTTP/1.1" 200 395
[11/Mar/2026 15:40:28] "GET / HTTP/1.1" 200 395

1
web/django.pid Normal file
View File

@@ -0,0 +1 @@
1503125

0
web/lab/__init__.py Normal file
View File

3
web/lab/admin.py Normal file
View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
web/lab/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class LabConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'lab'

View File

3
web/lab/models.py Normal file
View File

@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

View File

@@ -0,0 +1,43 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Best Artifacts</title>
<style>
table{border-collapse:collapse}
td,th{border:1px solid #ddd;padding:6px;font-family:ui-monospace,monospace;font-size:12px;vertical-align:top}
code{font-size:11px}
pre{margin:0;white-space:pre-wrap;max-width:900px}
</style>
</head>
<body>
<h1>Best Artifacts</h1>
<p>limit={{ limit }}</p>
<p><a href="/">Home</a></p>
<table>
<thead>
<tr>
<th>id</th><th>ts_utc</th><th>ann_return</th><th>ann_vol</th><th>max_dd</th><th>tpy</th>
<th>equity</th><th>weights</th><th>trades</th><th>config</th><th>params</th>
</tr>
</thead>
<tbody>
{% for r in rows %}
<tr>
<td>{{ r.id }}</td>
<td>{{ r.ts_utc }}</td>
<td>{{ r.ann_return }}</td>
<td>{{ r.ann_vol }}</td>
<td>{{ r.max_drawdown }}</td>
<td>{{ r.trades_per_year }}</td>
<td><code>{{ r.out_equity }}</code></td>
<td><code>{{ r.out_weights }}</code></td>
<td><code>{{ r.out_trades }}</code></td>
<td><code>{{ r.config_path }}</code></td>
<td><pre>{{ r.params_json }}</pre></td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

View File

@@ -0,0 +1,15 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>QFR Lab</title>
</head>
<body>
<h1>QFR Lab</h1>
<p>Experiments DB: <code>{{ db_path }}</code></p>
<ul>
<li><a href="/lab/top-trials">Top trials</a></li>
<li><a href="/lab/best-artifacts">Best artifacts</a></li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,42 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Top Trials</title>
<style>
table{border-collapse:collapse}
td,th{border:1px solid #ddd;padding:6px;font-family:ui-monospace,monospace;font-size:12px;vertical-align:top}
code{font-size:11px}
</style>
</head>
<body>
<h1>Top Trials (ann_return)</h1>
<p>Summary: {{ summary }}</p>
<p>limit={{ limit }}</p>
<p><a href="/">Home</a></p>
<table>
<thead>
<tr>
<th>id</th>
<th>ann_return</th><th>ann_vol</th><th>max_drawdown</th><th>sharpe</th><th>tpy</th>
<th>ts_utc</th><th>run_id</th><th>config</th>
</tr>
</thead>
<tbody>
{% for r in rows %}
<tr>
<td>{{ r.id }}</td>
<td>{{ r.ann_return }}</td>
<td>{{ r.ann_vol }}</td>
<td>{{ r.max_drawdown }}</td>
<td>{{ r.sharpe }}</td>
<td>{{ r.trades_per_year }}</td>
<td>{{ r.ts_utc }}</td>
<td><code>{{ r.run_id }}</code></td>
<td><code>{{ r.config_path }}</code></td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

3
web/lab/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

11
web/lab/urls.py Normal file
View File

@@ -0,0 +1,11 @@
from __future__ import annotations
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("lab/top-trials", views.top_trials, name="top_trials"),
path("lab/best-artifacts", views.best_artifacts, name="best_artifacts"),
]

113
web/lab/views.py Normal file
View File

@@ -0,0 +1,113 @@
from __future__ import annotations
import sqlite3
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
@dataclass
class TrialRow:
ann_return: float | None
ann_vol: float | None
max_drawdown: float | None
sharpe: float | None
trades_per_year: float | None
ts_utc: str | None
run_id: str | None
config_path: str | None
def _db_path() -> Path:
return Path(getattr(settings, "QFR_EXPERIMENTS_DB"))
def _connect() -> sqlite3.Connection:
con = sqlite3.connect(str(_db_path()))
con.row_factory = sqlite3.Row
return con
def index(request: HttpRequest) -> HttpResponse:
return render(
request,
"lab/index.html",
{
"db_path": str(_db_path()),
},
)
def top_trials(request: HttpRequest) -> HttpResponse:
limit = int(request.GET.get("limit", "50"))
limit = max(10, min(500, limit))
rows: list[dict[str, Any]] = []
summary: dict[str, Any] = {}
with _connect() as con:
cur = con.execute(
"""
SELECT ann_return, ann_vol, max_drawdown, sharpe, trades_per_year, ts_utc, run_id, config_path
FROM trials
WHERE ann_return IS NOT NULL
ORDER BY ann_return DESC
LIMIT ?
""",
(limit,),
)
rows = [dict(r) for r in cur.fetchall()]
cur2 = con.execute(
"""
SELECT
COUNT(*) AS n,
MAX(ann_return) AS best_ann,
MIN(max_drawdown) AS worst_dd,
MIN(trades_per_year) AS min_tpy,
MAX(trades_per_year) AS max_tpy
FROM trials
"""
)
summary = dict(cur2.fetchone())
return render(
request,
"lab/top_trials.html",
{
"rows": rows,
"summary": summary,
"limit": limit,
},
)
def best_artifacts(request: HttpRequest) -> HttpResponse:
limit = int(request.GET.get("limit", "50"))
limit = max(10, min(500, limit))
rows: list[dict[str, Any]] = []
with _connect() as con:
cur = con.execute(
"""
SELECT id, ts_utc, config_path, out_equity, out_weights, out_trades,
ann_return, ann_vol, max_drawdown, trades_per_year, params_json
FROM best_artifacts
ORDER BY id DESC
LIMIT ?
""",
(limit,),
)
rows = [dict(r) for r in cur.fetchall()]
return render(
request,
"lab/best_artifacts.html",
{
"rows": rows,
"limit": limit,
},
)

22
web/manage.py Executable file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qfrweb.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

0
web/qfrweb/__init__.py Normal file
View File

16
web/qfrweb/asgi.py Normal file
View File

@@ -0,0 +1,16 @@
"""
ASGI config for qfrweb project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qfrweb.settings')
application = get_asgi_application()

127
web/qfrweb/settings.py Normal file
View File

@@ -0,0 +1,127 @@
"""
Django settings for qfrweb project.
Generated by 'django-admin startproject' using Django 5.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-mi&&j81fxs8ni#1x%9y64h0^k+&@7xd*=q-5=4_i@+dasay7q1'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = [
"lab",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'qfrweb.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'qfrweb.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# QFR
QFR_EXPERIMENTS_DB = BASE_DIR.parent / 'data' / 'experiments.sqlite'

23
web/qfrweb/urls.py Normal file
View File

@@ -0,0 +1,23 @@
"""
URL configuration for qfrweb project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("", include("lab.urls")),
path('admin/', admin.site.urls),
]

16
web/qfrweb/wsgi.py Normal file
View File

@@ -0,0 +1,16 @@
"""
WSGI config for qfrweb project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qfrweb.settings')
application = get_wsgi_application()