股票中的趋势因子

登录后收藏

Onsite backtest IDE

Quant Buffet 原生回测 IDE

Edit and run Quant Buffet Python for 股票中的趋势因子 in the browser. Results update live with equity, drawdown, and metrics charts. Allowed: backtest.data, backtest.engine, backtest.metrics, numpy, pandas. Define ASSETS and make_on_day(prices). Shortcut: Ctrl+Enter. API docs →

Ready — edit code, then Run backtest.
IDE · 36 lines
Quant Buffet syntax cheat sheet (copy / insert)

Paste these fragments into the editor. The sandbox rejects QuantConnect, os, and network libraries.

Required imports
Only these libraries are allowed in the sandbox.
from __future__ import annotations

import numpy as np
import pandas as pd

from backtest.data import load_daily_prices
from backtest.engine import EngineConfig, PortfolioEngine
from backtest.metrics import compute_metrics
ASSETS list (whitelisted ETFs)
Module-level list. Tickers must be in the Quant Buffet whitelist.
ASSETS = ["SPY", "QQQ", "TLT", "GLD", "BIL"]
make_on_day contract
Must return (on_day, ready). on_day calls engine.set_target_weights.
def make_on_day(prices: pd.DataFrame):
    cols = [c for c in ASSETS if c in prices.columns]
    sma = prices[cols].rolling(200, min_periods=200).mean()
    state = {"last": None}

    def on_day(engine: PortfolioEngine, dt: pd.Timestamp) -> None:
        if sma.loc[dt].isna().all():
            return
        key = (dt.year, dt.month)
        if state["last"] == key:
            return
        state["last"] = key
        long = [
            s for s in cols
            if pd.notna(prices.at[dt, s]) and pd.notna(sma.at[dt, s])
            and prices.at[dt, s] > sma.at[dt, s]
        ]
        weights = {} if not long else {s: 1.0 / len(long) for s in long}
        engine.set_target_weights(dt, weights)

    ready = sma.dropna(how="all").index.min() if sma.notna().any().any() else None
    return on_day, ready
Set target weights
Weights should sum to about 1.0. Empty dict = 100% cash.
engine.set_target_weights(dt, {"SPY": 0.60, "BIL": 0.40})

Live backtest performance

CAGR
6.00%
Sharpe
0.63
Max DD
-18.15%
Vol
10.11%
Sortino
0.93
Beta
0.35
Up days
50%

Run the backtest to populate charts.

Export to your platform

Transform Quant Buffet lab code (ASSETS + make_on_day / PortfolioEngine) into native classes for a third-party IDE — then copy and paste.

Run in: QuantConnect Cloud or LEAN CLI · QCAlgorithm with Equity securities and monthly rebalance.

Detected pattern: Absolute momentumAssets: SPY, TLT, GLD, BIL
# Generated from Quant Buffet → QuantConnect LEAN
# Strategy: 股票中的趋势因子
# Detected pattern: Absolute momentum
# Source uses Quant Buffet lab APIs (ASSETS + make_on_day / PortfolioEngine).
# Review fees, data, and risk before live trading — educational export only.

from AlgorithmImports import *


class QuantBuffetExport(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2010, 1, 1)
        self.SetCash(100000)
        tickers = ["SPY", "TLT", "GLD", "BIL"]
        self.symbols = []
        for t in tickers:
            if "-" in t:  # crypto proxy e.g. BTC-USD
                self.symbols.append(self.AddCrypto(t.replace("-USD", ""), Resolution.Daily).Symbol)
            else:
                self.symbols.append(self.AddEquity(t, Resolution.Daily).Symbol)
        self.Schedule.On(
            self.DateRules.MonthStart(self.symbols[0]),
            self.TimeRules.AfterMarketOpen(self.symbols[0], 30),
            self.Rebalance,
        )
        # Logic: Long assets with positive 252-day return; equal-weight; monthly.

    def Rebalance(self):
        # Pattern: abs_momentum — Long assets with positive 252-day return; equal-weight; monthly.
        # Default: equal-weight. Port your make_on_day weights here via SetHoldings.
        w = 1.0 / len(self.symbols) if self.symbols else 0.0
        for symbol in self.symbols:
            self.SetHoldings(symbol, w)

导出代码使用目标平台的原生类与库。请在第三方 IDE 中安装依赖后运行;实盘前请自行验证。

学术论文

Trend Factor: A New Determinant of Cross-Section Stock Returns

作者趋势因子:横截面股票回报的新决定因素 [点击查看论文]

机构
  • University of North Carolina at Charlotte
  • ?University of North Carolina (UNC) at Charlotte - Finance
  • Washington University in St. Louis
  • ?Washington University in St. Louis - John M. Olin Business School

原文论文截图

Screenshot from the original paper
Screenshot from the original paper

策略概要

该策略的目标是纽约证券交易所、美国证券交易所和纳斯达克的股票,排除封闭式基金、房地产投资信托基金(REITs)、单位信托、美国存托凭证(ADRs)和外国股票。股票按市值排名,仅关注最大的五分之一。每月,使用相对于当月收盘价的股票价格的标准化3日、5日、10日和20日移动平均线构建趋势信号。横截面回归估计将趋势信号与回报联系起来的系数,这些系数在过去12个月内取平均值,以预测下个月的回报。股票按预测回报分为五等分,最高五分之一建立多头头寸,最低五分之一建立空头头寸,每月再平衡。

II. 策略合理性

学术研究假定,股票价格存在强劲趋势的时期,这很可能是由一些持续性和根本性的变化或投资者的反应不足或过度反应引起的。信息不确定性放大了这种效应。

回测表现

年化收益6.00%
波动率10.11%
贝塔0.35
夏普比率0.63
索提诺比率0.93
最大回撤-18.15%
胜率50%