deltafq 0.0.1__py3-none-any.whl → 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of deltafq might be problematic. Click here for more details.

deltafq/__init__.py CHANGED
@@ -0,0 +1,31 @@
1
+ """DeltaFQ - 专业的Python量化交易库
2
+
3
+ 一个面向量化策略开发者和量化研究人员的完整工具链。
4
+ """
5
+
6
+ __version__ = "0.1.1"
7
+ __author__ = "DeltaFQ Team"
8
+
9
+ # 导入主要模块
10
+ from deltafq import data
11
+ from deltafq import indicators
12
+ from deltafq import strategy
13
+ from deltafq import backtest
14
+ from deltafq import risk
15
+ from deltafq import performance
16
+ from deltafq import optimization
17
+ from deltafq import trade
18
+ from deltafq import utils
19
+
20
+ __all__ = [
21
+ "data",
22
+ "indicators",
23
+ "strategy",
24
+ "backtest",
25
+ "risk",
26
+ "performance",
27
+ "optimization",
28
+ "trade",
29
+ "utils",
30
+ ]
31
+
@@ -0,0 +1,7 @@
1
+ """回测引擎模块"""
2
+
3
+ from deltafq.backtest.engine import BacktestEngine
4
+ from deltafq.backtest.result import BacktestResult
5
+
6
+ __all__ = ["BacktestEngine", "BacktestResult"]
7
+
@@ -0,0 +1,52 @@
1
+ """回测引擎"""
2
+
3
+ import pandas as pd
4
+ from typing import Optional
5
+ from deltafq.strategy.base import Strategy
6
+ from deltafq.backtest.result import BacktestResult
7
+
8
+
9
+ class BacktestEngine:
10
+ """回测引擎"""
11
+
12
+ def __init__(
13
+ self,
14
+ initial_cash: float = 100000,
15
+ commission: float = 0.0003,
16
+ slippage: float = 0.0
17
+ ):
18
+ """初始化回测引擎
19
+
20
+ Args:
21
+ initial_cash: 初始资金
22
+ commission: 手续费率
23
+ slippage: 滑点
24
+ """
25
+ self.initial_cash = initial_cash
26
+ self.commission = commission
27
+ self.slippage = slippage
28
+
29
+ def run(
30
+ self,
31
+ data: pd.DataFrame,
32
+ strategy: Strategy
33
+ ) -> BacktestResult:
34
+ """运行回测
35
+
36
+ Args:
37
+ data: 历史数据
38
+ strategy: 策略实例
39
+
40
+ Returns:
41
+ 回测结果
42
+ """
43
+ for idx, bar in data.iterrows():
44
+ strategy.on_bar(bar)
45
+
46
+ result = BacktestResult(
47
+ initial_cash=self.initial_cash,
48
+ data=data,
49
+ signals=strategy.get_signals()
50
+ )
51
+ return result
52
+
@@ -0,0 +1,45 @@
1
+ """回测结果"""
2
+
3
+ import pandas as pd
4
+ from typing import Dict, Any, List
5
+
6
+
7
+ class BacktestResult:
8
+ """回测结果类"""
9
+
10
+ def __init__(
11
+ self,
12
+ initial_cash: float,
13
+ data: pd.DataFrame,
14
+ signals: List[Dict]
15
+ ):
16
+ self.initial_cash = initial_cash
17
+ self.data = data
18
+ self.signals = signals
19
+
20
+ def summary(self) -> Dict[str, Any]:
21
+ """生成回测摘要
22
+
23
+ Returns:
24
+ 包含各项指标的字典
25
+ """
26
+ return {
27
+ 'initial_cash': self.initial_cash,
28
+ 'total_signals': len(self.signals),
29
+ 'data_length': len(self.data),
30
+ }
31
+
32
+ def plot(self) -> None:
33
+ """绘制回测结果"""
34
+ try:
35
+ import matplotlib.pyplot as plt
36
+ plt.figure(figsize=(12, 6))
37
+ plt.plot(self.data['close'])
38
+ plt.title('Price Chart')
39
+ plt.xlabel('Date')
40
+ plt.ylabel('Price')
41
+ plt.grid(True)
42
+ plt.show()
43
+ except ImportError:
44
+ print("需要matplotlib: pip install matplotlib")
45
+
@@ -0,0 +1,7 @@
1
+ """数据获取和管理模块"""
2
+
3
+ from deltafq.data.base import DataSource
4
+ from deltafq.data.loader import get_stock_daily, get_stock_minute
5
+
6
+ __all__ = ["DataSource", "get_stock_daily", "get_stock_minute"]
7
+
deltafq/data/base.py ADDED
@@ -0,0 +1,30 @@
1
+ """数据源基类"""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Optional
5
+ import pandas as pd
6
+
7
+
8
+ class DataSource(ABC):
9
+ """数据源抽象基类"""
10
+
11
+ @abstractmethod
12
+ def get_data(
13
+ self,
14
+ symbol: str,
15
+ start_date: str,
16
+ end_date: str,
17
+ **kwargs
18
+ ) -> pd.DataFrame:
19
+ """获取数据
20
+
21
+ Args:
22
+ symbol: 股票代码
23
+ start_date: 开始日期
24
+ end_date: 结束日期
25
+
26
+ Returns:
27
+ 包含OHLCV数据的DataFrame
28
+ """
29
+ pass
30
+
deltafq/data/loader.py ADDED
@@ -0,0 +1,63 @@
1
+ """数据加载器"""
2
+
3
+ import pandas as pd
4
+ import numpy as np
5
+ from typing import Optional
6
+
7
+
8
+ def get_stock_daily(
9
+ symbol: str,
10
+ start: str,
11
+ end: str,
12
+ source: str = "mock"
13
+ ) -> pd.DataFrame:
14
+ """获取股票日线数据
15
+
16
+ Args:
17
+ symbol: 股票代码
18
+ start: 开始日期
19
+ end: 结束日期
20
+ source: 数据源,目前支持 'mock'
21
+
22
+ Returns:
23
+ 包含OHLCV数据的DataFrame
24
+ """
25
+ dates = pd.date_range(start=start, end=end, freq='B')
26
+ n = len(dates)
27
+ base_price = 100 + np.random.randn(n).cumsum()
28
+ open_price = base_price + np.random.randn(n) * 0.5
29
+ close_price = base_price + np.random.randn(n) * 0.5
30
+ high_price = np.maximum(open_price, close_price) + np.abs(np.random.randn(n) * 0.5)
31
+ low_price = np.minimum(open_price, close_price) - np.abs(np.random.randn(n) * 0.5)
32
+
33
+ data = pd.DataFrame({
34
+ 'open': open_price,
35
+ 'high': high_price,
36
+ 'low': low_price,
37
+ 'close': close_price,
38
+ 'volume': np.random.randint(1000000, 10000000, n),
39
+ }, index=dates)
40
+
41
+ data.index.name = 'date'
42
+ return data
43
+
44
+
45
+ def get_stock_minute(
46
+ symbol: str,
47
+ start: str,
48
+ end: str,
49
+ freq: str = '1min'
50
+ ) -> pd.DataFrame:
51
+ """获取股票分钟数据
52
+
53
+ Args:
54
+ symbol: 股票代码
55
+ start: 开始日期
56
+ end: 结束日期
57
+ freq: 频率,如 '1min', '5min'
58
+
59
+ Returns:
60
+ 包含OHLCV数据的DataFrame
61
+ """
62
+ raise NotImplementedError("分钟数据功能待实现")
63
+
@@ -0,0 +1,8 @@
1
+ """技术指标计算模块"""
2
+
3
+ from deltafq.indicators.trend import SMA, EMA, MACD
4
+ from deltafq.indicators.momentum import RSI
5
+ from deltafq.indicators.volatility import BOLL
6
+
7
+ __all__ = ["SMA", "EMA", "MACD", "RSI", "BOLL"]
8
+
@@ -0,0 +1,23 @@
1
+ """动量类指标"""
2
+
3
+ import pandas as pd
4
+
5
+
6
+ def RSI(data: pd.Series, period: int = 14) -> pd.Series:
7
+ """相对强弱指标
8
+
9
+ Args:
10
+ data: 价格序列
11
+ period: 周期
12
+
13
+ Returns:
14
+ RSI序列
15
+ """
16
+ delta = data.diff()
17
+ gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
18
+ loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
19
+
20
+ rs = gain / loss
21
+ rsi = 100 - (100 / (1 + rs))
22
+ return rsi
23
+
@@ -0,0 +1,61 @@
1
+ """趋势类指标"""
2
+
3
+ import pandas as pd
4
+ from typing import Union
5
+
6
+
7
+ def SMA(data: Union[pd.Series, pd.DataFrame], period: int) -> pd.Series:
8
+ """简单移动平均线
9
+
10
+ Args:
11
+ data: 价格序列
12
+ period: 周期
13
+
14
+ Returns:
15
+ SMA序列
16
+ """
17
+ return data.rolling(window=period).mean()
18
+
19
+
20
+ def EMA(data: Union[pd.Series, pd.DataFrame], period: int) -> pd.Series:
21
+ """指数移动平均线
22
+
23
+ Args:
24
+ data: 价格序列
25
+ period: 周期
26
+
27
+ Returns:
28
+ EMA序列
29
+ """
30
+ return data.ewm(span=period, adjust=False).mean()
31
+
32
+
33
+ def MACD(
34
+ data: pd.Series,
35
+ fast_period: int = 12,
36
+ slow_period: int = 26,
37
+ signal_period: int = 9
38
+ ) -> pd.DataFrame:
39
+ """MACD指标
40
+
41
+ Args:
42
+ data: 价格序列
43
+ fast_period: 快线周期
44
+ slow_period: 慢线周期
45
+ signal_period: 信号线周期
46
+
47
+ Returns:
48
+ 包含DIF、DEA、MACD的DataFrame
49
+ """
50
+ fast = EMA(data, fast_period)
51
+ slow = EMA(data, slow_period)
52
+ dif = fast - slow
53
+ dea = EMA(dif, signal_period)
54
+ macd = (dif - dea) * 2
55
+
56
+ return pd.DataFrame({
57
+ 'dif': dif,
58
+ 'dea': dea,
59
+ 'macd': macd
60
+ })
61
+
@@ -0,0 +1,27 @@
1
+ """波动率类指标"""
2
+
3
+ import pandas as pd
4
+
5
+
6
+ def BOLL(data: pd.Series, period: int = 20, std_dev: float = 2.0) -> pd.DataFrame:
7
+ """布林带
8
+
9
+ Args:
10
+ data: 价格序列
11
+ period: 周期
12
+ std_dev: 标准差倍数
13
+
14
+ Returns:
15
+ 包含upper、middle、lower的DataFrame
16
+ """
17
+ middle = data.rolling(window=period).mean()
18
+ std = data.rolling(window=period).std()
19
+ upper = middle + std_dev * std
20
+ lower = middle - std_dev * std
21
+
22
+ return pd.DataFrame({
23
+ 'upper': upper,
24
+ 'middle': middle,
25
+ 'lower': lower
26
+ })
27
+
@@ -0,0 +1,6 @@
1
+ """参数优化模块"""
2
+
3
+ from deltafq.optimization.grid_search import GridSearchOptimizer
4
+
5
+ __all__ = ["GridSearchOptimizer"]
6
+
@@ -0,0 +1,41 @@
1
+ """网格搜索优化器"""
2
+
3
+ from typing import Dict, List, Any, Callable
4
+ import itertools
5
+
6
+
7
+ class GridSearchOptimizer:
8
+ """网格搜索参数优化器"""
9
+
10
+ def __init__(self):
11
+ self.results = []
12
+
13
+ def optimize(
14
+ self,
15
+ param_grid: Dict[str, List[Any]],
16
+ objective_func: Callable
17
+ ) -> Dict[str, Any]:
18
+ """执行网格搜索
19
+
20
+ Args:
21
+ param_grid: 参数网格
22
+ objective_func: 目标函数
23
+
24
+ Returns:
25
+ 最优参数组合
26
+ """
27
+ keys = param_grid.keys()
28
+ values = param_grid.values()
29
+ best_score = float('-inf')
30
+ best_params = None
31
+
32
+ for combination in itertools.product(*values):
33
+ params = dict(zip(keys, combination))
34
+ score = objective_func(params)
35
+ self.results.append({'params': params, 'score': score})
36
+ if score > best_score:
37
+ best_score = score
38
+ best_params = params
39
+
40
+ return best_params
41
+
@@ -0,0 +1,6 @@
1
+ """绩效分析模块"""
2
+
3
+ from deltafq.performance.metrics import calculate_sharpe_ratio, calculate_annual_return
4
+
5
+ __all__ = ["calculate_sharpe_ratio", "calculate_annual_return"]
6
+
@@ -0,0 +1,37 @@
1
+ """绩效指标计算"""
2
+
3
+ import pandas as pd
4
+ import numpy as np
5
+
6
+
7
+ def calculate_annual_return(returns: pd.Series) -> float:
8
+ """计算年化收益率
9
+
10
+ Args:
11
+ returns: 收益率序列
12
+
13
+ Returns:
14
+ 年化收益率
15
+ """
16
+ total_return = (1 + returns).prod() - 1
17
+ n_years = len(returns) / 252
18
+ annual_return = (1 + total_return) ** (1 / n_years) - 1
19
+ return annual_return
20
+
21
+
22
+ def calculate_sharpe_ratio(
23
+ returns: pd.Series,
24
+ risk_free_rate: float = 0.03
25
+ ) -> float:
26
+ """计算夏普比率
27
+
28
+ Args:
29
+ returns: 收益率序列
30
+ risk_free_rate: 无风险利率
31
+
32
+ Returns:
33
+ 夏普比率
34
+ """
35
+ excess_returns = returns - risk_free_rate / 252
36
+ return np.sqrt(252) * excess_returns.mean() / excess_returns.std()
37
+
@@ -0,0 +1,7 @@
1
+ """风险管理模块"""
2
+
3
+ from deltafq.risk.position import PositionManager
4
+ from deltafq.risk.metrics import calculate_max_drawdown, calculate_var
5
+
6
+ __all__ = ["PositionManager", "calculate_max_drawdown", "calculate_var"]
7
+
@@ -0,0 +1,33 @@
1
+ """风险指标计算"""
2
+
3
+ import pandas as pd
4
+ import numpy as np
5
+
6
+
7
+ def calculate_max_drawdown(returns: pd.Series) -> float:
8
+ """计算最大回撤
9
+
10
+ Args:
11
+ returns: 收益率序列
12
+
13
+ Returns:
14
+ 最大回撤值
15
+ """
16
+ cumulative = (1 + returns).cumprod()
17
+ running_max = cumulative.expanding().max()
18
+ drawdown = (cumulative - running_max) / running_max
19
+ return drawdown.min()
20
+
21
+
22
+ def calculate_var(returns: pd.Series, confidence: float = 0.95) -> float:
23
+ """计算VaR (Value at Risk)
24
+
25
+ Args:
26
+ returns: 收益率序列
27
+ confidence: 置信度
28
+
29
+ Returns:
30
+ VaR值
31
+ """
32
+ return returns.quantile(1 - confidence)
33
+
@@ -0,0 +1,39 @@
1
+ """仓位管理"""
2
+
3
+ from typing import Optional
4
+
5
+
6
+ class PositionManager:
7
+ """仓位管理器"""
8
+
9
+ def __init__(self, max_position: float = 1.0):
10
+ """初始化仓位管理器
11
+
12
+ Args:
13
+ max_position: 最大持仓比例
14
+ """
15
+ self.max_position = max_position
16
+ self.current_position = 0.0
17
+
18
+ def calculate_size(
19
+ self,
20
+ signal: str,
21
+ cash: float,
22
+ price: float,
23
+ method: str = "fixed"
24
+ ) -> float:
25
+ """计算交易数量
26
+
27
+ Args:
28
+ signal: 信号类型 'buy' or 'sell'
29
+ cash: 可用资金
30
+ price: 当前价格
31
+ method: 计算方法
32
+
33
+ Returns:
34
+ 交易数量
35
+ """
36
+ if method == "fixed":
37
+ return cash * self.max_position / price
38
+ return 0.0
39
+
@@ -0,0 +1,6 @@
1
+ """策略框架模块"""
2
+
3
+ from deltafq.strategy.base import Strategy
4
+
5
+ __all__ = ["Strategy"]
6
+
@@ -0,0 +1,44 @@
1
+ """策略基类"""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Dict, Any
5
+ import pandas as pd
6
+
7
+
8
+ class Strategy(ABC):
9
+ """策略抽象基类"""
10
+
11
+ def __init__(self):
12
+ self.position = 0 # 当前持仓
13
+ self.cash = 100000 # 初始资金
14
+ self.signals = [] # 信号记录
15
+
16
+ @abstractmethod
17
+ def on_bar(self, bar: pd.Series) -> None:
18
+ """处理每根K线
19
+
20
+ Args:
21
+ bar: 包含OHLCV数据的Series
22
+ """
23
+ pass
24
+
25
+ def buy(self, size: float = 1.0) -> None:
26
+ """买入信号
27
+
28
+ Args:
29
+ size: 交易数量
30
+ """
31
+ self.signals.append({'action': 'buy', 'size': size})
32
+
33
+ def sell(self, size: float = 1.0) -> None:
34
+ """卖出信号
35
+
36
+ Args:
37
+ size: 交易数量
38
+ """
39
+ self.signals.append({'action': 'sell', 'size': size})
40
+
41
+ def get_signals(self) -> list:
42
+ """获取所有交易信号"""
43
+ return self.signals
44
+
@@ -0,0 +1,6 @@
1
+ """实盘交易接口模块"""
2
+
3
+ from deltafq.trade.broker import Broker
4
+
5
+ __all__ = ["Broker"]
6
+
@@ -0,0 +1,40 @@
1
+ """交易接口抽象"""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Dict, Any, List
5
+
6
+
7
+ class Broker(ABC):
8
+ """券商接口抽象基类"""
9
+
10
+ @abstractmethod
11
+ def submit_order(
12
+ self,
13
+ symbol: str,
14
+ action: str,
15
+ quantity: float,
16
+ order_type: str = "market"
17
+ ) -> str:
18
+ """提交订单
19
+
20
+ Args:
21
+ symbol: 证券代码
22
+ action: 动作 'buy' or 'sell'
23
+ quantity: 数量
24
+ order_type: 订单类型
25
+
26
+ Returns:
27
+ 订单ID
28
+ """
29
+ pass
30
+
31
+ @abstractmethod
32
+ def get_position(self) -> List[Dict[str, Any]]:
33
+ """获取持仓信息"""
34
+ pass
35
+
36
+ @abstractmethod
37
+ def get_account(self) -> Dict[str, Any]:
38
+ """获取账户信息"""
39
+ pass
40
+
@@ -0,0 +1,6 @@
1
+ """工具函数模块"""
2
+
3
+ from deltafq.utils.time import is_trading_day, get_trading_dates
4
+
5
+ __all__ = ["is_trading_day", "get_trading_dates"]
6
+
deltafq/utils/time.py ADDED
@@ -0,0 +1,32 @@
1
+ """时间相关工具函数"""
2
+
3
+ import pandas as pd
4
+ from datetime import datetime
5
+ from typing import List
6
+
7
+
8
+ def is_trading_day(date: datetime) -> bool:
9
+ """判断是否为交易日
10
+
11
+ Args:
12
+ date: 日期
13
+
14
+ Returns:
15
+ 是否为交易日
16
+ """
17
+ return date.weekday() < 5
18
+
19
+
20
+ def get_trading_dates(start: str, end: str) -> List[datetime]:
21
+ """获取交易日列表
22
+
23
+ Args:
24
+ start: 开始日期
25
+ end: 结束日期
26
+
27
+ Returns:
28
+ 交易日列表
29
+ """
30
+ dates = pd.date_range(start=start, end=end, freq='B')
31
+ return dates.tolist()
32
+
@@ -0,0 +1,202 @@
1
+ Metadata-Version: 2.4
2
+ Name: deltafq
3
+ Version: 0.1.1
4
+ Summary: A professional Python quantitative trading library
5
+ Author-email: DeltaFQ Team <your.email@example.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Delta-F/deltafq
8
+ Project-URL: Documentation, https://github.com/Delta-F/deltafq/tree/main/docs
9
+ Project-URL: Repository, https://github.com/Delta-F/deltafq
10
+ Project-URL: PyPI, https://pypi.org/project/deltafq/
11
+ Project-URL: Bug Tracker, https://github.com/Delta-F/deltafq/issues
12
+ Keywords: quantitative,trading,finance,backtest,strategy
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Financial and Insurance Industry
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Topic :: Office/Business :: Financial :: Investment
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: pandas>=1.3.0
27
+ Requires-Dist: numpy>=1.21.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
30
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
31
+ Requires-Dist: black>=22.0.0; extra == "dev"
32
+ Requires-Dist: flake8>=5.0.0; extra == "dev"
33
+ Requires-Dist: mypy>=0.990; extra == "dev"
34
+ Provides-Extra: plot
35
+ Requires-Dist: matplotlib>=3.5.0; extra == "plot"
36
+ Provides-Extra: all
37
+ Requires-Dist: matplotlib>=3.5.0; extra == "all"
38
+ Dynamic: license-file
39
+
40
+ # DeltaFQ
41
+
42
+ [![PyPI version](https://badge.fury.io/py/deltafq.svg)](https://badge.fury.io/py/deltafq)
43
+ [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
44
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
45
+
46
+ A professional Python quantitative trading library providing a complete toolkit for quantitative strategy development and research.
47
+
48
+ ## Features
49
+
50
+ - 📊 **Multi-source Data Support** - Unified data interface supporting multiple data sources
51
+ - 📈 **Rich Technical Indicators** - Built-in common technical indicators with custom extension support
52
+ - 🎯 **Flexible Strategy Framework** - Clean API for rapid trading strategy development
53
+ - ⚡ **Efficient Backtest Engine** - Vectorized computation for fast strategy validation
54
+ - 📉 **Comprehensive Risk Management** - Position management, risk control, and performance analysis
55
+ - 🔧 **Parameter Optimization Tools** - Multiple optimization algorithms for finding optimal parameters
56
+ - 📱 **Live Trading Interface** - Unified trading interface for seamless simulation and live trading
57
+
58
+ ## Installation
59
+
60
+ ```bash
61
+ pip install deltafq
62
+ ```
63
+
64
+ Or install from source:
65
+
66
+ ```bash
67
+ git clone https://github.com/Delta-F/deltafq.git
68
+ cd deltafq
69
+ pip install -e .
70
+ ```
71
+
72
+ ## Quick Start
73
+
74
+ ### Get Data
75
+
76
+ ```python
77
+ import deltafq as dfq
78
+
79
+ # Get stock data
80
+ data = dfq.data.get_stock_daily('000001.SZ', start='2020-01-01', end='2023-12-31')
81
+ print(data.head())
82
+ ```
83
+
84
+ ### Calculate Technical Indicators
85
+
86
+ ```python
87
+ # Calculate moving averages
88
+ data['ma5'] = dfq.indicators.SMA(data['close'], 5)
89
+ data['ma20'] = dfq.indicators.SMA(data['close'], 20)
90
+
91
+ # Calculate MACD
92
+ macd = dfq.indicators.MACD(data['close'])
93
+ data = data.join(macd)
94
+ ```
95
+
96
+ ### Build Trading Strategy
97
+
98
+ ```python
99
+ class MAStrategy(dfq.strategy.Strategy):
100
+ """Dual Moving Average Strategy"""
101
+
102
+ def on_bar(self, bar):
103
+ if bar.ma5 > bar.ma20:
104
+ self.buy()
105
+ elif bar.ma5 < bar.ma20:
106
+ self.sell()
107
+ ```
108
+
109
+ ### Run Backtest
110
+
111
+ ```python
112
+ # Create backtest engine
113
+ engine = dfq.backtest.BacktestEngine(
114
+ initial_cash=100000,
115
+ commission=0.0003
116
+ )
117
+
118
+ # Run backtest
119
+ result = engine.run(data, MAStrategy())
120
+
121
+ # View results
122
+ print(result.summary())
123
+ result.plot()
124
+ ```
125
+
126
+ ## Module Overview
127
+
128
+ - **data** - Data acquisition and management
129
+ - **indicators** - Technical indicator calculations
130
+ - **strategy** - Strategy development framework
131
+ - **backtest** - Backtest engine
132
+ - **risk** - Risk management
133
+ - **performance** - Performance analysis
134
+ - **optimization** - Parameter optimization
135
+ - **trade** - Live trading interface
136
+ - **utils** - Utility functions
137
+
138
+ ## Examples
139
+
140
+ Check the `examples/` directory for more example code:
141
+
142
+ - `ma_strategy.py` - Dual Moving Average Strategy
143
+ - `macd_strategy.py` - MACD Strategy
144
+ - `optimization_example.py` - Parameter Optimization Example
145
+
146
+ ## Documentation
147
+
148
+ - **User Guide**: [docs/GUIDE.md](docs/GUIDE.md) | [中文指南](docs/GUIDE_zh.md)
149
+ - **API Reference**: [docs/API.md](docs/API.md)
150
+ - **Development Guide**: [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md)
151
+ - **Changelog**: [docs/CHANGELOG.md](docs/CHANGELOG.md)
152
+
153
+ ## Dependencies
154
+
155
+ - Python >= 3.8
156
+ - pandas >= 1.3.0
157
+ - numpy >= 1.21.0
158
+
159
+ ## Development
160
+
161
+ ```bash
162
+ # Clone repository
163
+ git clone https://github.com/Delta-F/deltafq.git
164
+ cd deltafq
165
+
166
+ # Install development dependencies
167
+ pip install -e ".[dev]"
168
+
169
+ # Run tests
170
+ pytest
171
+
172
+ # Code formatting
173
+ black deltafq/
174
+
175
+ # Type checking
176
+ mypy deltafq/
177
+ ```
178
+
179
+ ## License
180
+
181
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
182
+
183
+ ## Contributing
184
+
185
+ Issues and Pull Requests are welcome!
186
+
187
+ ## Contact
188
+
189
+ - Project Homepage: [https://github.com/Delta-F/deltafq](https://github.com/Delta-F/deltafq)
190
+ - PyPI Homepage: [https://pypi.org/project/deltafq/](https://pypi.org/project/deltafq/)
191
+ - Issue Tracker: [https://github.com/Delta-F/deltafq/issues](https://github.com/Delta-F/deltafq/issues)
192
+
193
+ ---
194
+
195
+ ⚠️ **Risk Warning**: Quantitative trading involves risk. This library is for educational and research purposes only and does not constitute investment advice. Please exercise caution when trading live, as you bear the risk yourself.
196
+
197
+ ## Language Support
198
+
199
+ This project supports both English and Chinese documentation:
200
+
201
+ - **English**: [README.md](README.md) (current)
202
+ - **中文**: [README_zh.md](README_zh.md)
@@ -0,0 +1,29 @@
1
+ deltafq/__init__.py,sha256=j_xRF3hL3oBvHyovTHvMvS31Rppvtg-eSFPnvjU5N1s,640
2
+ deltafq/backtest/__init__.py,sha256=nH_lnnpx-XPs2FY8j4DdeptX5Rwumbgn9l82kyiu5Ds,184
3
+ deltafq/backtest/engine.py,sha256=YefCepHM9_Y4EJi5y4eDhjwLILu5iaj1Z7soaXjZLy4,1248
4
+ deltafq/backtest/result.py,sha256=2DS1b9c5iJb8BCeQt9p7p_hrqc805P8mWoqyu-pa3Zs,1164
5
+ deltafq/data/__init__.py,sha256=LCjI7BY2SE4JY_AyWoFd66Pb-9uPRvmuZYlsF6lZAF8,215
6
+ deltafq/data/base.py,sha256=nwwKlLD70jq7bv51F9umWygPKbN-vP_7GpxUdyI0K6g,610
7
+ deltafq/data/loader.py,sha256=wi6aYVUZ4c7u0LV-lHIKX40NnZ7twYga60oq0Pdex3s,1614
8
+ deltafq/indicators/__init__.py,sha256=kNg84vs20ShQYYxKL6j5p5aJWjpdyS2pivRPuHzpRA0,233
9
+ deltafq/indicators/momentum.py,sha256=CRGGjrs-kGpuuV7srTGy2jr9hvvnYF2AIlzOn9grBXI,502
10
+ deltafq/indicators/trend.py,sha256=kaC9tAQq-fR5bfVdHAMgiMgscfcKQCwTz2yG2ZN_N2c,1287
11
+ deltafq/indicators/volatility.py,sha256=jhCHrvdJa_nvPbjEFa1ktH-gDY3wT7Z2vPjQ7DRtjk0,626
12
+ deltafq/optimization/__init__.py,sha256=5uPJiOunFcRWupI2Nn37Jq2VShFASmM_UI7nZx93cCc,133
13
+ deltafq/optimization/grid_search.py,sha256=G_8xVBOr2Vac2RaI9B-WI3mYyzl0zVHuvNrmEdFXUiE,1100
14
+ deltafq/performance/__init__.py,sha256=JDxi_hTmbPSGafvtYjLM5r_r2pVz2L_njM4bUOpvpfw,186
15
+ deltafq/performance/metrics.py,sha256=r0akhbkVVN6g_vuJPb9V7k2-zx7i-tAPmLf7ejRT72c,843
16
+ deltafq/risk/__init__.py,sha256=ckuV7Mg5ijGCUDH9fbEbgxWyaLdcpSG92JYXwh_qUUg,229
17
+ deltafq/risk/metrics.py,sha256=cAUi3bWL4KDOOizgDfe8uKuOEuTWIhXEhG0mkuRFeo0,732
18
+ deltafq/risk/position.py,sha256=h11b7obMpriavPVXzgTiPXDAsjsXAkNy6SVEyoSItqA,911
19
+ deltafq/strategy/__init__.py,sha256=MtT73CleKjhlUPoauAqD2oVFi2sgNdfIB2ZFQhXNkVU,100
20
+ deltafq/strategy/base.py,sha256=chzi59RQUy1hIGZ8r4QPYcdpeVrC1VqtXPyTnGVFkAE,1066
21
+ deltafq/trade/__init__.py,sha256=9MLD7LlybjP0uATMbAqDPYkuwFIP1PPE9PG5WduUZBs,101
22
+ deltafq/trade/broker.py,sha256=IMW3e38mv8XkYF279tqQxKUIjcZ79N82cb52uFhEAWY,875
23
+ deltafq/utils/__init__.py,sha256=AMUJnZSlvojkgOWXROglzXXwqslHrp25YH_9GBbOA0s,149
24
+ deltafq/utils/time.py,sha256=0XGMR8xxX39HS-h7xg0gN6pTuOK-SOlRsWeQq9XLW5Y,641
25
+ deltafq-0.1.1.dist-info/licenses/LICENSE,sha256=5_jN6PqRGcdXKxxg6PCYHU7A2u29fcTdA-8laOCdsZU,1092
26
+ deltafq-0.1.1.dist-info/METADATA,sha256=2OqdSeGSE80XVsRQYFOyj7v73cxBQ-z35rhhHP9tCLE,6195
27
+ deltafq-0.1.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
28
+ deltafq-0.1.1.dist-info/top_level.txt,sha256=j1Q3ce7BEqdXVZd-mlHiJBDHq3iJGiKRKEXPW8xHLHo,8
29
+ deltafq-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 DeltaFQ Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
@@ -1,24 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: deltafq
3
- Version: 0.0.1
4
- Summary: A powerful quantitative trading framework for Python.
5
- Home-page: https://github.com/Delta-F/DeltaFQ
6
- Author: DeltaF
7
- Author-email: leek_li@outlook.com
8
- Classifier: Programming Language :: Python :: 3
9
- Classifier: License :: OSI Approved :: MIT License
10
- Classifier: Operating System :: OS Independent
11
- Requires-Python: >=3.7
12
- Description-Content-Type: text/markdown
13
- License-File: LICENSE
14
- Dynamic: author
15
- Dynamic: author-email
16
- Dynamic: classifier
17
- Dynamic: description
18
- Dynamic: description-content-type
19
- Dynamic: home-page
20
- Dynamic: license-file
21
- Dynamic: requires-python
22
- Dynamic: summary
23
-
24
- # DeltaFQ Project
@@ -1,6 +0,0 @@
1
- deltafq/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- deltafq-0.0.1.dist-info/licenses/LICENSE,sha256=rq0ric2R7qYMkxExrCj6sXBI2xoSvY1ajW3L-0BKQrE,1073
3
- deltafq-0.0.1.dist-info/METADATA,sha256=NTrKt7dIGJPfjJou4hNK6Z-48OCCgfQ2wnDs8QcYL2U,679
4
- deltafq-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
5
- deltafq-0.0.1.dist-info/top_level.txt,sha256=j1Q3ce7BEqdXVZd-mlHiJBDHq3iJGiKRKEXPW8xHLHo,8
6
- deltafq-0.0.1.dist-info/RECORD,,
@@ -1,7 +0,0 @@
1
- Copyright <YEAR> <COPYRIGHT HOLDER>
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
-
5
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
-
7
- THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.