deltafq 0.0.1__tar.gz → 0.1.1__tar.gz

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.

Files changed (48) hide show
  1. deltafq-0.1.1/LICENSE +22 -0
  2. deltafq-0.1.1/MANIFEST.in +7 -0
  3. deltafq-0.1.1/PKG-INFO +202 -0
  4. deltafq-0.1.1/README.md +163 -0
  5. deltafq-0.1.1/deltafq/__init__.py +31 -0
  6. deltafq-0.1.1/deltafq/backtest/__init__.py +7 -0
  7. deltafq-0.1.1/deltafq/backtest/engine.py +52 -0
  8. deltafq-0.1.1/deltafq/backtest/result.py +45 -0
  9. deltafq-0.1.1/deltafq/data/__init__.py +7 -0
  10. deltafq-0.1.1/deltafq/data/base.py +30 -0
  11. deltafq-0.1.1/deltafq/data/loader.py +63 -0
  12. deltafq-0.1.1/deltafq/indicators/__init__.py +8 -0
  13. deltafq-0.1.1/deltafq/indicators/momentum.py +23 -0
  14. deltafq-0.1.1/deltafq/indicators/trend.py +61 -0
  15. deltafq-0.1.1/deltafq/indicators/volatility.py +27 -0
  16. deltafq-0.1.1/deltafq/optimization/__init__.py +6 -0
  17. deltafq-0.1.1/deltafq/optimization/grid_search.py +41 -0
  18. deltafq-0.1.1/deltafq/performance/__init__.py +6 -0
  19. deltafq-0.1.1/deltafq/performance/metrics.py +37 -0
  20. deltafq-0.1.1/deltafq/risk/__init__.py +7 -0
  21. deltafq-0.1.1/deltafq/risk/metrics.py +33 -0
  22. deltafq-0.1.1/deltafq/risk/position.py +39 -0
  23. deltafq-0.1.1/deltafq/strategy/__init__.py +6 -0
  24. deltafq-0.1.1/deltafq/strategy/base.py +44 -0
  25. deltafq-0.1.1/deltafq/trade/__init__.py +6 -0
  26. deltafq-0.1.1/deltafq/trade/broker.py +40 -0
  27. deltafq-0.1.1/deltafq/utils/__init__.py +6 -0
  28. deltafq-0.1.1/deltafq/utils/time.py +32 -0
  29. deltafq-0.1.1/deltafq.egg-info/PKG-INFO +202 -0
  30. deltafq-0.1.1/deltafq.egg-info/SOURCES.txt +39 -0
  31. deltafq-0.1.1/deltafq.egg-info/requires.txt +15 -0
  32. deltafq-0.1.1/pyproject.toml +74 -0
  33. deltafq-0.1.1/setup.py +12 -0
  34. deltafq-0.1.1/tests/test_backtest.py +54 -0
  35. deltafq-0.1.1/tests/test_data.py +27 -0
  36. deltafq-0.1.1/tests/test_full_workflow.py +158 -0
  37. deltafq-0.1.1/tests/test_indicators.py +55 -0
  38. deltafq-0.1.1/tests/test_strategy.py +49 -0
  39. deltafq-0.0.1/LICENSE +0 -7
  40. deltafq-0.0.1/PKG-INFO +0 -24
  41. deltafq-0.0.1/README.md +0 -1
  42. deltafq-0.0.1/deltafq/__init__.py +0 -0
  43. deltafq-0.0.1/deltafq.egg-info/PKG-INFO +0 -24
  44. deltafq-0.0.1/deltafq.egg-info/SOURCES.txt +0 -8
  45. deltafq-0.0.1/setup.py +0 -19
  46. {deltafq-0.0.1 → deltafq-0.1.1}/deltafq.egg-info/dependency_links.txt +0 -0
  47. {deltafq-0.0.1 → deltafq-0.1.1}/deltafq.egg-info/top_level.txt +0 -0
  48. {deltafq-0.0.1 → deltafq-0.1.1}/setup.cfg +0 -0
deltafq-0.1.1/LICENSE ADDED
@@ -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
+
@@ -0,0 +1,7 @@
1
+ include README.md
2
+ include LICENSE
3
+ include pyproject.toml
4
+ recursive-include deltafq *.py
5
+ recursive-exclude * __pycache__
6
+ recursive-exclude * *.py[co]
7
+
deltafq-0.1.1/PKG-INFO ADDED
@@ -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,163 @@
1
+ # DeltaFQ
2
+
3
+ [![PyPI version](https://badge.fury.io/py/deltafq.svg)](https://badge.fury.io/py/deltafq)
4
+ [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ A professional Python quantitative trading library providing a complete toolkit for quantitative strategy development and research.
8
+
9
+ ## Features
10
+
11
+ - 📊 **Multi-source Data Support** - Unified data interface supporting multiple data sources
12
+ - 📈 **Rich Technical Indicators** - Built-in common technical indicators with custom extension support
13
+ - 🎯 **Flexible Strategy Framework** - Clean API for rapid trading strategy development
14
+ - ⚡ **Efficient Backtest Engine** - Vectorized computation for fast strategy validation
15
+ - 📉 **Comprehensive Risk Management** - Position management, risk control, and performance analysis
16
+ - 🔧 **Parameter Optimization Tools** - Multiple optimization algorithms for finding optimal parameters
17
+ - 📱 **Live Trading Interface** - Unified trading interface for seamless simulation and live trading
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ pip install deltafq
23
+ ```
24
+
25
+ Or install from source:
26
+
27
+ ```bash
28
+ git clone https://github.com/Delta-F/deltafq.git
29
+ cd deltafq
30
+ pip install -e .
31
+ ```
32
+
33
+ ## Quick Start
34
+
35
+ ### Get Data
36
+
37
+ ```python
38
+ import deltafq as dfq
39
+
40
+ # Get stock data
41
+ data = dfq.data.get_stock_daily('000001.SZ', start='2020-01-01', end='2023-12-31')
42
+ print(data.head())
43
+ ```
44
+
45
+ ### Calculate Technical Indicators
46
+
47
+ ```python
48
+ # Calculate moving averages
49
+ data['ma5'] = dfq.indicators.SMA(data['close'], 5)
50
+ data['ma20'] = dfq.indicators.SMA(data['close'], 20)
51
+
52
+ # Calculate MACD
53
+ macd = dfq.indicators.MACD(data['close'])
54
+ data = data.join(macd)
55
+ ```
56
+
57
+ ### Build Trading Strategy
58
+
59
+ ```python
60
+ class MAStrategy(dfq.strategy.Strategy):
61
+ """Dual Moving Average Strategy"""
62
+
63
+ def on_bar(self, bar):
64
+ if bar.ma5 > bar.ma20:
65
+ self.buy()
66
+ elif bar.ma5 < bar.ma20:
67
+ self.sell()
68
+ ```
69
+
70
+ ### Run Backtest
71
+
72
+ ```python
73
+ # Create backtest engine
74
+ engine = dfq.backtest.BacktestEngine(
75
+ initial_cash=100000,
76
+ commission=0.0003
77
+ )
78
+
79
+ # Run backtest
80
+ result = engine.run(data, MAStrategy())
81
+
82
+ # View results
83
+ print(result.summary())
84
+ result.plot()
85
+ ```
86
+
87
+ ## Module Overview
88
+
89
+ - **data** - Data acquisition and management
90
+ - **indicators** - Technical indicator calculations
91
+ - **strategy** - Strategy development framework
92
+ - **backtest** - Backtest engine
93
+ - **risk** - Risk management
94
+ - **performance** - Performance analysis
95
+ - **optimization** - Parameter optimization
96
+ - **trade** - Live trading interface
97
+ - **utils** - Utility functions
98
+
99
+ ## Examples
100
+
101
+ Check the `examples/` directory for more example code:
102
+
103
+ - `ma_strategy.py` - Dual Moving Average Strategy
104
+ - `macd_strategy.py` - MACD Strategy
105
+ - `optimization_example.py` - Parameter Optimization Example
106
+
107
+ ## Documentation
108
+
109
+ - **User Guide**: [docs/GUIDE.md](docs/GUIDE.md) | [中文指南](docs/GUIDE_zh.md)
110
+ - **API Reference**: [docs/API.md](docs/API.md)
111
+ - **Development Guide**: [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md)
112
+ - **Changelog**: [docs/CHANGELOG.md](docs/CHANGELOG.md)
113
+
114
+ ## Dependencies
115
+
116
+ - Python >= 3.8
117
+ - pandas >= 1.3.0
118
+ - numpy >= 1.21.0
119
+
120
+ ## Development
121
+
122
+ ```bash
123
+ # Clone repository
124
+ git clone https://github.com/Delta-F/deltafq.git
125
+ cd deltafq
126
+
127
+ # Install development dependencies
128
+ pip install -e ".[dev]"
129
+
130
+ # Run tests
131
+ pytest
132
+
133
+ # Code formatting
134
+ black deltafq/
135
+
136
+ # Type checking
137
+ mypy deltafq/
138
+ ```
139
+
140
+ ## License
141
+
142
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
143
+
144
+ ## Contributing
145
+
146
+ Issues and Pull Requests are welcome!
147
+
148
+ ## Contact
149
+
150
+ - Project Homepage: [https://github.com/Delta-F/deltafq](https://github.com/Delta-F/deltafq)
151
+ - PyPI Homepage: [https://pypi.org/project/deltafq/](https://pypi.org/project/deltafq/)
152
+ - Issue Tracker: [https://github.com/Delta-F/deltafq/issues](https://github.com/Delta-F/deltafq/issues)
153
+
154
+ ---
155
+
156
+ ⚠️ **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.
157
+
158
+ ## Language Support
159
+
160
+ This project supports both English and Chinese documentation:
161
+
162
+ - **English**: [README.md](README.md) (current)
163
+ - **中文**: [README_zh.md](README_zh.md)
@@ -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
+
@@ -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
+
@@ -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
+