├── .DS_Store ├── .ipynb_checkpoints ├── README-checkpoint.md ├── untitled-checkpoint.txt └── 跨平台量化环境测试+Rqalpha+Tushare+Quantaxis+Funcat+Hikyuu+Abu+Kivy-checkpoint.ipynb ├── AI量化与分析 └── tensorflow1.5彩票测试.ipynb ├── BigQuant-AI量化 ├── .ipynb_checkpoints │ ├── ai-自动 测试 - 策略&研究 - BigQuant量化社区-checkpoint.pdf │ └── 可视化策略-去除退市股-checkpoint.ipynb ├── AI量化策略开发-BigQuant.webarchive ├── ai-自动 测试 - 策略&研究 - BigQuant量化社区.pdf ├── ai-自动-一只权0号测试 - 策略&研究 - BigQuant量化社区.pdf └── 可视化策略-去除退市股.ipynb ├── DevilYuan量化 ├── DySS_KDJ.ipynb └── DySS_KDJ2793.py ├── DySS_KDJ.ipynb ├── JD策略还原.ipynb ├── KIVY跨平台量化测试RqalphaOK+TushareOK+QuantaxisOK+FuncatOK+DevilYuanOK+HikyuuNO+AbuOK++ziplineNO.ipynb ├── LSIM-RNN-example_using_keras.ipynb ├── QA.DATA.TEST.ipynb ├── QA结构说明.ipynb ├── QA选股.ipynb ├── QA选股MA.ipynb ├── README.md ├── T0backtest.ipynb ├── hikyuu量化 ├── .DS_Store ├── 策略 - 副本.ipynb └── 策略.ipynb ├── macd.ipynb ├── pip install -r ├── .DS_Store ├── bf │ ├── abupy.txt │ ├── kivy.txt │ ├── quantaxis.txt │ └── rqalpha.txt ├── kivy-m_pip_freeze.txt ├── pip_freeze.txt └── python-m_pip_freeze.txt ├── pp-cpu.ipynb ├── python头条教程 ├── .DS_Store ├── 15分钟,教你用Python爬网站数据,并用BI可视化分析!.pdf ├── 《学Python量化,通往财务自由》|选股实战之CAPM模型.pdf ├── 使用LSTM预测股票价格:机器学习案例研究.ipynb ├── 使用LSTM预测股票价格:机器学习案例研究.pdf └── 选股实战之CAPM模型.ipynb ├── quantaxis_backend.ipynb ├── quantaxis量化 ├── .DS_Store ├── QA.DATA.TEST.ipynb ├── QA结构说明.ipynb └── quantaxis_backend.ipynb ├── rqalpha量化 ├── .DS_Store ├── .ipynb_checkpoints │ └── 查询股票-Rqalpha-Tushare-Quantaxis-Funcat-Kivy-checkpoint.ipynb ├── THS-LINK.ipynb ├── cci+boll.ipynb ├── 回测 │ ├── .DS_Store │ ├── .ipynb_checkpoints │ │ └── RQ回测-checkpoint.ipynb │ ├── RQ回测.ipynb │ ├── Untitled.ipynb │ ├── Untitled1.ipynb │ ├── Untitled2.ipynb │ ├── run-rqalpha-in-ipython.ipynb │ ├── 交易系统回测例子.ipynb │ ├── 回测1.ipynb │ ├── 回测2.ipynb │ ├── 回测3.ipynb │ ├── 回测模版.ipynb │ ├── 回测模版2.ipynb │ ├── 回测模版3.ipynb │ ├── 回测模版的副本.ipynb │ └── 回测系统.ipynb ├── 多项次拟合策略.ipynb ├── 实例 │ ├── 20180201 │ │ ├── funcat-tutorial-rqalpha-py2的副本.ipynb │ │ ├── funcat-tutorial-rqalpha-py3的副本.ipynb │ │ ├── funcat-tutorial-tushare-py2的副本.ipynb │ │ └── funcat-tutorial-tushare-py3的副本.ipynb │ ├── .DS_Store │ ├── 0202 │ │ ├── funcat-tutorial-rqalpha-py2的副本.ipynb │ │ ├── funcat-tutorial-rqalpha-py3的副本.ipynb │ │ ├── funcat-tutorial-tushare-py2的副本.ipynb │ │ └── funcat-tutorial-tushare-py3的副本.ipynb │ ├── CCI-Copy1.ipynb │ ├── CCI.ipynb │ ├── THS.ipynb │ ├── Untitled的副本.ipynb │ ├── funcat-tutorial-rqalpha-py2.ipynb │ ├── funcat-tutorial-rqalpha-py3.ipynb │ ├── funcat-tutorial-tushare-py2.ipynb │ ├── funcat-tutorial-tushare-py3.ipynb │ ├── my-notebook.ipynb │ ├── my-notebook.ipynb的副本.txt │ ├── pytdxtest.ipynb │ ├── test.py │ ├── ths api.ipynb │ ├── ths-pytdx.ipynb │ ├── ths-rqalpha.ipynb │ ├── ths-rqalpha.py │ ├── ths-tushare.ipynb │ ├── ths-tushare.py │ ├── ths.py │ ├── zt.py │ ├── 我的选股-Copy1.ipynb │ ├── 我的选股-Copy2.ipynb │ ├── 我的选股.ipynb │ ├── 我的选股.py │ ├── 我的选股的副本-Copy1.ipynb │ └── 我的选股的副本.ipynb ├── 查询股票-RQ.ipynb ├── 查询股票-Rqalpha-Tushare-Quantaxis-Funcat-Kivy.ipynb ├── 查询股票-TU.ipynb ├── 涨停-RQ.ipynb ├── 涨停-TU.ipynb └── 选股 │ ├── .DS_Store │ ├── .ipynb_checkpoints │ ├── 925选股-checkpoint.ipynb │ ├── BOOL选股-RQ-checkpoint.ipynb │ └── MACD 选股-checkpoint.ipynb │ ├── 925.ipynb │ ├── 925选股.ipynb │ ├── BOOL选股-RQ.ipynb │ ├── BOOL选股-TU.ipynb │ ├── CCI选股RQ.ipynb │ ├── CCI选股TU.ipynb │ ├── DMA选股RQ.ipynb │ ├── DMA选股TU.ipynb │ ├── KDJ 选股RQ.ipynb │ ├── KDJ 选股TU.ipynb │ ├── MACD 选股.ipynb │ ├── Untitled.ipynb │ └── 选股成交量BOLL.ipynb ├── untitled.txt ├── 京东量化 ├── jd回测.xlsx └── jd源码.txt ├── 使用LSTM预测股票价格:机器学习案例研究.ipynb ├── 希尔伯特变换.ipynb ├── 滚动训练示例.ipynb ├── 用Python爬网站数据并用BI可视化分析.ipynb ├── 用于算法交易的神经网络——正确的时间序列预测和回测.ipynb ├── 神经网络算法股票涨跌预测模型.ipynb ├── 策略test-带注释.ipynb ├── 跨平台量化环境测试+RQ+TU+QA+Funcat+Hikyuu+Abu+DevilYuan+Kivy+tensorflow 2.ipynb ├── 跨平台量化环境测试+RQ+TU+QA+Funcat+Hikyuu+Abu+DevilYuan+Kivy+tensorflow.ipynb ├── 跨平台量化环境综合对抗测试.ipynb ├── 选股RQ TU.ipynb ├── 选股实战之CAPM模型.ipynb └── 飞狐指标选股分析 ├── 4152B7F78F29352BE9B1E42DA61D2C30.jpg ├── 56E9E52F38417A8F8A6C918B9A0C2FC0.jpg ├── 5DBFF4F442556A46BB142FC95DCE8AE5.jpg ├── 6F7C1D112F1FC95964A2AFAF1B3A0F09.jpg ├── 706F846AC1D97A880C53BCA56E57ABF6.jpg ├── 964BDAEE6127C21BD39A23735A4631BF.jpg ├── A3EAD336FAA99D0CBF76F5E7B977675C.jpg └── C60D0650ED1E479DFC06AD55F7DB8458.jpg /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/.DS_Store -------------------------------------------------------------------------------- /.ipynb_checkpoints/README-checkpoint.md: -------------------------------------------------------------------------------- 1 | 2 | pip install -r 见目录对应txt 3 | 4 | kivy环境部署:quantaxis+rqalpha+abupy+hikyuu+abupy 5 | python -m pip install -r kivy.txt 或 pip install -r kivy.txt 部署环境 6 | 开启jupyter notebook 或 notebook 7 | 8 | rqalpha 环境部署:rqalpha+funcat+tushare 9 | python -m pip install -r rqalpha.txt 或 pip install -r rqalpha.txt 部署环境 10 | 开启jupyter notebook 或 notebook 11 | 12 | quantaxis环境部署:quantaxis+tushare+pytdx 13 | python -m pip install -r quantaxis.txt 或 pip install -r quantaxis.txt 部署环境 14 | 开启jupyter notebook 或 notebook 15 | 16 | hiykuu环境部署: 17 | python -m pip install -r hikyuu.txt 或 pip install -r hikyuu.txt 部署环境 18 | 开启jupyter notebook 或 notebook 19 | 20 | abupy环境部署: 21 | python -m pip install -r abupy.txt 或 pip install -r abupy.txt 部署环境 22 | 开启jupyter notebook 或 notebook -------------------------------------------------------------------------------- /.ipynb_checkpoints/untitled-checkpoint.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/.ipynb_checkpoints/untitled-checkpoint.txt -------------------------------------------------------------------------------- /BigQuant-AI量化/.ipynb_checkpoints/ai-自动 测试 - 策略&研究 - BigQuant量化社区-checkpoint.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/BigQuant-AI量化/.ipynb_checkpoints/ai-自动 测试 - 策略&研究 - BigQuant量化社区-checkpoint.pdf -------------------------------------------------------------------------------- /BigQuant-AI量化/AI量化策略开发-BigQuant.webarchive: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/BigQuant-AI量化/AI量化策略开发-BigQuant.webarchive -------------------------------------------------------------------------------- /BigQuant-AI量化/ai-自动 测试 - 策略&研究 - BigQuant量化社区.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/BigQuant-AI量化/ai-自动 测试 - 策略&研究 - BigQuant量化社区.pdf -------------------------------------------------------------------------------- /BigQuant-AI量化/ai-自动-一只权0号测试 - 策略&研究 - BigQuant量化社区.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/BigQuant-AI量化/ai-自动-一只权0号测试 - 策略&研究 - BigQuant量化社区.pdf -------------------------------------------------------------------------------- /DevilYuan量化/DySS_KDJ.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import math, operator\n", 10 | "\n", 11 | "import talib\n", 12 | "\n", 13 | "from ..DyStockSelectStrategyTemplate import *\n", 14 | "from ....Data.Utility.DyStockDataUtility import *\n", 15 | "\n", 16 | "\n", 17 | "class DySS_KDJ2793(DyStockSelectStrategyTemplate):\n", 18 | " name = 'DySS_KDJ2793'\n", 19 | " chName = 'KDJ2793'\n", 20 | "\n", 21 | " colNames = ['代码', '名称', '背离强度']\n", 22 | "\n", 23 | " param = OrderedDict\\\n", 24 | " ([\n", 25 | " ('基准日期', datetime.today().strftime(\"%Y-%m-%d\")),\n", 26 | " ('KDJ2793指标', 'close'),\n", 27 | " ('极值窗口', 4),\n", 28 | " ('底背离次数', 3),\n", 29 | " ('金叉', 1)\n", 30 | " ])\n", 31 | "\n", 32 | " paramToolTip = {'KDJ2793指标': 'open, high, low, close',\n", 33 | " '极值窗口': '滑动窗口大小(w), 周期则为2w+1',\n", 34 | " '金叉': '1:考虑金叉,0:不考虑金叉'\n", 35 | " }\n", 36 | "\n", 37 | " autoFillDays = True\n", 38 | "\n", 39 | " # 策略参数\n", 40 | " kdjDays = 100\n", 41 | "\n", 42 | " def __init__(self, param, info):\n", 43 | " super().__init__(param, info)\n", 44 | "\n", 45 | " # unpack parameters\n", 46 | " self._baseDate = param['基准日期']\n", 47 | " self._kdjIndicator = param['KDJ2793指标']\n", 48 | " self._extremaWindow = param['极值窗口']\n", 49 | " self._bottomDeviationNbr = param['底背离次数']\n", 50 | " self._crossOver = True if param['金叉'] else False\n", 51 | "\n", 52 | " def onDaysLoad(self):\n", 53 | " return self._baseDate, -self.kdjDays + 1\n", 54 | "\n", 55 | " def onInit(self, dataEngine, errorDataEngine):\n", 56 | " self._stockAllCodes = dataEngine.daysEngine.stockAllCodes\n", 57 | "\n", 58 | " def onStockDays(self, code, df):\n", 59 | " # 计算KDJ\n", 60 | " diff, dea, bar = self._kdj(df, self._kdjIndicator)\n", 61 | " if diff is None: return\n", 62 | "\n", 63 | " # 计算极值\n", 64 | " extremas, peaks, bottoms = DyStockDataUtility.rwExtremas(df, w=self._extremaWindow, bottomIndicator=self._kdjIndicator)\n", 65 | "\n", 66 | " # 不考虑KDJ金叉时则考虑右边界\n", 67 | " if not self._crossOver:\n", 68 | " bottoms[df.index[-1]] = df.ix[-1, self._kdjIndicator]\n", 69 | "\n", 70 | " if bottoms.size < self._bottomDeviationNbr: return\n", 71 | "\n", 72 | " # 极小值递减\n", 73 | " bottoms = bottoms[-self._bottomDeviationNbr:]\n", 74 | " if ((bottoms - bottoms.shift(1)) > 0).sum() > 0: return\n", 75 | "\n", 76 | " # 极小值对应的KDJ的DIFF递增\n", 77 | " positions = [df.index.get_loc(index) for index in bottoms.index]\n", 78 | " \n", 79 | " # 确保diff的值不是NaN\n", 80 | " diff = diff[positions]\n", 81 | " if sum(np.isnan(diff)) > 0: return\n", 82 | "\n", 83 | " if ((diff[1:] - diff[:-1]) < 0).sum() > 0: return\n", 84 | "\n", 85 | " # 考虑金叉\n", 86 | " if self._crossOver:\n", 87 | " if not (diff[-1] > dea[-1] and diff[-2] < dea[-2]):\n", 88 | " return\n", 89 | "\n", 90 | " # 计算背离强度\n", 91 | " bottomsList = list(bottoms.values)\n", 92 | " bottomsChanges = list(map(lambda x,y:abs((x-y)/y), bottomsList[1:], bottomsList[:-1]))\n", 93 | "\n", 94 | " diffList = list(diff)\n", 95 | " diffChanges = list(map(lambda x,y:abs((x-y)/y), diffList[1:], diffList[:-1]))\n", 96 | "\n", 97 | " assert len(bottomsList) == len(diffList)\n", 98 | "\n", 99 | " deviationIntensity = list(map(lambda x,y:x*y, bottomsChanges, diffChanges))\n", 100 | " deviationIntensity = sum(deviationIntensity)*100\n", 101 | " \n", 102 | " # 设置结果\n", 103 | " pair = [code, self._stockAllCodes[code], deviationIntensity]\n", 104 | " self._result.append(pair)\n", 105 | "\n", 106 | " def _kdj(self, df, indicator='close'):\n", 107 | " values = df[indicator]\n", 108 | "\n", 109 | " try:\n", 110 | " diff, dea, bar = talib.kdj(values.values, fastperiod=27, slowperiod=9, signalperiod=3)\n", 111 | " bar *= 2\n", 112 | " except Exception as ex:\n", 113 | " return None, None, None\n", 114 | "\n", 115 | " return diff, dea, bar" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": null, 121 | "metadata": {}, 122 | "outputs": [], 123 | "source": [] 124 | } 125 | ], 126 | "metadata": { 127 | "kernelspec": { 128 | "display_name": "Python 3", 129 | "language": "python", 130 | "name": "python3" 131 | }, 132 | "language_info": { 133 | "codemirror_mode": { 134 | "name": "ipython", 135 | "version": 3 136 | }, 137 | "file_extension": ".py", 138 | "mimetype": "text/x-python", 139 | "name": "python", 140 | "nbconvert_exporter": "python", 141 | "pygments_lexer": "ipython3", 142 | "version": "3.6.5" 143 | } 144 | }, 145 | "nbformat": 4, 146 | "nbformat_minor": 2 147 | } 148 | -------------------------------------------------------------------------------- /DevilYuan量化/DySS_KDJ2793.py: -------------------------------------------------------------------------------- 1 | import math, operator 2 | 3 | import talib 4 | 5 | from ..DyStockSelectStrategyTemplate import * 6 | from ....Data.Utility.DyStockDataUtility import * 7 | 8 | 9 | class DySS_KDJ2793(DyStockSelectStrategyTemplate): 10 | name = 'DySS_KDJ2793' 11 | chName = 'KDJ2793' 12 | 13 | colNames = ['代码', '名称', '背离强度'] 14 | 15 | param = OrderedDict\ 16 | ([ 17 | ('基准日期', datetime.today().strftime("%Y-%m-%d")), 18 | ('KDJ2793指标', 'close'), 19 | ('极值窗口', 4), 20 | ('底背离次数', 3), 21 | ('金叉', 1) 22 | ]) 23 | 24 | paramToolTip = {'KDJ2793指标': 'open, high, low, close', 25 | '极值窗口': '滑动窗口大小(w), 周期则为2w+1', 26 | '金叉': '1:考虑金叉,0:不考虑金叉' 27 | } 28 | 29 | autoFillDays = True 30 | 31 | # 策略参数 32 | kdjDays = 100 33 | 34 | def __init__(self, param, info): 35 | super().__init__(param, info) 36 | 37 | # unpack parameters 38 | self._baseDate = param['基准日期'] 39 | self._kdjIndicator = param['KDJ2793指标'] 40 | self._extremaWindow = param['极值窗口'] 41 | self._bottomDeviationNbr = param['底背离次数'] 42 | self._crossOver = True if param['金叉'] else False 43 | 44 | def onDaysLoad(self): 45 | return self._baseDate, -self.kdjDays + 1 46 | 47 | def onInit(self, dataEngine, errorDataEngine): 48 | self._stockAllCodes = dataEngine.daysEngine.stockAllCodes 49 | 50 | def onStockDays(self, code, df): 51 | # 计算KDJ 52 | diff, dea, bar = self._kdj(df, self._kdjIndicator) 53 | if diff is None: return 54 | 55 | # 计算极值 56 | extremas, peaks, bottoms = DyStockDataUtility.rwExtremas(df, w=self._extremaWindow, bottomIndicator=self._kdjIndicator) 57 | 58 | # 不考虑KDJ金叉时则考虑右边界 59 | if not self._crossOver: 60 | bottoms[df.index[-1]] = df.ix[-1, self._kdjIndicator] 61 | 62 | if bottoms.size < self._bottomDeviationNbr: return 63 | 64 | # 极小值递减 65 | bottoms = bottoms[-self._bottomDeviationNbr:] 66 | if ((bottoms - bottoms.shift(1)) > 0).sum() > 0: return 67 | 68 | # 极小值对应的KDJ的DIFF递增 69 | positions = [df.index.get_loc(index) for index in bottoms.index] 70 | 71 | # 确保diff的值不是NaN 72 | diff = diff[positions] 73 | if sum(np.isnan(diff)) > 0: return 74 | 75 | if ((diff[1:] - diff[:-1]) < 0).sum() > 0: return 76 | 77 | # 考虑金叉 78 | if self._crossOver: 79 | if not (diff[-1] > dea[-1] and diff[-2] < dea[-2]): 80 | return 81 | 82 | # 计算背离强度 83 | bottomsList = list(bottoms.values) 84 | bottomsChanges = list(map(lambda x,y:abs((x-y)/y), bottomsList[1:], bottomsList[:-1])) 85 | 86 | diffList = list(diff) 87 | diffChanges = list(map(lambda x,y:abs((x-y)/y), diffList[1:], diffList[:-1])) 88 | 89 | assert len(bottomsList) == len(diffList) 90 | 91 | deviationIntensity = list(map(lambda x,y:x*y, bottomsChanges, diffChanges)) 92 | deviationIntensity = sum(deviationIntensity)*100 93 | 94 | # 设置结果 95 | pair = [code, self._stockAllCodes[code], deviationIntensity] 96 | self._result.append(pair) 97 | 98 | def _kdj(self, df, indicator='close'): 99 | values = df[indicator] 100 | 101 | try: 102 | diff, dea, bar = talib.kdj(values.values, fastperiod=27, slowperiod=9, signalperiod=3) 103 | bar *= 2 104 | except Exception as ex: 105 | return None, None, None 106 | 107 | return diff, dea, bar -------------------------------------------------------------------------------- /DySS_KDJ.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import math, operator\n", 10 | "\n", 11 | "import talib\n", 12 | "\n", 13 | "from ..DyStockSelectStrategyTemplate import *\n", 14 | "from ....Data.Utility.DyStockDataUtility import *\n", 15 | "\n", 16 | "\n", 17 | "class DySS_KDJ2793(DyStockSelectStrategyTemplate):\n", 18 | " name = 'DySS_KDJ2793'\n", 19 | " chName = 'KDJ2793'\n", 20 | "\n", 21 | " colNames = ['代码', '名称', '背离强度']\n", 22 | "\n", 23 | " param = OrderedDict\\\n", 24 | " ([\n", 25 | " ('基准日期', datetime.today().strftime(\"%Y-%m-%d\")),\n", 26 | " ('KDJ2793指标', 'close'),\n", 27 | " ('极值窗口', 4),\n", 28 | " ('底背离次数', 3),\n", 29 | " ('金叉', 1)\n", 30 | " ])\n", 31 | "\n", 32 | " paramToolTip = {'KDJ2793指标': 'open, high, low, close',\n", 33 | " '极值窗口': '滑动窗口大小(w), 周期则为2w+1',\n", 34 | " '金叉': '1:考虑金叉,0:不考虑金叉'\n", 35 | " }\n", 36 | "\n", 37 | " autoFillDays = True\n", 38 | "\n", 39 | " # 策略参数\n", 40 | " kdjDays = 100\n", 41 | "\n", 42 | " def __init__(self, param, info):\n", 43 | " super().__init__(param, info)\n", 44 | "\n", 45 | " # unpack parameters\n", 46 | " self._baseDate = param['基准日期']\n", 47 | " self._kdjIndicator = param['KDJ2793指标']\n", 48 | " self._extremaWindow = param['极值窗口']\n", 49 | " self._bottomDeviationNbr = param['底背离次数']\n", 50 | " self._crossOver = True if param['金叉'] else False\n", 51 | "\n", 52 | " def onDaysLoad(self):\n", 53 | " return self._baseDate, -self.kdjDays + 1\n", 54 | "\n", 55 | " def onInit(self, dataEngine, errorDataEngine):\n", 56 | " self._stockAllCodes = dataEngine.daysEngine.stockAllCodes\n", 57 | "\n", 58 | " def onStockDays(self, code, df):\n", 59 | " # 计算KDJ\n", 60 | " diff, dea, bar = self._kdj(df, self._kdjIndicator)\n", 61 | " if diff is None: return\n", 62 | "\n", 63 | " # 计算极值\n", 64 | " extremas, peaks, bottoms = DyStockDataUtility.rwExtremas(df, w=self._extremaWindow, bottomIndicator=self._kdjIndicator)\n", 65 | "\n", 66 | " # 不考虑KDJ金叉时则考虑右边界\n", 67 | " if not self._crossOver:\n", 68 | " bottoms[df.index[-1]] = df.ix[-1, self._kdjIndicator]\n", 69 | "\n", 70 | " if bottoms.size < self._bottomDeviationNbr: return\n", 71 | "\n", 72 | " # 极小值递减\n", 73 | " bottoms = bottoms[-self._bottomDeviationNbr:]\n", 74 | " if ((bottoms - bottoms.shift(1)) > 0).sum() > 0: return\n", 75 | "\n", 76 | " # 极小值对应的KDJ的DIFF递增\n", 77 | " positions = [df.index.get_loc(index) for index in bottoms.index]\n", 78 | " \n", 79 | " # 确保diff的值不是NaN\n", 80 | " diff = diff[positions]\n", 81 | " if sum(np.isnan(diff)) > 0: return\n", 82 | "\n", 83 | " if ((diff[1:] - diff[:-1]) < 0).sum() > 0: return\n", 84 | "\n", 85 | " # 考虑金叉\n", 86 | " if self._crossOver:\n", 87 | " if not (diff[-1] > dea[-1] and diff[-2] < dea[-2]):\n", 88 | " return\n", 89 | "\n", 90 | " # 计算背离强度\n", 91 | " bottomsList = list(bottoms.values)\n", 92 | " bottomsChanges = list(map(lambda x,y:abs((x-y)/y), bottomsList[1:], bottomsList[:-1]))\n", 93 | "\n", 94 | " diffList = list(diff)\n", 95 | " diffChanges = list(map(lambda x,y:abs((x-y)/y), diffList[1:], diffList[:-1]))\n", 96 | "\n", 97 | " assert len(bottomsList) == len(diffList)\n", 98 | "\n", 99 | " deviationIntensity = list(map(lambda x,y:x*y, bottomsChanges, diffChanges))\n", 100 | " deviationIntensity = sum(deviationIntensity)*100\n", 101 | " \n", 102 | " # 设置结果\n", 103 | " pair = [code, self._stockAllCodes[code], deviationIntensity]\n", 104 | " self._result.append(pair)\n", 105 | "\n", 106 | " def _kdj(self, df, indicator='close'):\n", 107 | " values = df[indicator]\n", 108 | "\n", 109 | " try:\n", 110 | " diff, dea, bar = talib.kdj(values.values, fastperiod=27, slowperiod=9, signalperiod=3)\n", 111 | " bar *= 2\n", 112 | " except Exception as ex:\n", 113 | " return None, None, None\n", 114 | "\n", 115 | " return diff, dea, bar" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": null, 121 | "metadata": {}, 122 | "outputs": [], 123 | "source": [] 124 | } 125 | ], 126 | "metadata": { 127 | "kernelspec": { 128 | "display_name": "Python 3", 129 | "language": "python", 130 | "name": "python3" 131 | }, 132 | "language_info": { 133 | "codemirror_mode": { 134 | "name": "ipython", 135 | "version": 3 136 | }, 137 | "file_extension": ".py", 138 | "mimetype": "text/x-python", 139 | "name": "python", 140 | "nbconvert_exporter": "python", 141 | "pygments_lexer": "ipython3", 142 | "version": "3.6.5" 143 | } 144 | }, 145 | "nbformat": 4, 146 | "nbformat_minor": 2 147 | } 148 | -------------------------------------------------------------------------------- /LSIM-RNN-example_using_keras.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stderr", 10 | "output_type": "stream", 11 | "text": [ 12 | "Using TensorFlow backend.\n" 13 | ] 14 | } 15 | ], 16 | "source": [ 17 | "import keras\n", 18 | "import numpy as np\n", 19 | "import matplotlib.pyplot as plt\n", 20 | "import pandas as pd\n", 21 | "from pandas import datetime\n", 22 | "import math, time\n", 23 | "import itertools\n", 24 | "from sklearn import preprocessing\n", 25 | "import datetime\n", 26 | "from operator import itemgetter\n", 27 | "from sklearn.metrics import mean_squared_error\n", 28 | "from math import sqrt\n", 29 | "from keras.models import Sequential\n", 30 | "from keras.layers.core import Dense, Dropout, Activation\n", 31 | "from keras.layers.recurrent import LSTM\n", 32 | "import QUANTAXIS as QA\n", 33 | "# 获取全市场的股票代码信息列表\n", 34 | "QA_code_list = QA.QA_fetch_stock_list_adv()\n", 35 | "#QA_code_list\n", 36 | "#QA全市场code列表\n", 37 | "QA_code = QA_code_list.code.tolist() \n", 38 | "#QA_code\n", 39 | "#QA全市场name列表\n", 40 | "QA_name = QA_code_list.name.tolist() \n", 41 | "#QA_name \n" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": 2, 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "#训练起始时间\n", 51 | "start_date='2015-06-01'\n", 52 | "end_date='2017-06-01'\n", 53 | "#inst = D.instruments(start_date, end_date, market='CN_STOCK_A')\n", 54 | "#print(inst)\n", 55 | "instruments = ['600519']\n", 56 | "#instruments = QA_code\n", 57 | "hists = QA.QA_fetch_stock_day_adv(instruments, start_date, end_date).data\n", 58 | "hist = hists\n" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 3, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "## load data function\n", 68 | "def load_data(stock, seq_len):\n", 69 | " # stock 是一个input的dataframe\n", 70 | " amount_of_features = len(stock.columns)\n", 71 | " data = stock.as_matrix() #pd.DataFrame(stock)\n", 72 | " sequence_length = seq_len + 1\n", 73 | " result = []\n", 74 | " for index in range(len(data) - sequence_length):\n", 75 | " result.append(data[index: index + sequence_length])\n", 76 | "\n", 77 | " result = np.array(result)\n", 78 | " row = round(0.9 * result.shape[0])\n", 79 | " train = result[:int(row), :]\n", 80 | " x_train = train[:, :-1]\n", 81 | " y_train = train[:, -1][:,-1]\n", 82 | " x_test = result[int(row):, :-1]\n", 83 | " y_test = result[int(row):, -1][:,-1]\n", 84 | "\n", 85 | " x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], amount_of_features))\n", 86 | " x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], amount_of_features)) \n", 87 | "\n", 88 | " return [x_train, y_train, x_test, y_test]\n", 89 | "\n", 90 | "def build_model(layers):\n", 91 | " model = Sequential()\n", 92 | "\n", 93 | " model.add(LSTM(\n", 94 | " input_dim=layers[0],\n", 95 | " output_dim=layers[1],\n", 96 | " return_sequences=True))\n", 97 | " model.add(Dropout(0.2))\n", 98 | "\n", 99 | " model.add(LSTM(\n", 100 | " layers[2],\n", 101 | " return_sequences=False))\n", 102 | " model.add(Dropout(0.2))\n", 103 | "\n", 104 | " model.add(Dense(\n", 105 | " output_dim=layers[2]))\n", 106 | " model.add(Activation(\"linear\"))\n", 107 | "\n", 108 | " start = time.time()\n", 109 | " model.compile(loss=\"mse\", optimizer=\"rmsprop\",metrics=['accuracy'])\n", 110 | " print(\"Compilation Time : \", time.time() - start)\n", 111 | " return model\n", 112 | "\n", 113 | "def build_model2(layers):\n", 114 | " d = 0.2\n", 115 | " model = Sequential()\n", 116 | " model.add(LSTM(128, input_shape=(layers[1], layers[0]), return_sequences=True))\n", 117 | " model.add(Dropout(d))\n", 118 | " model.add(LSTM(64, input_shape=(layers[1], layers[0]), return_sequences=False))\n", 119 | " model.add(Dropout(d))\n", 120 | " model.add(Dense(16,init='uniform',activation='relu')) \n", 121 | " model.add(Dense(1,init='uniform',activation='relu'))\n", 122 | " model.compile(loss='mse',optimizer='adam',metrics=['accuracy'])\n", 123 | " return model" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": 4, 129 | "metadata": {}, 130 | "outputs": [ 131 | { 132 | "name": "stderr", 133 | "output_type": "stream", 134 | "text": [ 135 | "QUANTAXIS>> The Pic has been saved to your path: ./QA_index_day_None_.html\n" 136 | ] 137 | } 138 | ], 139 | "source": [ 140 | "data=QA.QA_fetch_index_day_adv('000001','2010-01-01','2019-03-01')\n", 141 | "data.plot()\n", 142 | "plt.show()" 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": 5, 148 | "metadata": {}, 149 | "outputs": [ 150 | { 151 | "name": "stderr", 152 | "output_type": "stream", 153 | "text": [ 154 | "QUANTAXIS>> The Pic has been saved to your path: ./QA_index_day_None_.html\n" 155 | ] 156 | } 157 | ], 158 | "source": [ 159 | "#data = hist\n", 160 | "#data.plot()\n", 161 | "#plt.show()" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": 6, 167 | "metadata": {}, 168 | "outputs": [], 169 | "source": [ 170 | "used_data=pd.concat([data.open,data.high,data.close],axis=1)" 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "execution_count": 7, 176 | "metadata": {}, 177 | "outputs": [ 178 | { 179 | "name": "stderr", 180 | "output_type": "stream", 181 | "text": [ 182 | "/Volumes/QuantOsUSB/QuantOsUSB/kivy.app/Contents/Resources/venv/lib/python3.6/site-packages/ipykernel_launcher.py:5: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.\n", 183 | " \"\"\"\n" 184 | ] 185 | } 186 | ], 187 | "source": [ 188 | "window = 5\n", 189 | "X_train, y_train, X_test, y_test = load_data(used_data[::-1], window)" 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": 8, 195 | "metadata": {}, 196 | "outputs": [ 197 | { 198 | "data": { 199 | "text/plain": [ 200 | "array([[[2954.4 , 2994.01, 2994.01],\n", 201 | " [2950.05, 2965.3 , 2940.95],\n", 202 | " [2939.93, 2997.49, 2953.82],\n", 203 | " [2969.1 , 2995.68, 2941.52],\n", 204 | " [2838.39, 2961.8 , 2961.28]],\n", 205 | "\n", 206 | " [[2950.05, 2965.3 , 2940.95],\n", 207 | " [2939.93, 2997.49, 2953.82],\n", 208 | " [2969.1 , 2995.68, 2941.52],\n", 209 | " [2838.39, 2961.8 , 2961.28],\n", 210 | " [2749.46, 2804.23, 2804.23]],\n", 211 | "\n", 212 | " [[2939.93, 2997.49, 2953.82],\n", 213 | " [2969.1 , 2995.68, 2941.52],\n", 214 | " [2838.39, 2961.8 , 2961.28],\n", 215 | " [2749.46, 2804.23, 2804.23],\n", 216 | " [2759.94, 2794.01, 2751.8 ]],\n", 217 | "\n", 218 | " ...,\n", 219 | "\n", 220 | " [[2908.87, 2921.27, 2898.14],\n", 221 | " [2927.26, 2939.05, 2911.41],\n", 222 | " [2928.3 , 2933.41, 2927.08],\n", 223 | " [2850.33, 2923.77, 2922.95],\n", 224 | " [2798.74, 2850.42, 2841.04]],\n", 225 | "\n", 226 | " [[2927.26, 2939.05, 2911.41],\n", 227 | " [2928.3 , 2933.41, 2927.08],\n", 228 | " [2850.33, 2923.77, 2922.95],\n", 229 | " [2798.74, 2850.42, 2841.04],\n", 230 | " [2837.61, 2854.7 , 2810.95]],\n", 231 | "\n", 232 | " [[2928.3 , 2933.41, 2927.08],\n", 233 | " [2850.33, 2923.77, 2922.95],\n", 234 | " [2798.74, 2850.42, 2841.04],\n", 235 | " [2837.61, 2854.7 , 2810.95],\n", 236 | " [2868.73, 2880.56, 2848.55]]])" 237 | ] 238 | }, 239 | "execution_count": 8, 240 | "metadata": {}, 241 | "output_type": "execute_result" 242 | } 243 | ], 244 | "source": [ 245 | "X_train" 246 | ] 247 | }, 248 | { 249 | "cell_type": "code", 250 | "execution_count": null, 251 | "metadata": {}, 252 | "outputs": [ 253 | { 254 | "name": "stderr", 255 | "output_type": "stream", 256 | "text": [ 257 | "/Volumes/QuantOsUSB/QuantOsUSB/kivy.app/Contents/Resources/venv/lib/python3.6/site-packages/ipykernel_launcher.py:54: UserWarning: Update your `Dense` call to the Keras 2 API: `Dense(16, activation=\"relu\", kernel_initializer=\"uniform\")`\n", 258 | "/Volumes/QuantOsUSB/QuantOsUSB/kivy.app/Contents/Resources/venv/lib/python3.6/site-packages/ipykernel_launcher.py:55: UserWarning: Update your `Dense` call to the Keras 2 API: `Dense(1, activation=\"relu\", kernel_initializer=\"uniform\")`\n" 259 | ] 260 | } 261 | ], 262 | "source": [ 263 | "model = build_model2([3,window,1])" 264 | ] 265 | }, 266 | { 267 | "cell_type": "code", 268 | "execution_count": null, 269 | "metadata": {}, 270 | "outputs": [ 271 | { 272 | "name": "stderr", 273 | "output_type": "stream", 274 | "text": [ 275 | "/Volumes/QuantOsUSB/QuantOsUSB/kivy.app/Contents/Resources/venv/lib/python3.6/site-packages/ipykernel_launcher.py:7: UserWarning: The `nb_epoch` argument in `fit` has been renamed `epochs`.\n", 276 | " import sys\n" 277 | ] 278 | } 279 | ], 280 | "source": [ 281 | "model.fit(\n", 282 | " X_train,\n", 283 | " y_train,\n", 284 | " batch_size=512,\n", 285 | " nb_epoch=500,\n", 286 | " validation_split=0.1,\n", 287 | " verbose=0)" 288 | ] 289 | }, 290 | { 291 | "cell_type": "code", 292 | "execution_count": null, 293 | "metadata": {}, 294 | "outputs": [], 295 | "source": [ 296 | "# print(X_test[-1])\n", 297 | "diff=[]\n", 298 | "ratio=[]\n", 299 | "p = model.predict(X_test)\n", 300 | "for u in range(len(y_test)):\n", 301 | " pr = p[u][0]\n", 302 | " ratio.append((y_test[u]/pr)-1)\n", 303 | " diff.append(abs(y_test[u]- pr))\n", 304 | " #print(u, y_test[u], pr, (y_test[u]/pr)-1, abs(y_test[u]- pr))" 305 | ] 306 | }, 307 | { 308 | "cell_type": "code", 309 | "execution_count": null, 310 | "metadata": {}, 311 | "outputs": [], 312 | "source": [ 313 | "import matplotlib.pyplot as plt2\n", 314 | "plt2.figure(figsize=(16,16)) #图表长宽量 16,16\n", 315 | "plt2.grid(True)\n", 316 | "plt2.plot(p,color='red', label='prediction') #预测\n", 317 | "plt2.plot(y_test,color='blue', label='y_test')\n", 318 | "plt2.legend(loc='upper left')\n", 319 | "plt2.show()" 320 | ] 321 | }, 322 | { 323 | "cell_type": "code", 324 | "execution_count": null, 325 | "metadata": {}, 326 | "outputs": [], 327 | "source": [] 328 | } 329 | ], 330 | "metadata": { 331 | "kernelspec": { 332 | "display_name": "Python 3", 333 | "language": "python", 334 | "name": "python3" 335 | }, 336 | "language_info": { 337 | "codemirror_mode": { 338 | "name": "ipython", 339 | "version": 3 340 | }, 341 | "file_extension": ".py", 342 | "mimetype": "text/x-python", 343 | "name": "python", 344 | "nbconvert_exporter": "python", 345 | "pygments_lexer": "ipython3", 346 | "version": "3.6.5" 347 | } 348 | }, 349 | "nbformat": 4, 350 | "nbformat_minor": 2 351 | } 352 | -------------------------------------------------------------------------------- /QA选股.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 24, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import QUANTAXIS as QA\n", 10 | "import matplotlib.pyplot as plt\n", 11 | "import numpy as np\n", 12 | "import pandas as pd\n", 13 | "from talib import *\n", 14 | "import time\n", 15 | "import datetime\n" 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": 25, 21 | "metadata": {}, 22 | "outputs": [ 23 | { 24 | "data": { 25 | "text/plain": [ 26 | "'\\nQA_code_list = QA.QA_fetch_stock_list_adv()\\nQA_code_list\\nQA_code = QA_code_list.code.tolist() \\nQA_code\\nQA_qfq_data = QA.QA_fetch_stock_day_adv(QA_code,start,end).to_qfq() \\nQA_qfq = QA_qfq_data.data\\nQA_qfq\\n'" 27 | ] 28 | }, 29 | "execution_count": 25, 30 | "metadata": {}, 31 | "output_type": "execute_result" 32 | } 33 | ], 34 | "source": [ 35 | "'''\n", 36 | "QA_code_list = QA.QA_fetch_stock_list_adv()\n", 37 | "QA_code_list\n", 38 | "QA_code = QA_code_list.code.tolist() \n", 39 | "QA_code\n", 40 | "QA_qfq_data = QA.QA_fetch_stock_day_adv(QA_code,start,end).to_qfq() \n", 41 | "QA_qfq = QA_qfq_data.data\n", 42 | "QA_qfq\n", 43 | "'''" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": 26, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "def market_list():\n", 53 | " import QUANTAXIS as QA\n", 54 | " return list(QA.QA_fetch_stock_list_adv().code)" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": 29, 60 | "metadata": {}, 61 | "outputs": [], 62 | "source": [ 63 | "# 定义均线金叉、长期均线上扬的选股函数\n", 64 | "def ma_select(code_list=market_list(), date=None, short=10, long=100):\n", 65 | "#def ma_select(code_list= QA_code_list.code.tolist() , date=None, short=10, long=100):\n", 66 | " \"\"\"\n", 67 | " :param code_list: 选股范围,默认全市场\n", 68 | " :param date: 选股日期,默认None为现在\n", 69 | " :param short: 短期均线\n", 70 | " :param long: 长期均线\n", 71 | " :return: 返回选后的股票列表\n", 72 | " \"\"\"\n", 73 | " now = datetime.now().strftime('%Y-%m-%d')\n", 74 | " if date is None:\n", 75 | " date = now\n", 76 | " date = QA.QA_util_get_real_date(date)\n", 77 | " if date == now and datetime.now().strftime('%H:%M') < '09:30':\n", 78 | " date = QA.QA_util_get_last_day(date, n=1)\n", 79 | " long_days_ago = QA.QA_util_get_last_day(date=date, n=long)\n", 80 | " data = QA.QA_fetch_stock_day_adv(code=code_list, start=long_days_ago, end=date)\n", 81 | " data = data.to_qfq()\n", 82 | " ind_data = data.add_func(QA.QA_indicator_MA, short, long)\n", 83 | " # 选取最后两日的数据\n", 84 | " ind_1 = ind_data.xs(date, level=0)\n", 85 | " ind_2 = ind_data.xs(QA.QA_util_get_last_day(date, 1), level=0)\n", 86 | " # 最后两日都有数据的股票代码\n", 87 | " code = list(set(ind_1.index) & set(ind_2.index))\n", 88 | " # 将最后两日的数据切齐\n", 89 | " ind_1 = ind_1.reindex(code)\n", 90 | " ind_2 = ind_2.reindex(code)\n", 91 | " # 选取最后一天均线大于前一天均线的代码列表\n", 92 | " code = list(ind_1[ind_1['MA'+str(long)] > ind_2['MA'+str(long)]].index)\n", 93 | " ind_1 = ind_1.reindex(code)\n", 94 | " # 选取均线金叉的股票代码\n", 95 | " code = list(ind_1[ind_1['MA'+str(short)] > ind_1['MA'+str(long)]].index)\n", 96 | " return code\n" 97 | ] 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": null, 102 | "metadata": {}, 103 | "outputs": [], 104 | "source": [] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": null, 109 | "metadata": {}, 110 | "outputs": [], 111 | "source": [] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": null, 116 | "metadata": {}, 117 | "outputs": [], 118 | "source": [] 119 | } 120 | ], 121 | "metadata": { 122 | "kernelspec": { 123 | "display_name": "Python 3", 124 | "language": "python", 125 | "name": "python3" 126 | }, 127 | "language_info": { 128 | "codemirror_mode": { 129 | "name": "ipython", 130 | "version": 3 131 | }, 132 | "file_extension": ".py", 133 | "mimetype": "text/x-python", 134 | "name": "python", 135 | "nbconvert_exporter": "python", 136 | "pygments_lexer": "ipython3", 137 | "version": "3.6.5" 138 | } 139 | }, 140 | "nbformat": 4, 141 | "nbformat_minor": 2 142 | } 143 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 安装kivy: 3 | 下载kivy3.dmg拷贝kivy3.app到应用程序目录,改名kivy.app 4 | 5 | 建立 kivy.app 终端关联 6 | 7 | ln -s /Applications/Kivy.app/Contents/Resources/script /usr/local/bin/kivy 8 | 9 | 使用brew安装ta-lib库和mongodb:brew.sh去参考 10 | 安装brew管理: 11 | /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 12 | 13 | 安装talib库: 14 | brew install ta-lib 15 | 16 | 安装mongodb数据库服务器环境: 17 | brew install mongodb 18 | 19 | 开启终端安装配置环境 20 | kivy后输入import kivy测试kivy环境是否正常。正常后下面配置 21 | 22 | 终端kivy环境配置: 23 | kivy -m pip install -r kivy-m_pip_freeze.txt 24 | 25 | kivy -m jupyter notebook 或 kivy -m jupyterlab进入web后开启终端 26 | 27 | web终端虚拟环境python配置: 28 | python -m pip install -r python-m_pip_freeze.txt 29 | 30 | web终端环境配置: 31 | pip install -r pip_freeze.txt 32 | -------------------------------------------------------------------------------- /T0backtest.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "ename": "AttributeError", 10 | "evalue": "'NoneType' object has no attribute 'add_account'", 11 | "output_type": "error", 12 | "traceback": [ 13 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 14 | "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", 15 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 113\u001b[0m \u001b[0mend\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'2018-12-10'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 114\u001b[0m \u001b[0mcode_list\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'000001'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 115\u001b[0;31m commission_fee=0.00015)\n\u001b[0m\u001b[1;32m 116\u001b[0m \u001b[0mbacktest\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mstart_market\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 117\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", 16 | "\u001b[0;32m\u001b[0m in \u001b[0;36m__init__\u001b[0;34m(self, market_type, frequence, start, end, code_list, commission_fee)\u001b[0m\n\u001b[1;32m 90\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m__init__\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmarket_type\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfrequence\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstart\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mend\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcode_list\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcommission_fee\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 91\u001b[0m \u001b[0msuper\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__init__\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmarket_type\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfrequence\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstart\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mend\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcode_list\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcommission_fee\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 92\u001b[0;31m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0maccount\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mportfolio\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd_account\u001b[0m\u001b[0;34m(\u001b[0m \u001b[0mMAMINT0Strategy\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0muser_cookie\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0muser\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0muser_cookie\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mportfolio_cookie\u001b[0m\u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mportfolio\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mportfolio_cookie\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 93\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 94\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mafter_success\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 17 | "\u001b[0;31mAttributeError\u001b[0m: 'NoneType' object has no attribute 'add_account'" 18 | ] 19 | } 20 | ], 21 | "source": [ 22 | "\n", 23 | "# coding: utf-8\n", 24 | "\n", 25 | "# In[1]:\n", 26 | "\n", 27 | "\n", 28 | "from QUANTAXIS.QAARP.QAStrategy import QA_Strategy\n", 29 | "from QUANTAXIS.QAARP.QAAccount import QA_Account\n", 30 | "from QUANTAXIS.QAUtil.QAParameter import (AMOUNT_MODEL, MARKET_TYPE,\n", 31 | " FREQUENCE, ORDER_DIRECTION,\n", 32 | " ORDER_MODEL, RUNNING_ENVIRONMENT)\n", 33 | "\n", 34 | "\n", 35 | "import random\n", 36 | "\n", 37 | "\n", 38 | "# In[2]:\n", 39 | "\n", 40 | "\n", 41 | "class MAMINT0Strategy(QA_Account):\n", 42 | " def __init__(self, user_cookie='default', portfolio_cookie='default', init_hold={'000001': 10000}):\n", 43 | " super().__init__(user_cookie, portfolio_cookie, init_hold=init_hold)\n", 44 | " self.account_cookie = 'T0BACKTEST'\n", 45 | " self.running_environment = RUNNING_ENVIRONMENT.TZERO\n", 46 | " self.frequence = FREQUENCE.ONE_MIN\n", 47 | " self.market_type = MARKET_TYPE.STOCK_CN\n", 48 | "\n", 49 | " self.result = {}\n", 50 | "\n", 51 | " def on_bar(self, event):\n", 52 | "\n", 53 | " # min5= self.market_data.min5\n", 54 | " # min15= self.market_data.min15\n", 55 | "\n", 56 | " # min5macd=QA.QA_indicator_MACD(min5)\n", 57 | " # min15macd=QA.QA_indicator_MACD(min15)\n", 58 | " # self.result['min5macd']=min5macd\n", 59 | "\n", 60 | " # self.cash_available # 当前剩余现金\n", 61 | " # self.sell_available # 当前可卖股票\n", 62 | " # self.history_table # 当前的历史交易\n", 63 | " # self.hold_time # 当前的持仓时间\n", 64 | " # self.hold_price # 当前持仓的成本价格\n", 65 | " # self.get_orders # 获取历史订单\n", 66 | " # self.allow_sellopen # 账户是否允许卖空\n", 67 | " # self.allow_t0 # 账户是否允许t0\n", 68 | " # self.commission_coeff # 账户的手续费(可自行调整)\n", 69 | "\n", 70 | " try:\n", 71 | " for item in event.market_data.code:\n", 72 | "\n", 73 | " print('================')\n", 74 | " print(self.sell_available)\n", 75 | " print('================')\n", 76 | " print(self.hold_available)\n", 77 | " if self.sell_available.get(item, 0) > 0:\n", 78 | " event.send_order(account_cookie=self.account_cookie,\n", 79 | " amount=self.sell_available[item], amount_model=AMOUNT_MODEL.BY_AMOUNT,\n", 80 | " time=self.current_time, code=item, price=0,\n", 81 | " order_model=ORDER_MODEL.MARKET, towards=ORDER_DIRECTION.SELL,\n", 82 | " market_type=self.market_type, frequence=self.frequence,\n", 83 | " broker_name=self.broker\n", 84 | " )\n", 85 | " else:\n", 86 | " event.send_order(account_cookie=self.account_cookie,\n", 87 | " amount=100, amount_model=AMOUNT_MODEL.BY_AMOUNT,\n", 88 | " time=self.current_time, code=item, price=0,\n", 89 | " order_model=ORDER_MODEL.MARKET, towards=ORDER_DIRECTION.BUY,\n", 90 | " market_type=self.market_type, frequence=self.frequence,\n", 91 | " broker_name=self.broker)\n", 92 | " except:\n", 93 | " pass\n", 94 | "\n", 95 | "\n", 96 | "# In[3]:\n", 97 | "\n", 98 | "\n", 99 | "from QUANTAXIS.QAARP.QARisk import QA_Risk\n", 100 | "from QUANTAXIS.QAARP.QAUser import QA_User\n", 101 | "from QUANTAXIS.QAApplication.QABacktest import QA_Backtest\n", 102 | "from QUANTAXIS.QAUtil.QALogs import QA_util_log_info\n", 103 | "from QUANTAXIS.QAUtil.QAParameter import FREQUENCE, MARKET_TYPE\n", 104 | "\n", 105 | "\n", 106 | "class Backtest(QA_Backtest):\n", 107 | " '''\n", 108 | " 多线程模式回测示例\n", 109 | " '''\n", 110 | "\n", 111 | " def __init__(self, market_type, frequence, start, end, code_list, commission_fee):\n", 112 | " super().__init__(market_type, frequence, start, end, code_list, commission_fee)\n", 113 | " self.account = self.portfolio.add_account( MAMINT0Strategy(user_cookie=self.user.user_cookie, portfolio_cookie= self.portfolio.portfolio_cookie))\n", 114 | "\n", 115 | " def after_success(self):\n", 116 | " QA_util_log_info(self.account.history_table)\n", 117 | " risk = QA_Risk(self.account, benchmark_code='000300',\n", 118 | " benchmark_type=MARKET_TYPE.INDEX_CN)\n", 119 | "\n", 120 | " print(risk().T)\n", 121 | " self.user.save()\n", 122 | " risk.save()\n", 123 | " risk.plot_assets_curve()\n", 124 | " print(risk.profit_construct)\n", 125 | "\n", 126 | "\n", 127 | "# In[4]:\n", 128 | "\n", 129 | "\n", 130 | "import QUANTAXIS as QA\n", 131 | "backtest = Backtest(market_type=MARKET_TYPE.STOCK_CN,\n", 132 | " frequence=FREQUENCE.FIFTEEN_MIN,\n", 133 | " start='2018-11-01',\n", 134 | " end='2018-12-10',\n", 135 | " code_list=['000001'],\n", 136 | " commission_fee=0.00015)\n", 137 | "backtest.start_market()\n", 138 | "\n", 139 | "backtest.run()\n", 140 | "backtest.stop()\n", 141 | "\n", 142 | "\n", 143 | "# In[5]:\n", 144 | "\n", 145 | "\n", 146 | "print(backtest.account.history_table)" 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": null, 152 | "metadata": {}, 153 | "outputs": [], 154 | "source": [] 155 | } 156 | ], 157 | "metadata": { 158 | "kernelspec": { 159 | "display_name": "Python 3", 160 | "language": "python", 161 | "name": "python3" 162 | }, 163 | "language_info": { 164 | "codemirror_mode": { 165 | "name": "ipython", 166 | "version": 3 167 | }, 168 | "file_extension": ".py", 169 | "mimetype": "text/x-python", 170 | "name": "python", 171 | "nbconvert_exporter": "python", 172 | "pygments_lexer": "ipython3", 173 | "version": "3.6.5" 174 | } 175 | }, 176 | "nbformat": 4, 177 | "nbformat_minor": 2 178 | } 179 | -------------------------------------------------------------------------------- /hikyuu量化/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/hikyuu量化/.DS_Store -------------------------------------------------------------------------------- /macd.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "ename": "TypeError", 10 | "evalue": "__init__() got an unexpected keyword argument 'username'", 11 | "output_type": "error", 12 | "traceback": [ 13 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 14 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 15 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 28\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 29\u001b[0m \u001b[0;31m# create account\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 30\u001b[0;31m \u001b[0muser\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mQA\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mQA_User\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0musername\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'quantaxis'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpassword\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'quantaxis'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 31\u001b[0m \u001b[0mportfolio\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0muser\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnew_portfolio\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'qatestportfolio'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 32\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", 16 | "\u001b[0;31mTypeError\u001b[0m: __init__() got an unexpected keyword argument 'username'" 17 | ] 18 | } 19 | ], 20 | "source": [ 21 | "# -*- coding: utf-8 -*-\n", 22 | "# Demo: MACD strategy\n", 23 | "# src: ./test_backtest/MACD_JCSC.py\n", 24 | "# jupyter: ./test_backtest/QUANTAXIS回测分析全过程讲解.ipynb\n", 25 | "# paper: ./test_backtest/QUANTAXIS回测分析全过程讲解.md\n", 26 | "\n", 27 | "import QUANTAXIS as QA\n", 28 | "import numpy as np\n", 29 | "import pandas as pd\n", 30 | "import datetime\n", 31 | "st1=datetime.datetime.now()\n", 32 | "# define the MACD strategy\n", 33 | "def MACD_JCSC(dataframe, SHORT=12, LONG=26, M=9):\n", 34 | " \"\"\"\n", 35 | " 1.DIF向上突破DEA,买入信号参考。\n", 36 | " 2.DIF向下跌破DEA,卖出信号参考。\n", 37 | " \"\"\"\n", 38 | " CLOSE = dataframe.close\n", 39 | " DIFF = QA.EMA(CLOSE, SHORT) - QA.EMA(CLOSE, LONG)\n", 40 | " DEA = QA.EMA(DIFF, M)\n", 41 | " MACD = 2*(DIFF-DEA)\n", 42 | "\n", 43 | " CROSS_JC = QA.CROSS(DIFF, DEA)\n", 44 | " CROSS_SC = QA.CROSS(DEA, DIFF)\n", 45 | " ZERO = 0\n", 46 | " return pd.DataFrame({'DIFF': DIFF, 'DEA': DEA, 'MACD': MACD, 'CROSS_JC': CROSS_JC, 'CROSS_SC': CROSS_SC, 'ZERO': ZERO})\n", 47 | "\n", 48 | "\n", 49 | "# create account\n", 50 | "user = QA.QA_User(username='quantaxis', password='quantaxis')\n", 51 | "portfolio = user.new_portfolio('qatestportfolio')\n", 52 | "\n", 53 | "\n", 54 | "Account = portfolio.new_account(account_cookie='macd_stock', init_cash=1000000)\n", 55 | "Broker = QA.QA_BacktestBroker()\n", 56 | "\n", 57 | "QA.QA_SU_save_strategy('MACD_JCSC','Indicator',Account.account_cookie)\n", 58 | "# get data from mongodb\n", 59 | "data = QA.QA_fetch_stock_day_adv(\n", 60 | " ['000001', '000002', '000004', '600000'], '2017-09-01', '2018-05-20')\n", 61 | "data = data.to_qfq()\n", 62 | "\n", 63 | "# add indicator\n", 64 | "ind = data.add_func(MACD_JCSC)\n", 65 | "# ind.xs('000001',level=1)['2018-01'].plot()\n", 66 | "\n", 67 | "data_forbacktest=data.select_time('2018-01-01','2018-05-01')\n", 68 | "\n", 69 | "\n", 70 | "for items in data_forbacktest.panel_gen:\n", 71 | " for item in items.security_gen:\n", 72 | " daily_ind=ind.loc[item.index]\n", 73 | "\n", 74 | " if daily_ind.CROSS_JC.iloc[0]>0:\n", 75 | " order=Account.send_order(\n", 76 | " code=item.code[0], \n", 77 | " time=item.date[0], \n", 78 | " amount=1000, \n", 79 | " towards=QA.ORDER_DIRECTION.BUY, \n", 80 | " price=0, \n", 81 | " order_model=QA.ORDER_MODEL.CLOSE, \n", 82 | " amount_model=QA.AMOUNT_MODEL.BY_AMOUNT\n", 83 | " )\n", 84 | " #print(item.to_json()[0])\n", 85 | " Broker.receive_order(QA.QA_Event(order=order,market_data=item))\n", 86 | " trade_mes=Broker.query_orders(Account.account_cookie,'filled')\n", 87 | " res=trade_mes.loc[order.account_cookie,order.realorder_id]\n", 88 | " order.trade(res.trade_id,res.trade_price,res.trade_amount,res.trade_time)\n", 89 | " elif daily_ind.CROSS_SC.iloc[0]>0:\n", 90 | " #print(item.code)\n", 91 | " if Account.sell_available.get(item.code[0], 0)>0:\n", 92 | " order=Account.send_order(\n", 93 | " code=item.code[0], \n", 94 | " time=item.date[0], \n", 95 | " amount=Account.sell_available.get(item.code[0], 0), \n", 96 | " towards=QA.ORDER_DIRECTION.SELL, \n", 97 | " price=0, \n", 98 | " order_model=QA.ORDER_MODEL.MARKET, \n", 99 | " amount_model=QA.AMOUNT_MODEL.BY_AMOUNT\n", 100 | " )\n", 101 | " #print\n", 102 | " Broker.receive_order(QA.QA_Event(order=order,market_data=item))\n", 103 | " trade_mes=Broker.query_orders(Account.account_cookie,'filled')\n", 104 | " res=trade_mes.loc[order.account_cookie,order.realorder_id]\n", 105 | " order.trade(res.trade_id,res.trade_price,res.trade_amount,res.trade_time)\n", 106 | " Account.settle()\n", 107 | "\n", 108 | "print('TIME -- {}'.format(datetime.datetime.now()-st1))\n", 109 | "print(Account.history)\n", 110 | "print(Account.history_table)\n", 111 | "print(Account.daily_hold)\n", 112 | "\n", 113 | "# create Risk analysis\n", 114 | "Risk = QA.QA_Risk(Account)\n", 115 | "\n", 116 | "user.save()\n", 117 | "Risk.save()\n", 118 | "\n", 119 | "\n", 120 | "# print(Risk.message)\n", 121 | "# print(Risk.assets)\n", 122 | "# Risk.plot_assets_curve()\n", 123 | "# plt=Risk.plot_dailyhold()\n", 124 | "# plt.show()\n", 125 | "# plt1=Risk.plot_signal()\n", 126 | "# plt.show()\n", 127 | "\n", 128 | "# performance=QA.QA_Performance(Account)\n", 129 | "# plt=performance.plot_pnlmoney(performance.pnl_fifo)\n", 130 | "# plt.show()\n", 131 | "# Risk.assets.plot()\n", 132 | "# Risk.benchmark_assets.plot()\n", 133 | "\n", 134 | "# save result\n", 135 | "\n", 136 | "#account_info = QA.QA_fetch_account({'account_cookie': 'user_admin_macd'})\n", 137 | "#account = QA.QA_Account().from_message(account_info[0])\n", 138 | "#print(account)\n", 139 | "\n" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": {}, 146 | "outputs": [], 147 | "source": [] 148 | } 149 | ], 150 | "metadata": { 151 | "kernelspec": { 152 | "display_name": "Python 3", 153 | "language": "python", 154 | "name": "python3" 155 | }, 156 | "language_info": { 157 | "codemirror_mode": { 158 | "name": "ipython", 159 | "version": 3 160 | }, 161 | "file_extension": ".py", 162 | "mimetype": "text/x-python", 163 | "name": "python", 164 | "nbconvert_exporter": "python", 165 | "pygments_lexer": "ipython3", 166 | "version": "3.6.5" 167 | } 168 | }, 169 | "nbformat": 4, 170 | "nbformat_minor": 2 171 | } 172 | -------------------------------------------------------------------------------- /pip install -r/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/pip install -r/.DS_Store -------------------------------------------------------------------------------- /pip install -r/bf/abupy.txt: -------------------------------------------------------------------------------- 1 | abupy==0.4.0 2 | appnope==0.1.0 3 | atomicwrites==1.2.1 4 | attrs==18.2.0 5 | backcall==0.1.0 6 | bleach==3.0.2 7 | bokeh==1.0.1 8 | certifi==2018.10.15 9 | chardet==3.0.4 10 | cycler==0.10.0 11 | Cython==0.28.2 12 | decorator==4.3.0 13 | defusedxml==0.5.0 14 | docutils==0.14 15 | entrypoints==0.2.3 16 | idna==2.7 17 | ipykernel==5.1.0 18 | ipython==7.1.1 19 | ipython-genutils==0.2.0 20 | ipywidgets==7.4.2 21 | jedi==0.13.1 22 | Jinja2==2.10 23 | jsonschema==2.6.0 24 | jupyter-client==5.2.3 25 | jupyter-core==4.4.0 26 | jupyterlab==0.35.4 27 | jupyterlab-server==0.2.0 28 | kiwisolver==1.0.1 29 | MarkupSafe==1.1.0 30 | matplotlib==3.0.2 31 | mistune==0.8.4 32 | more-itertools==4.3.0 33 | mpl-finance==0.10.0 34 | nbconvert==5.4.0 35 | nbformat==4.4.0 36 | notebook==5.7.1 37 | numpy==1.15.4 38 | osxrelocator==1.0.1 39 | packaging==18.0 40 | pandas==0.23.4 41 | pandocfilters==1.4.2 42 | parso==0.3.1 43 | patsy==0.5.1 44 | pexpect==4.6.0 45 | pickleshare==0.7.5 46 | Pillow==5.3.0 47 | pluggy==0.8.0 48 | prometheus-client==0.4.2 49 | prompt-toolkit==2.0.7 50 | psutil==5.4.8 51 | ptyprocess==0.6.0 52 | py==1.7.0 53 | Pygments==2.2.0 54 | pyparsing==2.3.0 55 | pytest==4.0.0 56 | python-dateutil==2.7.5 57 | pytz==2018.7 58 | PyYAML==3.13 59 | pyzmq==17.1.2 60 | requests==2.20.1 61 | scikit-learn==0.20.0 62 | scipy==1.1.0 63 | seaborn==0.9.0 64 | Send2Trash==1.5.0 65 | six==1.11.0 66 | statsmodels==0.9.0 67 | terminado==0.8.1 68 | testpath==0.4.2 69 | toolz==0.9.0 70 | tornado==5.1.1 71 | traitlets==4.3.2 72 | urllib3==1.24.1 73 | wcwidth==0.1.7 74 | webencodings==0.5.1 75 | widgetsnbextension==3.4.2 76 | -------------------------------------------------------------------------------- /pip install -r/bf/kivy.txt: -------------------------------------------------------------------------------- 1 | absl-py==0.6.1 2 | abupy==0.4.0 3 | altgraph==0.16.1 4 | appdirs==1.4.3 5 | appnope==0.1.0 6 | APScheduler==3.5.3 7 | asn1crypto==0.24.0 8 | astor==0.7.1 9 | atomicwrites==1.2.1 10 | attrs==17.4.0 11 | Automat==0.7.0 12 | backcall==0.1.0 13 | backports.functools-lru-cache==1.5 14 | bcolz==1.1.2 15 | beautifulsoup4==4.6.0 16 | better-exceptions==0.2.1 17 | bidict==0.17.5 18 | bleach==1.5.0 19 | bokeh==1.0.1 20 | bs4==0.0.1 21 | build==1.0.2 22 | buildozer==0.36 23 | cached-property==1.3.1 24 | certifi==2018.1.18 25 | cffi==1.11.5 26 | chardet==3.0.4 27 | Click==7.0 28 | colorama==0.3.9 29 | colorlog==3.1.4 30 | constantly==15.1.0 31 | coverage==4.5.2 32 | cryptography==2.4.1 33 | cssselect==1.0.3 34 | cycler==0.10.0 35 | Cython==0.28.2 36 | decorator==4.2.1 37 | defusedxml==0.5.0 38 | delegator.py==0.1.1 39 | demjson==2.2.4 40 | dill==0.2.5 41 | docutils==0.14 42 | dukpy==0.2.2 43 | entrypoints==0.2.3 44 | ExtensionClass==4.4 45 | Flask==1.0.2 46 | Flask-SocketIO==3.0.2 47 | funcat==0.3.2 48 | future==0.17.1 49 | gast==0.2.0 50 | greenlet==0.4.15 51 | grpcio==1.16.1 52 | h5py==2.8.0 53 | html5lib==0.9999999 54 | hyperlink==18.0.0 55 | idna==2.6 56 | incremental==17.5.0 57 | inflection==0.3.1 58 | ipykernel==4.6.1 59 | ipython==6.2.1 60 | ipython-genutils==0.2.0 61 | ipywidgets==7.4.2 62 | itsdangerous==1.1.0 63 | jaqs==0.6.12 64 | javascripthon==0.10 65 | jedi==0.11.1 66 | Jinja2==2.10 67 | jsonpickle==0.9.4 68 | jsonschema==2.6.0 69 | jupyter==1.0.0 70 | jupyter-client==5.1.0 71 | jupyter-console==6.0.0 72 | jupyter-core==4.3.0 73 | jupyter-echarts-pypkg==0.1.2 74 | jupyterlab==0.31.2 75 | jupyterlab-launcher==0.10.2 76 | jupyterlab-server==0.2.0 77 | Keras==2.2.4 78 | Keras-Applications==1.0.6 79 | Keras-Preprocessing==1.0.5 80 | kiwisolver==1.0.1 81 | line-profiler==2.1.2 82 | llvmlite==0.25.0 83 | lml==0.0.2 84 | loc==0.0.2 85 | lock==2018.3.25.2110 86 | Logbook==1.0.0 87 | lru-dict==1.1.6 88 | lxml==4.1.1 89 | macholib==1.11 90 | macropy3==1.1.0b2 91 | Markdown==3.0.1 92 | MarkupSafe==1.0 93 | matplotlib==3.0.2 94 | mistune==0.7.4 95 | module==0.2.1 96 | more-itertools==4.3.0 97 | motor==2.0.0 98 | mpl-finance==0.10.0 99 | msgpack==0.5.6 100 | msgpack-python==0.5.6 101 | mysql==0.0.2 102 | mysqlclient==1.3.13 103 | nbconvert==5.2.1 104 | nbformat==4.4.0 105 | notebook==5.0.0 106 | numba==0.40.1 107 | numpy==1.15.4 108 | osxrelocator==1.0.1 109 | packaging==18.0 110 | pandas==0.23.4 111 | pandocfilters==1.4.2 112 | parsel==1.5.1 113 | parso==0.1.1 114 | patsy==0.5.1 115 | pefile==2018.8.8 116 | pexpect==4.3.1 117 | pickleshare==0.7.4 118 | pika==0.12.0 119 | Pillow==5.3.0 120 | pluggy==0.6.0 121 | ply==3.11 122 | progressbar2==3.34.3 123 | prometheus-client==0.4.2 124 | prompt-toolkit==1.0.15 125 | protobuf==3.6.1 126 | psutil==5.4.8 127 | psycopg2==2.7.6.1 128 | ptyprocess==0.5.2 129 | py==1.5.2 130 | pyasn1==0.4.4 131 | pyasn1-modules==0.2.2 132 | pyconvert==0.6.3 133 | pycparser==2.19 134 | PyDispatcher==2.0.5 135 | pyecharts==0.5.11 136 | pyecharts-javascripthon==0.0.6 137 | pyecharts-jupyter-installer==0.0.3 138 | pyecharts-snapshot==0.1.9 139 | Pygments==2.2.0 140 | PyHamcrest==1.9.0 141 | PyInstaller==3.4 142 | pymongo==3.7.2 143 | PyMySQL==0.9.2 144 | pyOpenSSL==18.0.0 145 | pyparsing==2.2.0 146 | pytdx==1.67 147 | pytesseract==0.2.5 148 | pytest==3.4.0 149 | python-dateutil==2.6.1 150 | python-engineio==2.3.2 151 | python-for-android==0.6.0 152 | python-snappy==0.5.3 153 | python-socketio==2.0.0 154 | python-utils==2.2.0 155 | pytz==2017.3 156 | PyYAML==3.12 157 | pyzmq==16.0.2 158 | qtconsole==4.4.3 159 | Quandl==3.4.4 160 | quantaxis==1.2.0 161 | queuelib==1.5.0 162 | redis==3.0.1 163 | requests==2.18.4 164 | retrying==1.3.3 165 | rqalpha==3.2.0 166 | save==0.1 167 | scikit-learn==0.20.0 168 | scipy==1.1.0 169 | Scrapy==1.5.1 170 | seaborn==0.9.0 171 | selenium==3.141.0 172 | Send2Trash==1.5.0 173 | service-identity==17.0.0 174 | sh==1.12.4 175 | simplegeneric==0.8.1 176 | simplejson==3.16.0 177 | six==1.11.0 178 | sql==0.4.0 179 | SQLAlchemy==1.2.14 180 | statsmodels==0.9.0 181 | stock==2.0 182 | stock-info==1.0.0 183 | TA-Lib==0.4.16 184 | tabulate==0.8.2 185 | tensorboard==1.12.0 186 | tensorflow==1.12.0 187 | termcolor==1.1.0 188 | terminado==0.6 189 | testpath==0.3 190 | thriftpy==0.3.9 191 | toolz==0.9.0 192 | tornado==4.5.2 193 | traitlets==4.3.2 194 | tushare==1.2.17 195 | Twisted==18.9.0 196 | tzlocal==1.5.1 197 | urllib3==1.22 198 | virtualenv==16.1.0 199 | w3lib==1.19.0 200 | wcwidth==0.1.7 201 | webencodings==0.5.1 202 | Werkzeug==0.14.1 203 | widgetsnbextension==3.4.2 204 | xlrd==1.1.0 205 | XlsxWriter==1.0.2 206 | zenlog==1.1 207 | zope.interface==4.6.0 208 | -------------------------------------------------------------------------------- /pip install -r/bf/quantaxis.txt: -------------------------------------------------------------------------------- 1 | absl-py==0.6.1 2 | appnope==0.1.0 3 | APScheduler==3.5.3 4 | asn1crypto==0.24.0 5 | astor==0.7.1 6 | attrs==18.2.0 7 | Automat==0.7.0 8 | backcall==0.1.0 9 | beautifulsoup4==4.6.0 10 | bidict==0.17.5 11 | bleach==3.0.2 12 | bs4==0.0.1 13 | certifi==2018.10.15 14 | cffi==1.11.5 15 | chardet==3.0.4 16 | Click==7.0 17 | colorlog==3.1.4 18 | constantly==15.1.0 19 | cryptography==2.4.1 20 | cssselect==1.0.3 21 | cycler==0.10.0 22 | Cython==0.27.3 23 | decorator==4.3.0 24 | defusedxml==0.5.0 25 | delegator.py==0.1.1 26 | demjson==2.2.4 27 | docutils==0.14 28 | dukpy==0.2.2 29 | entrypoints==0.2.3 30 | Flask==1.0.2 31 | Flask-SocketIO==3.0.2 32 | Flask-Sockets==0.2.1 33 | future==0.17.1 34 | gast==0.2.0 35 | gevent==1.3.7 36 | gevent-websocket==0.10.1 37 | greenlet==0.4.15 38 | grpcio==1.16.1 39 | h5py==2.8.0 40 | hyperlink==18.0.0 41 | idna==2.7 42 | incremental==17.5.0 43 | ipykernel==5.1.0 44 | ipython==7.1.1 45 | ipython-genutils==0.2.0 46 | itsdangerous==1.1.0 47 | javascripthon==0.10 48 | jedi==0.13.1 49 | Jinja2==2.10 50 | jqdatasdk==1.4.9 51 | jsonschema==2.6.0 52 | jupyter-client==5.2.3 53 | jupyter-core==4.4.0 54 | jupyter-echarts-pypkg==0.1.2 55 | Keras==2.2.4 56 | Keras-Applications==1.0.6 57 | Keras-Preprocessing==1.0.5 58 | kiwisolver==1.0.1 59 | lml==0.0.2 60 | loc==0.0.2 61 | lxml==4.2.5 62 | macropy3==1.1.0b2 63 | Markdown==3.0.1 64 | MarkupSafe==1.1.0 65 | matplotlib==3.0.2 66 | mistune==0.8.3 67 | motor==2.0.0 68 | msgpack==0.5.6 69 | msgpack-python==0.4.7 70 | nbconvert==5.4.0 71 | nbformat==4.4.0 72 | notebook==5.7.1 73 | numpy==1.14.0 74 | osxrelocator==1.0.1 75 | pandas==0.23.4 76 | pandocfilters==1.4.2 77 | parsel==1.5.1 78 | parso==0.3.1 79 | patsy==0.5.1 80 | pexpect==4.6.0 81 | pickleshare==0.7.5 82 | Pillow==5.3.0 83 | ply==3.11 84 | prometheus-client==0.4.2 85 | prompt-toolkit==2.0.7 86 | protobuf==3.6.1 87 | ptyprocess==0.6.0 88 | pyasn1==0.4.4 89 | pyasn1-modules==0.2.2 90 | pyconvert==0.6.3 91 | pycparser==2.19 92 | PyDispatcher==2.0.5 93 | pyecharts==0.5.11 94 | pyecharts-javascripthon==0.0.6 95 | pyecharts-jupyter-installer==0.0.3 96 | pyecharts-snapshot==0.1.9 97 | Pygments==2.2.0 98 | PyHamcrest==1.9.0 99 | pymongo==3.7.2 100 | PyMySQL==0.9.2 101 | pyOpenSSL==18.0.0 102 | pyparsing==2.3.0 103 | pytdx==1.67 104 | pytesseract==0.2.5 105 | python-dateutil==2.7.5 106 | python-engineio==2.3.2 107 | python-socketio==2.0.0 108 | pytz==2018.7 109 | PyYAML==3.13 110 | pyzmq==17.1.2 111 | quantaxis==1.2.0 112 | queuelib==1.5.0 113 | requests==2.20.1 114 | retrying==1.3.3 115 | save==0.1 116 | scipy==1.1.0 117 | Scrapy==1.5.1 118 | seaborn==0.9.0 119 | selenium==3.141.0 120 | Send2Trash==1.5.0 121 | service-identity==17.0.0 122 | simplejson==3.16.0 123 | six==1.11.0 124 | SQLAlchemy==1.2.14 125 | statsmodels==0.9.0 126 | stock-info==1.0.0 127 | TA-Lib==0.4.17 128 | tabulate==0.8.2 129 | tensorboard==1.12.0 130 | tensorflow==1.12.0 131 | termcolor==1.1.0 132 | terminado==0.8.1 133 | testpath==0.4.2 134 | thriftpy==0.3.9 135 | tornado==5.1.1 136 | traitlets==4.3.2 137 | tushare==1.2.16 138 | Twisted==18.9.0 139 | tzlocal==1.5.1 140 | urllib3==1.24.1 141 | w3lib==1.19.0 142 | wcwidth==0.1.7 143 | webencodings==0.5.1 144 | Werkzeug==0.14.1 145 | zenlog==1.1 146 | zope.interface==4.6.0 147 | -------------------------------------------------------------------------------- /pip install -r/bf/rqalpha.txt: -------------------------------------------------------------------------------- 1 | appnope==0.1.0 2 | APScheduler==3.5.3 3 | asn1crypto==0.24.0 4 | atomicwrites==1.2.1 5 | attrs==17.4.0 6 | backcall==0.1.0 7 | backports.functools-lru-cache==1.5 8 | bcolz==1.1.2 9 | beautifulsoup4==4.6.0 10 | better-exceptions==0.2.1 11 | bleach==1.5.0 12 | bs4==0.0.1 13 | build==1.0.2 14 | cached-property==1.3.1 15 | certifi==2018.1.18 16 | cffi==1.11.5 17 | chardet==3.0.4 18 | click==6.7 19 | colorama==0.3.9 20 | coverage==4.5.2 21 | cryptography==2.4.1 22 | cycler==0.10.0 23 | Cython==0.28.2 24 | decorator==4.2.1 25 | defusedxml==0.5.0 26 | dill==0.2.5 27 | docutils==0.14 28 | entrypoints==0.2.3 29 | funcat==0.3.2 30 | future==0.17.1 31 | html5lib==0.9999999 32 | idna==2.6 33 | inflection==0.3.1 34 | ipykernel==4.6.1 35 | ipython==6.2.1 36 | ipython-genutils==0.2.0 37 | ipywidgets==7.4.2 38 | jaqs==0.6.12 39 | jedi==0.11.1 40 | Jinja2==2.9.6 41 | jsonpickle==0.9.4 42 | jsonschema==2.6.0 43 | jupyter==1.0.0 44 | jupyter-client==5.1.0 45 | jupyter-console==6.0.0 46 | jupyter-core==4.3.0 47 | jupyterlab==0.31.2 48 | jupyterlab-launcher==0.10.2 49 | kiwisolver==1.0.1 50 | line-profiler==2.1.2 51 | llvmlite==0.25.0 52 | Logbook==1.0.0 53 | lru-dict==1.1.6 54 | lxml==4.1.1 55 | MarkupSafe==1.0 56 | matplotlib==2.1.2 57 | mistune==0.7.4 58 | more-itertools==4.3.0 59 | motor==2.0.0 60 | msgpack==0.5.6 61 | msgpack-python==0.5.6 62 | nbconvert==5.2.1 63 | nbformat==4.4.0 64 | notebook==5.0.0 65 | numba==0.40.1 66 | numpy==1.14.0 67 | osxrelocator==1.0.1 68 | pandas==0.20.0 69 | pandocfilters==1.4.2 70 | parso==0.1.1 71 | pexpect==4.3.1 72 | pickleshare==0.7.4 73 | pika==0.12.0 74 | pluggy==0.6.0 75 | progressbar2==3.34.3 76 | prometheus-client==0.4.2 77 | prompt-toolkit==1.0.15 78 | psycopg2==2.7.6.1 79 | ptyprocess==0.5.2 80 | py==1.5.2 81 | pycparser==2.19 82 | Pygments==2.2.0 83 | pymongo==3.6.0 84 | PyMySQL==0.9.2 85 | pyparsing==2.2.0 86 | pytest==3.4.0 87 | python-dateutil==2.6.1 88 | python-snappy==0.5.3 89 | python-utils==2.2.0 90 | pytz==2017.3 91 | PyYAML==3.12 92 | pyzmq==16.0.2 93 | qtconsole==4.4.3 94 | Quandl==3.4.4 95 | QuantDigger==0.400 96 | redis==3.0.1 97 | requests==2.18.4 98 | rqalpha==3.0.9 99 | rqalpha-mod-fxdayu-source==0.1.0 100 | scipy==1.1.0 101 | seaborn==0.9.0 102 | Send2Trash==1.5.0 103 | simplegeneric==0.8.1 104 | simplejson==3.13.2 105 | six==1.11.0 106 | SQLAlchemy==1.2.14 107 | stock==2.0 108 | TA-Lib==0.4.16 109 | tabulate==0.8.2 110 | terminado==0.6 111 | testpath==0.3 112 | tornado==4.5.2 113 | traitlets==4.3.2 114 | tushare==1.1.3 115 | tzlocal==1.5.1 116 | urllib3==1.22 117 | wcwidth==0.1.7 118 | webencodings==0.5.1 119 | widgetsnbextension==3.4.2 120 | xlrd==1.1.0 121 | XlsxWriter==1.0.2 122 | -------------------------------------------------------------------------------- /pip install -r/kivy-m_pip_freeze.txt: -------------------------------------------------------------------------------- 1 | appdirs==1.4.3 2 | appnope==0.1.0 3 | backcall==0.1.0 4 | bleach==3.0.2 5 | buildozer==0.36 6 | colorama==0.4.0 7 | decorator==4.3.0 8 | defusedxml==0.5.0 9 | entrypoints==0.2.3 10 | ipykernel==5.1.0 11 | ipython==7.1.1 12 | ipython-genutils==0.2.0 13 | ipywidgets==7.4.2 14 | jedi==0.13.1 15 | Jinja2==2.10 16 | jsonschema==2.6.0 17 | jupyter==1.0.0 18 | jupyter-client==5.2.3 19 | jupyter-console==6.0.0 20 | jupyter-core==4.4.0 21 | MarkupSafe==1.1.0 22 | mistune==0.8.4 23 | nbconvert==5.4.0 24 | nbformat==4.4.0 25 | notebook==5.7.2 26 | pandocfilters==1.4.2 27 | parso==0.3.1 28 | pexpect==4.6.0 29 | pickleshare==0.7.5 30 | prometheus-client==0.4.2 31 | prompt-toolkit==2.0.7 32 | ptyprocess==0.6.0 33 | Pygments==2.2.0 34 | python-dateutil==2.7.5 35 | python-for-android==0.6.0 36 | pyzmq==17.1.2 37 | qtconsole==4.4.3 38 | Send2Trash==1.5.0 39 | sh==1.12.4 40 | six==1.11.0 41 | terminado==0.8.1 42 | testpath==0.4.2 43 | tornado==5.1.1 44 | traitlets==4.3.2 45 | virtualenv==16.1.0 46 | wcwidth==0.1.7 47 | webencodings==0.5.1 48 | widgetsnbextension==3.4.2 49 | -------------------------------------------------------------------------------- /pip install -r/pip_freeze.txt: -------------------------------------------------------------------------------- 1 | absl-py==0.6.1 2 | abupy==0.4.0 3 | aiohttp==3.4.4 4 | altgraph==0.16.1 5 | appdirs==1.4.3 6 | appnope==0.1.0 7 | APScheduler==3.5.3 8 | asn1crypto==0.24.0 9 | astor==0.7.1 10 | astroid==2.1.0 11 | async-timeout==3.0.1 12 | atomicwrites==1.2.1 13 | attrs==17.4.0 14 | Automat==0.7.0 15 | backcall==0.1.0 16 | backports.functools-lru-cache==1.5 17 | bcolz==1.1.2 18 | beautifulsoup4==4.6.0 19 | better-exceptions==0.2.1 20 | bidict==0.17.5 21 | black==18.9b0 22 | bleach==1.5.0 23 | bokeh==1.0.1 24 | bs4==0.0.1 25 | build==1.0.2 26 | buildozer==0.36 27 | cached-property==1.3.1 28 | certifi==2018.1.18 29 | cffi==1.11.5 30 | chardet==3.0.4 31 | Click==7.0 32 | colorama==0.3.9 33 | colorlog==3.1.4 34 | constantly==15.1.0 35 | coverage==4.5.2 36 | cryptography==2.4.1 37 | cssselect==1.0.3 38 | cycler==0.10.0 39 | Cython==0.28.2 40 | decorator==4.2.1 41 | defusedxml==0.5.0 42 | delegator.py==0.1.1 43 | demjson==2.2.4 44 | dill==0.2.5 45 | docutils==0.14 46 | dukpy==0.2.2 47 | entrypoints==0.2.3 48 | ExtensionClass==4.4 49 | Flask==1.0.2 50 | Flask-SocketIO==3.0.2 51 | funcat==0.3.2 52 | future==0.17.1 53 | gast==0.2.0 54 | greenlet==0.4.15 55 | grpcio==1.16.1 56 | h5py==2.8.0 57 | Hikyuu==1.0.9 58 | html5lib==0.9999999 59 | hyperlink==18.0.0 60 | idna==2.6 61 | idna-ssl==1.1.0 62 | incremental==17.5.0 63 | inflection==0.3.1 64 | ipykernel==4.6.1 65 | ipyparallel==6.2.3 66 | ipython==6.2.1 67 | ipython-genutils==0.2.0 68 | ipywidgets==7.4.2 69 | isort==4.3.4 70 | itsdangerous==1.1.0 71 | jaqs==0.6.12 72 | javascripthon==0.10 73 | jedi==0.11.1 74 | Jinja2==2.10 75 | jnius==1.1.0 76 | jqdatasdk==1.4.9 77 | jsonpickle==0.9.4 78 | jsonschema==2.6.0 79 | jupyter==1.0.0 80 | jupyter-client==5.1.0 81 | jupyter-console==6.0.0 82 | jupyter-core==4.3.0 83 | jupyter-echarts-pypkg==0.1.2 84 | jupyterlab==0.31.2 85 | jupyterlab-launcher==0.10.2 86 | jupyterlab-server==0.2.0 87 | Keras==2.2.4 88 | Keras-Applications==1.0.6 89 | Keras-Preprocessing==1.0.5 90 | Kivy==1.10.1 91 | Kivy-Garden==0.1.4 92 | kiwisolver==1.0.1 93 | lazy-object-proxy==1.3.1 94 | line-profiler==2.1.2 95 | llvmlite==0.25.0 96 | lml==0.0.2 97 | loc==0.0.2 98 | lock==2018.3.25.2110 99 | Logbook==1.0.0 100 | lru-dict==1.1.6 101 | lxml==4.1.1 102 | macholib==1.11 103 | macropy3==1.1.0b2 104 | Markdown==3.0.1 105 | MarkupSafe==1.0 106 | matplotlib==3.0.2 107 | mccabe==0.6.1 108 | mistune==0.7.4 109 | module==0.2.1 110 | more-itertools==4.3.0 111 | motor==2.0.0 112 | mpl-finance==0.10.0 113 | msgpack==0.5.6 114 | msgpack-python==0.4.7 115 | multidict==4.5.2 116 | mysql==0.0.2 117 | mysqlclient==1.3.13 118 | nbconvert==5.2.1 119 | nbformat==4.4.0 120 | notebook==5.0.0 121 | numba==0.40.1 122 | numpy==1.15.4 123 | osxrelocator==1.0.1 124 | packaging==18.0 125 | pandas==0.23.4 126 | pandocfilters==1.4.2 127 | parsel==1.5.1 128 | parso==0.1.1 129 | patsy==0.5.1 130 | pefile==2018.8.8 131 | pexpect==4.3.1 132 | pickleshare==0.7.4 133 | pika==0.12.0 134 | Pillow==5.3.0 135 | pluggy==0.6.0 136 | ply==3.11 137 | progressbar2==3.34.3 138 | prometheus-client==0.4.2 139 | prompt-toolkit==1.0.15 140 | protobuf==3.6.1 141 | psutil==5.4.8 142 | psycopg2==2.7.6.1 143 | ptyprocess==0.5.2 144 | py==1.5.2 145 | pyasn1==0.4.4 146 | pyasn1-modules==0.2.2 147 | pyconvert==0.6.3 148 | pycparser==2.19 149 | PyDispatcher==2.0.5 150 | pyecharts==0.5.11 151 | pyecharts-javascripthon==0.0.6 152 | pyecharts-jupyter-installer==0.0.3 153 | pyecharts-snapshot==0.1.9 154 | Pygments==2.2.0 155 | PyHamcrest==1.9.0 156 | PyInstaller==3.4 157 | pylint==2.2.1 158 | pymongo==3.7.2 159 | pymssql==2.1.4 160 | PyMySQL==0.9.2 161 | pyOpenSSL==18.0.0 162 | pyparsing==2.2.0 163 | PyQRCode==1.2.1 164 | PyQt5==5.11.3 165 | PyQt5-sip==4.19.13 166 | pytdx==1.67 167 | pytesseract==0.2.5 168 | pytest==3.4.0 169 | python-dateutil==2.6.1 170 | python-engineio==2.3.2 171 | python-for-android==0.6.0 172 | python-snappy==0.5.3 173 | python-socketio==2.0.0 174 | python-utils==2.2.0 175 | python-xlib==0.23 176 | pytz==2017.3 177 | pywinauto==0.6.5 178 | PyYAML==3.12 179 | pyzmq==16.0.2 180 | QDarkStyle==2.6.4 181 | qtconsole==4.4.3 182 | Quandl==3.4.4 183 | quantaxis==1.2.0 184 | queuelib==1.5.0 185 | redis==3.0.1 186 | requests==2.18.4 187 | retrying==1.3.3 188 | rqalpha==3.2.0 189 | save==0.1 190 | scikit-learn==0.20.0 191 | scipy==1.1.0 192 | Scrapy==1.5.1 193 | seaborn==0.9.0 194 | selenium==3.141.0 195 | Send2Trash==1.5.0 196 | service-identity==17.0.0 197 | sh==1.12.4 198 | simplegeneric==0.8.1 199 | simplejson==3.16.0 200 | six==1.11.0 201 | sql==0.4.0 202 | SQLAlchemy==1.2.14 203 | statsmodels==0.9.0 204 | stock==2.0 205 | stock-info==1.0.0 206 | TA-Lib==0.4.16 207 | tabulate==0.8.2 208 | tensorboard==1.12.0 209 | tensorboardX==1.4 210 | tensorflow==1.12.0 211 | termcolor==1.1.0 212 | terminado==0.6 213 | testpath==0.3 214 | thriftpy==0.3.9 215 | toml==0.10.0 216 | toolz==0.9.0 217 | tornado==4.5.2 218 | traitlets==4.3.2 219 | tushare==1.2.17 220 | Twisted==18.9.0 221 | typed-ast==1.1.0 222 | tzlocal==1.5.1 223 | urllib3==1.22 224 | virtualenv==16.1.0 225 | w3lib==1.19.0 226 | wcwidth==0.1.7 227 | webencodings==0.5.1 228 | Werkzeug==0.14.1 229 | widgetsnbextension==3.4.2 230 | wrapt==1.10.11 231 | xlrd==1.1.0 232 | XlsxWriter==1.0.2 233 | yarl==1.2.6 234 | zenlog==1.1 235 | zope.interface==4.6.0 236 | -------------------------------------------------------------------------------- /pip install -r/python-m_pip_freeze.txt: -------------------------------------------------------------------------------- 1 | absl-py==0.6.1 2 | abupy==0.4.0 3 | aiohttp==3.4.4 4 | altgraph==0.16.1 5 | appdirs==1.4.3 6 | appnope==0.1.0 7 | APScheduler==3.5.3 8 | asn1crypto==0.24.0 9 | astor==0.7.1 10 | astroid==2.1.0 11 | async-timeout==3.0.1 12 | atomicwrites==1.2.1 13 | attrs==17.4.0 14 | Automat==0.7.0 15 | backcall==0.1.0 16 | backports.functools-lru-cache==1.5 17 | bcolz==1.1.2 18 | beautifulsoup4==4.6.0 19 | better-exceptions==0.2.1 20 | bidict==0.17.5 21 | black==18.9b0 22 | bleach==1.5.0 23 | bokeh==1.0.1 24 | bs4==0.0.1 25 | build==1.0.2 26 | buildozer==0.36 27 | cached-property==1.3.1 28 | certifi==2018.1.18 29 | cffi==1.11.5 30 | chardet==3.0.4 31 | Click==7.0 32 | colorama==0.3.9 33 | colorlog==3.1.4 34 | constantly==15.1.0 35 | coverage==4.5.2 36 | cryptography==2.4.1 37 | cssselect==1.0.3 38 | cycler==0.10.0 39 | Cython==0.28.2 40 | decorator==4.2.1 41 | defusedxml==0.5.0 42 | delegator.py==0.1.1 43 | demjson==2.2.4 44 | dill==0.2.5 45 | docutils==0.14 46 | dukpy==0.2.2 47 | entrypoints==0.2.3 48 | ExtensionClass==4.4 49 | Flask==1.0.2 50 | Flask-SocketIO==3.0.2 51 | funcat==0.3.2 52 | future==0.17.1 53 | gast==0.2.0 54 | greenlet==0.4.15 55 | grpcio==1.16.1 56 | h5py==2.8.0 57 | Hikyuu==1.0.9 58 | html5lib==0.9999999 59 | hyperlink==18.0.0 60 | idna==2.6 61 | idna-ssl==1.1.0 62 | incremental==17.5.0 63 | inflection==0.3.1 64 | ipykernel==4.6.1 65 | ipyparallel==6.2.3 66 | ipython==6.2.1 67 | ipython-genutils==0.2.0 68 | ipywidgets==7.4.2 69 | isort==4.3.4 70 | itsdangerous==1.1.0 71 | jaqs==0.6.12 72 | javascripthon==0.10 73 | jedi==0.11.1 74 | Jinja2==2.10 75 | jnius==1.1.0 76 | jqdatasdk==1.4.9 77 | jsonpickle==0.9.4 78 | jsonschema==2.6.0 79 | jupyter==1.0.0 80 | jupyter-client==5.1.0 81 | jupyter-console==6.0.0 82 | jupyter-core==4.3.0 83 | jupyter-echarts-pypkg==0.1.2 84 | jupyterlab==0.31.2 85 | jupyterlab-launcher==0.10.2 86 | jupyterlab-server==0.2.0 87 | Keras==2.2.4 88 | Keras-Applications==1.0.6 89 | Keras-Preprocessing==1.0.5 90 | Kivy==1.10.1 91 | Kivy-Garden==0.1.4 92 | kiwisolver==1.0.1 93 | lazy-object-proxy==1.3.1 94 | line-profiler==2.1.2 95 | llvmlite==0.25.0 96 | lml==0.0.2 97 | loc==0.0.2 98 | lock==2018.3.25.2110 99 | Logbook==1.0.0 100 | lru-dict==1.1.6 101 | lxml==4.1.1 102 | macholib==1.11 103 | macropy3==1.1.0b2 104 | Markdown==3.0.1 105 | MarkupSafe==1.0 106 | matplotlib==3.0.2 107 | mccabe==0.6.1 108 | mistune==0.7.4 109 | module==0.2.1 110 | more-itertools==4.3.0 111 | motor==2.0.0 112 | mpl-finance==0.10.0 113 | msgpack==0.5.6 114 | msgpack-python==0.4.7 115 | multidict==4.5.2 116 | mysql==0.0.2 117 | mysqlclient==1.3.13 118 | nbconvert==5.2.1 119 | nbformat==4.4.0 120 | notebook==5.0.0 121 | numba==0.40.1 122 | numpy==1.15.4 123 | osxrelocator==1.0.1 124 | packaging==18.0 125 | pandas==0.23.4 126 | pandocfilters==1.4.2 127 | parsel==1.5.1 128 | parso==0.1.1 129 | patsy==0.5.1 130 | pefile==2018.8.8 131 | pexpect==4.3.1 132 | pickleshare==0.7.4 133 | pika==0.12.0 134 | Pillow==5.3.0 135 | pluggy==0.6.0 136 | ply==3.11 137 | progressbar2==3.34.3 138 | prometheus-client==0.4.2 139 | prompt-toolkit==1.0.15 140 | protobuf==3.6.1 141 | psutil==5.4.8 142 | psycopg2==2.7.6.1 143 | ptyprocess==0.5.2 144 | py==1.5.2 145 | pyasn1==0.4.4 146 | pyasn1-modules==0.2.2 147 | pyconvert==0.6.3 148 | pycparser==2.19 149 | PyDispatcher==2.0.5 150 | pyecharts==0.5.11 151 | pyecharts-javascripthon==0.0.6 152 | pyecharts-jupyter-installer==0.0.3 153 | pyecharts-snapshot==0.1.9 154 | Pygments==2.2.0 155 | PyHamcrest==1.9.0 156 | PyInstaller==3.4 157 | pylint==2.2.1 158 | pymongo==3.7.2 159 | pymssql==2.1.4 160 | PyMySQL==0.9.2 161 | pyOpenSSL==18.0.0 162 | pyparsing==2.2.0 163 | PyQRCode==1.2.1 164 | PyQt5==5.11.3 165 | PyQt5-sip==4.19.13 166 | pytdx==1.67 167 | pytesseract==0.2.5 168 | pytest==3.4.0 169 | python-dateutil==2.6.1 170 | python-engineio==2.3.2 171 | python-for-android==0.6.0 172 | python-snappy==0.5.3 173 | python-socketio==2.0.0 174 | python-utils==2.2.0 175 | python-xlib==0.23 176 | pytz==2017.3 177 | pywinauto==0.6.5 178 | PyYAML==3.12 179 | pyzmq==16.0.2 180 | QDarkStyle==2.6.4 181 | qtconsole==4.4.3 182 | Quandl==3.4.4 183 | quantaxis==1.2.0 184 | queuelib==1.5.0 185 | redis==3.0.1 186 | requests==2.18.4 187 | retrying==1.3.3 188 | rqalpha==3.2.0 189 | save==0.1 190 | scikit-learn==0.20.0 191 | scipy==1.1.0 192 | Scrapy==1.5.1 193 | seaborn==0.9.0 194 | selenium==3.141.0 195 | Send2Trash==1.5.0 196 | service-identity==17.0.0 197 | sh==1.12.4 198 | simplegeneric==0.8.1 199 | simplejson==3.16.0 200 | six==1.11.0 201 | sql==0.4.0 202 | SQLAlchemy==1.2.14 203 | statsmodels==0.9.0 204 | stock==2.0 205 | stock-info==1.0.0 206 | TA-Lib==0.4.16 207 | tabulate==0.8.2 208 | tensorboard==1.12.0 209 | tensorboardX==1.4 210 | tensorflow==1.12.0 211 | termcolor==1.1.0 212 | terminado==0.6 213 | testpath==0.3 214 | thriftpy==0.3.9 215 | toml==0.10.0 216 | toolz==0.9.0 217 | tornado==4.5.2 218 | traitlets==4.3.2 219 | tushare==1.2.17 220 | Twisted==18.9.0 221 | typed-ast==1.1.0 222 | tzlocal==1.5.1 223 | urllib3==1.22 224 | virtualenv==16.1.0 225 | w3lib==1.19.0 226 | wcwidth==0.1.7 227 | webencodings==0.5.1 228 | Werkzeug==0.14.1 229 | widgetsnbextension==3.4.2 230 | wrapt==1.10.11 231 | xlrd==1.1.0 232 | XlsxWriter==1.0.2 233 | yarl==1.2.6 234 | zenlog==1.1 235 | zope.interface==4.6.0 236 | -------------------------------------------------------------------------------- /pp-cpu.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "Usage: python auto_diff.py [ncpus]\n", 13 | " [ncpus] - the number of workers to run in parallel,\n", 14 | " if omitted it will be set to the number of processors in the system\n", 15 | "\n" 16 | ] 17 | }, 18 | { 19 | "ename": "ValueError", 20 | "evalue": "invalid literal for int() with base 10: '-f'", 21 | "output_type": "error", 22 | "traceback": [ 23 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 24 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", 25 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 101\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 102\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msys\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0margv\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 103\u001b[0;31m \u001b[0mncpus\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msys\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0margv\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 104\u001b[0m \u001b[0;31m# Creates jobserver with ncpus workers\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 105\u001b[0m \u001b[0mjob_server\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mServer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mncpus\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mppservers\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mppservers\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 26 | "\u001b[0;31mValueError\u001b[0m: invalid literal for int() with base 10: '-f'" 27 | ] 28 | } 29 | ], 30 | "source": [ 31 | "#!/usr/bin/env python\n", 32 | "# File: auto_diff.py\n", 33 | "# Author: Vitalii Vanovschi\n", 34 | "# Desc: This program demonstrates parallel computations with pp module\n", 35 | "# using class methods as parallel functions (available since pp 1.4).\n", 36 | "# Program calculates the partial sums of f(x) = x-x**2/2+x**3/3-x**4/4+...\n", 37 | "# and first derivatives f'(x) using automatic differentiation technique.\n", 38 | "# In the limit f(x) = ln(x+1) and f'(x) = 1/(x+1).\n", 39 | "# Parallel Python Software: http://www.parallelpython.com\n", 40 | "\n", 41 | "import math\n", 42 | "import sys\n", 43 | "import pp\n", 44 | "\n", 45 | "# Partial implemenmtation of automatic differentiation class\n", 46 | "\n", 47 | "\n", 48 | "class AD(object):\n", 49 | "\n", 50 | " def __init__(self, x, dx=0.0):\n", 51 | " self.x = float(x)\n", 52 | " self.dx = float(dx)\n", 53 | "\n", 54 | " def __pow__(self, val):\n", 55 | " if isinstance(val, int):\n", 56 | " p = self.x**val\n", 57 | " return AD(self.x**val, val*self.x**(val-1)*self.dx)\n", 58 | " else:\n", 59 | " raise TypeError(\"Second argumnet must be an integer\")\n", 60 | "\n", 61 | " def __add__(self, val):\n", 62 | " if isinstance(val, AD):\n", 63 | " return AD(self.x+val.x, self.dx+val.dx)\n", 64 | " else:\n", 65 | " return AD(self.x+val, self.dx)\n", 66 | "\n", 67 | " def __radd__(self, val):\n", 68 | " return self+val\n", 69 | "\n", 70 | " def __mul__(self, val):\n", 71 | " if isinstance(val, AD):\n", 72 | " return AD(self.x*val.x, self.x*val.dx+val.x*self.dx)\n", 73 | " else:\n", 74 | " return AD(self.x*val, val*self.dx)\n", 75 | "\n", 76 | " def __rmul__(self, val):\n", 77 | " return self*val\n", 78 | "\n", 79 | " def __div__(self, val):\n", 80 | " if isinstance(val, AD):\n", 81 | " return self*AD(1/val.x, -val.dx/val.x**2)\n", 82 | " else:\n", 83 | " return self*(1/float(val))\n", 84 | " __truediv__ = __div__ # PYTHON 3\n", 85 | "\n", 86 | " def __rdiv__(self, val):\n", 87 | " return AD(val)/self\n", 88 | " __rtruediv__ = __rdiv__ # PYTHON 3\n", 89 | "\n", 90 | " def __sub__(self, val):\n", 91 | " if isinstance(val, AD):\n", 92 | " return AD(self.x-val.x, self.dx-val.dx)\n", 93 | " else:\n", 94 | " return AD(self.x-val, self.dx)\n", 95 | "\n", 96 | " def __repr__(self):\n", 97 | " return str((self.x, self.dx))\n", 98 | "\n", 99 | "\n", 100 | "class PartialSum(object):\n", 101 | "\n", 102 | " def __init__(self, n):\n", 103 | " \"\"\"\n", 104 | " This class contains methods which will be executed in parallel\n", 105 | " \"\"\"\n", 106 | "\n", 107 | " self.n = n\n", 108 | "\n", 109 | " def t_log(self, x):\n", 110 | " \"\"\"\n", 111 | " truncated natural logarithm\n", 112 | " \"\"\"\n", 113 | " return self.partial_sum(x-1)\n", 114 | "\n", 115 | " def partial_sum(self, x):\n", 116 | " \"\"\"\n", 117 | " partial sum for truncated natural logarithm\n", 118 | " \"\"\"\n", 119 | " return sum([float(i%2 and 1 or -1)*x**i/i for i in range(1, self.n)])\n", 120 | "\n", 121 | "\n", 122 | "print(\"\"\"Usage: python auto_diff.py [ncpus]\n", 123 | " [ncpus] - the number of workers to run in parallel,\n", 124 | " if omitted it will be set to the number of processors in the system\n", 125 | "\"\"\")\n", 126 | "\n", 127 | "# tuple of all parallel python servers to connect with\n", 128 | "#ppservers = (\"*\",) # auto-discover\n", 129 | "#ppservers = (\"10.0.0.1\",\"10.0.0.2\") # list of static IPs\n", 130 | "ppservers = ()\n", 131 | "\n", 132 | "if len(sys.argv) > 1:\n", 133 | " ncpus = int(sys.argv[1])\n", 134 | " # Creates jobserver with ncpus workers\n", 135 | " job_server = pp.Server(ncpus, ppservers=ppservers)\n", 136 | "else:\n", 137 | " # Creates jobserver with automatically detected number of workers\n", 138 | " job_server = pp.Server(ppservers=ppservers)\n", 139 | "\n", 140 | "print(\"Starting pp with %s workers\" % job_server.get_ncpus())\n", 141 | "\n", 142 | "proc = PartialSum(20000)\n", 143 | "\n", 144 | "results = []\n", 145 | "for i in range(32):\n", 146 | " # Creates an object with x = float(i)/32+1 and dx = 1.0\n", 147 | " ad_x = AD(float(i)/32+1, 1.0)\n", 148 | " # Submits a job of calulating proc.t_log(x).\n", 149 | " f = job_server.submit(proc.t_log, (ad_x, ))\n", 150 | " results.append((ad_x.x, f))\n", 151 | "\n", 152 | "for x, f in results:\n", 153 | " # Retrieves the result of the calculation\n", 154 | " val = f()\n", 155 | " print(\"t_log(%lf) = %lf, t_log'(%lf) = %lf\" % (x, val.x, x, val.dx))\n", 156 | "\n", 157 | "# Print execution statistics\n", 158 | "job_server.print_stats()\n", 159 | "\n", 160 | "# Parallel Python Software: http://www.parallelpython.com\n", 161 | "\n" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "metadata": {}, 168 | "outputs": [], 169 | "source": [] 170 | } 171 | ], 172 | "metadata": { 173 | "kernelspec": { 174 | "display_name": "Python 3", 175 | "language": "python", 176 | "name": "python3" 177 | }, 178 | "language_info": { 179 | "codemirror_mode": { 180 | "name": "ipython", 181 | "version": 3 182 | }, 183 | "file_extension": ".py", 184 | "mimetype": "text/x-python", 185 | "name": "python", 186 | "nbconvert_exporter": "python", 187 | "pygments_lexer": "ipython3", 188 | "version": "3.6.5" 189 | } 190 | }, 191 | "nbformat": 4, 192 | "nbformat_minor": 2 193 | } 194 | -------------------------------------------------------------------------------- /python头条教程/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/python头条教程/.DS_Store -------------------------------------------------------------------------------- /python头条教程/15分钟,教你用Python爬网站数据,并用BI可视化分析!.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/python头条教程/15分钟,教你用Python爬网站数据,并用BI可视化分析!.pdf -------------------------------------------------------------------------------- /python头条教程/《学Python量化,通往财务自由》|选股实战之CAPM模型.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/python头条教程/《学Python量化,通往财务自由》|选股实战之CAPM模型.pdf -------------------------------------------------------------------------------- /python头条教程/使用LSTM预测股票价格:机器学习案例研究.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/python头条教程/使用LSTM预测股票价格:机器学习案例研究.pdf -------------------------------------------------------------------------------- /quantaxis_backend.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 8, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "ename": "IndentationError", 10 | "evalue": "unexpected indent (, line 48)", 11 | "output_type": "error", 12 | "traceback": [ 13 | "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m48\u001b[0m\n\u001b[0;31m @cached_property\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m unexpected indent\n" 14 | ] 15 | } 16 | ], 17 | "source": [ 18 | "# -*- coding: utf-8 -*-\n", 19 | "#\n", 20 | "\n", 21 | "from cached_property import cached_property\n", 22 | "\n", 23 | "#from .backend import DataBackend\n", 24 | "#from ..utils import lru_cache, get_str_date_from_int, get_int_date\n", 25 | "from backend import DataBackend\n", 26 | "from utils import lru_cache, get_str_date_from_int, get_int_date\n", 27 | "\n", 28 | "\n", 29 | "class TushareDataBackend(DataBackend):\n", 30 | "\n", 31 | " #@cached_property\n", 32 | " def ts(self):\n", 33 | " try:\n", 34 | " import tushare as ts\n", 35 | " return ts\n", 36 | " except ImportError:\n", 37 | " print(\"-\" * 50)\n", 38 | " print(\">>> Missing tushare. Please run `pip install tushare`\")\n", 39 | " print(\"-\" * 50)\n", 40 | " raise\n", 41 | "\n", 42 | "class QUANTAXISDataBackend(DataBackend):\n", 43 | "\n", 44 | " #@cached_property\n", 45 | " def QA(self):\n", 46 | " try:\n", 47 | " import QUANTAXIS as QA\n", 48 | " return QA\n", 49 | " except ImportError:\n", 50 | " print(\"-\" * 50)\n", 51 | " print(\">>> Missing QUANTAXIS. Please run `pip install QUANTAXIS`\")\n", 52 | " print(\"-\" * 50)\n", 53 | " raise\n", 54 | "''' \n", 55 | "| 类别 | 实时 | 从数据库中 | QADataStruct格式|\n", 56 | "| --------| ------------------- | --------------- | --------------- |\n", 57 | "| 股票日线 | QA_fetch_get_stock_day | QA_fetch_stock_day | QA_fetch_stock_day_adv |\n", 58 | "| 股票分钟线 | QA_fetch_get_stock_min | QA_fetch_stock_min | QA_fetch_stock_min_adv |\n", 59 | "| 股票列表 | QA_fetch_get_stock_list | QA_fetch_stock_list | QA_fetch_stock_list_adv |\n", 60 | "| 股票版块 | QA_fetch_get_stock_block | QA_fetch_stock_block | QA_fetch_stock_block_adv |\n", 61 | "| 股票分笔 | QA_fetch_get_stock_transaction | X| X|\n", 62 | "| 股票实时分笔 | QA_fetch_get_stock_transaction_realtime | X| X|\n", 63 | "| 股票权息 | QA_fetch_get_stock_xdxr | QA_fetch_stock_xdxr | X|\n", 64 | "| 股票信息 | QA_fetch_get_stock_info | QA_fetch_stock_info| X|\n", 65 | "| 股票实时5挡价格 | QA_fetch_get_stock_realtime | X| X|\n", 66 | "| 指数日线 | QA_fetch_get_index_day | QA_fetch_index_day | QA_fetch_index_day_adv |\n", 67 | "| 指数分钟线 | QA_fetch_get_index_min | QA_fetch_index_min | QA_fetch_index_day_min |\n", 68 | "| ETF日线 | QA_fetch_get_etf_day | QA_fetch_etf_day | QA_fetch_etf_day_adv |\n", 69 | "| ETF分钟线 | QA_fetch_get_etf_min | QA_fetch_etf_min | QA_fetch_etf_min_adv |\n", 70 | "| 期货日线 | QA_fetch_get_future_day | X| X|\n", 71 | "| 期货分钟线 | QA_fetch_get_future_min | X| X|\n", 72 | "| 期货历史分笔 | QA_fetch_get_future_transaction | X| X|\n", 73 | "| 期货实时分笔 | QA_fetch_get_future_transaction_realtime | X| X|\n", 74 | "| 期货列表 | QA_fetch_get_future_list | X| X|\n", 75 | "'''\n", 76 | "\n", 77 | " #@cached_property\n", 78 | " def stock_basics(self):\n", 79 | " return self.QA.QA_fetch_stock_day_adv()\n", 80 | "\n", 81 | " #@cached_property\n", 82 | " def code_name_map(self):\n", 83 | " code_name_map = self.stock_basics[[\"name\"]].to_dict()[\"name\"]\n", 84 | " return code_name_map\n", 85 | "\n", 86 | " def convert_code(self, order_book_id):\n", 87 | " return order_book_id.split(\".\")[0]\n", 88 | "\n", 89 | " #@lru_cache(maxsize=4096)\n", 90 | " def get_price(self, order_book_id, start, end, freq):\n", 91 | " \"\"\"\n", 92 | " :param order_book_id: e.g. 000002.XSHE\n", 93 | " :param start: 20160101\n", 94 | " :param end: 20160201\n", 95 | " :returns:\n", 96 | " :rtype: numpy.rec.array\n", 97 | " \"\"\"\n", 98 | " start = get_str_date_from_int(start)\n", 99 | " end = get_str_date_from_int(end)\n", 100 | " code = self.convert_code(order_book_id)\n", 101 | " is_index = False\n", 102 | " if ((order_book_id.startswith(\"0\") and order_book_id.endswith(\".XSHG\")) or\n", 103 | " (order_book_id.startswith(\"3\") and order_book_id.endswith(\".XSHE\"))\n", 104 | " ):\n", 105 | " is_index = True\n", 106 | " ktype = freq\n", 107 | " if freq[-1] == \"m\":\n", 108 | " ktype = freq[:-1]\n", 109 | " elif freq == \"1d\":\n", 110 | " ktype = \"D\"\n", 111 | " # else W M\n", 112 | "\n", 113 | " df = self.ts.get_k_data(code, start=start, end=end, index=is_index, ktype=ktype)\n", 114 | "\n", 115 | " if freq[-1] == \"m\":\n", 116 | " df[\"datetime\"] = df.apply(\n", 117 | " lambda row: int(row[\"date\"].split(\" \")[0].replace(\"-\", \"\")) * 1000000 + int(row[\"date\"].split(\" \")[1].replace(\":\", \"\")) * 100, axis=1)\n", 118 | " elif freq in (\"1d\", \"W\", \"M\"):\n", 119 | " df[\"datetime\"] = df[\"date\"].apply(lambda x: int(x.replace(\"-\", \"\")) * 1000000)\n", 120 | "\n", 121 | " del df[\"code\"]\n", 122 | " arr = df.to_records()\n", 123 | "\n", 124 | " return arr\n", 125 | "\n", 126 | " #@lru_cache()\n", 127 | " def get_order_book_id_list(self):\n", 128 | " \"\"\"获取所有的股票代码列表\n", 129 | " \"\"\"\n", 130 | " info = self.ts.get_stock_basics()\n", 131 | " code_list = info.index.sort_values().tolist()\n", 132 | " order_book_id_list = [\n", 133 | " (code + \".XSHG\" if code.startswith(\"6\") else code + \".XSHE\")\n", 134 | " for code in code_list\n", 135 | " ]\n", 136 | " return order_book_id_list\n", 137 | "\n", 138 | " @lru_cache()\n", 139 | " def get_trading_dates(self, start, end):\n", 140 | " \"\"\"获取所有的交易日\n", 141 | "\n", 142 | " :param start: 20160101\n", 143 | " :param end: 20160201\n", 144 | " \"\"\"\n", 145 | " start = get_str_date_from_int(start)\n", 146 | " end = get_str_date_from_int(end)\n", 147 | " df = self.ts.get_k_data(\"000001\", index=True, start=start, end=end)\n", 148 | " trading_dates = [get_int_date(date) for date in df.date.tolist()]\n", 149 | " return trading_dates\n", 150 | "\n", 151 | " @lru_cache(maxsize=4096)\n", 152 | " def symbol(self, order_book_id):\n", 153 | " \"\"\"获取order_book_id对应的名字\n", 154 | " :param order_book_id str: 股票代码\n", 155 | " :returns: 名字\n", 156 | " :rtype: str\n", 157 | " \"\"\"\n", 158 | " code = self.convert_code(order_book_id)\n", 159 | " return \"{}[{}]\".format(order_book_id, self.code_name_map.get(code))\n", 160 | "\n", 161 | "\n" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "metadata": { 168 | "collapsed": true 169 | }, 170 | "outputs": [], 171 | "source": [] 172 | } 173 | ], 174 | "metadata": { 175 | "kernelspec": { 176 | "display_name": "Python 3", 177 | "language": "python", 178 | "name": "python3" 179 | }, 180 | "language_info": { 181 | "codemirror_mode": { 182 | "name": "ipython", 183 | "version": 3 184 | }, 185 | "file_extension": ".py", 186 | "mimetype": "text/x-python", 187 | "name": "python", 188 | "nbconvert_exporter": "python", 189 | "pygments_lexer": "ipython3", 190 | "version": "3.6.5" 191 | } 192 | }, 193 | "nbformat": 4, 194 | "nbformat_minor": 2 195 | } 196 | -------------------------------------------------------------------------------- /quantaxis量化/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/quantaxis量化/.DS_Store -------------------------------------------------------------------------------- /quantaxis量化/quantaxis_backend.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 8, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "ename": "IndentationError", 10 | "evalue": "unexpected indent (, line 48)", 11 | "output_type": "error", 12 | "traceback": [ 13 | "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m48\u001b[0m\n\u001b[0;31m @cached_property\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m unexpected indent\n" 14 | ] 15 | } 16 | ], 17 | "source": [ 18 | "# -*- coding: utf-8 -*-\n", 19 | "#\n", 20 | "\n", 21 | "from cached_property import cached_property\n", 22 | "\n", 23 | "#from .backend import DataBackend\n", 24 | "#from ..utils import lru_cache, get_str_date_from_int, get_int_date\n", 25 | "from backend import DataBackend\n", 26 | "from utils import lru_cache, get_str_date_from_int, get_int_date\n", 27 | "\n", 28 | "\n", 29 | "class TushareDataBackend(DataBackend):\n", 30 | "\n", 31 | " #@cached_property\n", 32 | " def ts(self):\n", 33 | " try:\n", 34 | " import tushare as ts\n", 35 | " return ts\n", 36 | " except ImportError:\n", 37 | " print(\"-\" * 50)\n", 38 | " print(\">>> Missing tushare. Please run `pip install tushare`\")\n", 39 | " print(\"-\" * 50)\n", 40 | " raise\n", 41 | "\n", 42 | "class QUANTAXISDataBackend(DataBackend):\n", 43 | "\n", 44 | " #@cached_property\n", 45 | " def QA(self):\n", 46 | " try:\n", 47 | " import QUANTAXIS as QA\n", 48 | " return QA\n", 49 | " except ImportError:\n", 50 | " print(\"-\" * 50)\n", 51 | " print(\">>> Missing QUANTAXIS. Please run `pip install QUANTAXIS`\")\n", 52 | " print(\"-\" * 50)\n", 53 | " raise\n", 54 | "''' \n", 55 | "| 类别 | 实时 | 从数据库中 | QADataStruct格式|\n", 56 | "| --------| ------------------- | --------------- | --------------- |\n", 57 | "| 股票日线 | QA_fetch_get_stock_day | QA_fetch_stock_day | QA_fetch_stock_day_adv |\n", 58 | "| 股票分钟线 | QA_fetch_get_stock_min | QA_fetch_stock_min | QA_fetch_stock_min_adv |\n", 59 | "| 股票列表 | QA_fetch_get_stock_list | QA_fetch_stock_list | QA_fetch_stock_list_adv |\n", 60 | "| 股票版块 | QA_fetch_get_stock_block | QA_fetch_stock_block | QA_fetch_stock_block_adv |\n", 61 | "| 股票分笔 | QA_fetch_get_stock_transaction | X| X|\n", 62 | "| 股票实时分笔 | QA_fetch_get_stock_transaction_realtime | X| X|\n", 63 | "| 股票权息 | QA_fetch_get_stock_xdxr | QA_fetch_stock_xdxr | X|\n", 64 | "| 股票信息 | QA_fetch_get_stock_info | QA_fetch_stock_info| X|\n", 65 | "| 股票实时5挡价格 | QA_fetch_get_stock_realtime | X| X|\n", 66 | "| 指数日线 | QA_fetch_get_index_day | QA_fetch_index_day | QA_fetch_index_day_adv |\n", 67 | "| 指数分钟线 | QA_fetch_get_index_min | QA_fetch_index_min | QA_fetch_index_day_min |\n", 68 | "| ETF日线 | QA_fetch_get_etf_day | QA_fetch_etf_day | QA_fetch_etf_day_adv |\n", 69 | "| ETF分钟线 | QA_fetch_get_etf_min | QA_fetch_etf_min | QA_fetch_etf_min_adv |\n", 70 | "| 期货日线 | QA_fetch_get_future_day | X| X|\n", 71 | "| 期货分钟线 | QA_fetch_get_future_min | X| X|\n", 72 | "| 期货历史分笔 | QA_fetch_get_future_transaction | X| X|\n", 73 | "| 期货实时分笔 | QA_fetch_get_future_transaction_realtime | X| X|\n", 74 | "| 期货列表 | QA_fetch_get_future_list | X| X|\n", 75 | "'''\n", 76 | "\n", 77 | " #@cached_property\n", 78 | " def stock_basics(self):\n", 79 | " return self.QA.QA_fetch_stock_day_adv()\n", 80 | "\n", 81 | " #@cached_property\n", 82 | " def code_name_map(self):\n", 83 | " code_name_map = self.stock_basics[[\"name\"]].to_dict()[\"name\"]\n", 84 | " return code_name_map\n", 85 | "\n", 86 | " def convert_code(self, order_book_id):\n", 87 | " return order_book_id.split(\".\")[0]\n", 88 | "\n", 89 | " #@lru_cache(maxsize=4096)\n", 90 | " def get_price(self, order_book_id, start, end, freq):\n", 91 | " \"\"\"\n", 92 | " :param order_book_id: e.g. 000002.XSHE\n", 93 | " :param start: 20160101\n", 94 | " :param end: 20160201\n", 95 | " :returns:\n", 96 | " :rtype: numpy.rec.array\n", 97 | " \"\"\"\n", 98 | " start = get_str_date_from_int(start)\n", 99 | " end = get_str_date_from_int(end)\n", 100 | " code = self.convert_code(order_book_id)\n", 101 | " is_index = False\n", 102 | " if ((order_book_id.startswith(\"0\") and order_book_id.endswith(\".XSHG\")) or\n", 103 | " (order_book_id.startswith(\"3\") and order_book_id.endswith(\".XSHE\"))\n", 104 | " ):\n", 105 | " is_index = True\n", 106 | " ktype = freq\n", 107 | " if freq[-1] == \"m\":\n", 108 | " ktype = freq[:-1]\n", 109 | " elif freq == \"1d\":\n", 110 | " ktype = \"D\"\n", 111 | " # else W M\n", 112 | "\n", 113 | " df = self.ts.get_k_data(code, start=start, end=end, index=is_index, ktype=ktype)\n", 114 | "\n", 115 | " if freq[-1] == \"m\":\n", 116 | " df[\"datetime\"] = df.apply(\n", 117 | " lambda row: int(row[\"date\"].split(\" \")[0].replace(\"-\", \"\")) * 1000000 + int(row[\"date\"].split(\" \")[1].replace(\":\", \"\")) * 100, axis=1)\n", 118 | " elif freq in (\"1d\", \"W\", \"M\"):\n", 119 | " df[\"datetime\"] = df[\"date\"].apply(lambda x: int(x.replace(\"-\", \"\")) * 1000000)\n", 120 | "\n", 121 | " del df[\"code\"]\n", 122 | " arr = df.to_records()\n", 123 | "\n", 124 | " return arr\n", 125 | "\n", 126 | " #@lru_cache()\n", 127 | " def get_order_book_id_list(self):\n", 128 | " \"\"\"获取所有的股票代码列表\n", 129 | " \"\"\"\n", 130 | " info = self.ts.get_stock_basics()\n", 131 | " code_list = info.index.sort_values().tolist()\n", 132 | " order_book_id_list = [\n", 133 | " (code + \".XSHG\" if code.startswith(\"6\") else code + \".XSHE\")\n", 134 | " for code in code_list\n", 135 | " ]\n", 136 | " return order_book_id_list\n", 137 | "\n", 138 | " @lru_cache()\n", 139 | " def get_trading_dates(self, start, end):\n", 140 | " \"\"\"获取所有的交易日\n", 141 | "\n", 142 | " :param start: 20160101\n", 143 | " :param end: 20160201\n", 144 | " \"\"\"\n", 145 | " start = get_str_date_from_int(start)\n", 146 | " end = get_str_date_from_int(end)\n", 147 | " df = self.ts.get_k_data(\"000001\", index=True, start=start, end=end)\n", 148 | " trading_dates = [get_int_date(date) for date in df.date.tolist()]\n", 149 | " return trading_dates\n", 150 | "\n", 151 | " @lru_cache(maxsize=4096)\n", 152 | " def symbol(self, order_book_id):\n", 153 | " \"\"\"获取order_book_id对应的名字\n", 154 | " :param order_book_id str: 股票代码\n", 155 | " :returns: 名字\n", 156 | " :rtype: str\n", 157 | " \"\"\"\n", 158 | " code = self.convert_code(order_book_id)\n", 159 | " return \"{}[{}]\".format(order_book_id, self.code_name_map.get(code))\n", 160 | "\n", 161 | "\n" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "metadata": { 168 | "collapsed": true 169 | }, 170 | "outputs": [], 171 | "source": [] 172 | } 173 | ], 174 | "metadata": { 175 | "kernelspec": { 176 | "display_name": "Python 3", 177 | "language": "python", 178 | "name": "python3" 179 | }, 180 | "language_info": { 181 | "codemirror_mode": { 182 | "name": "ipython", 183 | "version": 3 184 | }, 185 | "file_extension": ".py", 186 | "mimetype": "text/x-python", 187 | "name": "python", 188 | "nbconvert_exporter": "python", 189 | "pygments_lexer": "ipython3", 190 | "version": "3.6.5" 191 | } 192 | }, 193 | "nbformat": 4, 194 | "nbformat_minor": 2 195 | } 196 | -------------------------------------------------------------------------------- /rqalpha量化/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/rqalpha量化/.DS_Store -------------------------------------------------------------------------------- /rqalpha量化/回测 /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/rqalpha量化/回测 /.DS_Store -------------------------------------------------------------------------------- /rqalpha量化/回测 /Untitled.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "%load_ext Cython" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": { 16 | "collapsed": true 17 | }, 18 | "outputs": [], 19 | "source": [ 20 | "%reload_ext Cython" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": { 27 | "collapsed": true 28 | }, 29 | "outputs": [], 30 | "source": [ 31 | "%%cython\n", 32 | "cdef int add(int x, int y):\n", 33 | " return x + y" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "%%cython -h" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": null, 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "%%cython\n", 52 | "def sum(int a, int b):\n", 53 | " cdef int s = a+b\n", 54 | " return s\n", 55 | "sum(1,3)\n", 56 | "\n", 57 | "def AVEDEV(value,N):\n", 58 | " mean = value/N\n", 59 | " for i in range(1,N):\n", 60 | " mean += REF(value,i)/N\n", 61 | " sum_ = ABS(value-mean)\n", 62 | " for i in range(1,N):\n", 63 | " sum_ += ABS(REF(value,i)-mean)\n", 64 | " return sum_/N" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "%%cython\n", 74 | "def sum(int a, int b):\n", 75 | " cdef int s = a+b\n", 76 | " return s\n", 77 | "sum(1,3)\n", 78 | "\n", 79 | "def sum1( a, b):\n", 80 | " s = a+b\n", 81 | " return s\n", 82 | "\n", 83 | "%timeit sum\n", 84 | "%timeit sum1" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [ 93 | "%%cython\n", 94 | "def ABS(int a, int b):\n", 95 | " cdef int s = a+b\n", 96 | " return s\n", 97 | "ABS(1,3)\n", 98 | "\n", 99 | "def ABS1( a, b):\n", 100 | " s = a+b\n", 101 | " return s\n", 102 | "\n", 103 | "%timeit ABS\n", 104 | "%timeit ABS1" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": 1, 110 | "metadata": { 111 | "collapsed": true 112 | }, 113 | "outputs": [], 114 | "source": [ 115 | "%load_ext Cython" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": null, 121 | "metadata": { 122 | "collapsed": true 123 | }, 124 | "outputs": [], 125 | "source": [] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": null, 130 | "metadata": {}, 131 | "outputs": [ 132 | { 133 | "name": "stdout", 134 | "output_type": "stream", 135 | "text": [ 136 | "《设定测试》读取当日时间格式:n1 2018-02-14\n", 137 | "《设定测试》读取当日时间格式:n2 20180214\n", 138 | "《设定测试》读取前二日时间格式:n3 2018-02-04\n", 139 | "《设定测试》读取当日时间格式:n4 2018214\n", 140 | "《设定测试》读取当日时间格式:n5 2018-02-14T10:50:47.176561\n", 141 | "《设定测试》手动设定选股开始时间格式:n8 20180201\n", 142 | "《设定测试》手动设定选股结束时间格式:n9 20180209\n", 143 | "《设定测试》自动设定数据起始设定前推200天:n10 2017-07-29\n", 144 | "《设定测试》设定股票代码 000001.XSHG\n", 145 | "《数据测试》打印 开盘 最高 最低 收盘 成交量 3172.85 3180.11 3062.74 3129.85 25638917600.0\n", 146 | "《数据测试》当天涨幅 -0.04052666268144278\n", 147 | "《数据测试》打印60日均线 3372.0388333333312\n", 148 | "《数据测试》判断收盘价是否大于60日均线 False\n", 149 | "《数据测试》30日最高价 3587.03\n", 150 | "《数据测试》最近30日,收盘价 Close 大于60日均线的天数 24\n", 151 | "《数据测试》10日均线上穿 False\n", 152 | "《数据测试》最近10天收阳线的天数 3\n", 153 | "《数据测试》最近60天K线实体的最高价 3563.64\n", 154 | "《数据测试》5日均线上穿10日均线 False\n", 155 | "《RQALPHA本地化开始CCI选股》读取开始时间:==》n5 2018-02-14T10:50:47.176561\n", 156 | "\n", 157 | "[20180214]\n", 158 | "[20180213]\n", 159 | "20180213 000301.XSHE 东方市场\n", 160 | "20180213 000528.XSHE 柳工\n", 161 | "20180213 002153.XSHE 石基信息\n", 162 | "20180213 002336.XSHE 人人乐\n", 163 | "20180213 002376.XSHE 新北洋\n", 164 | "20180213 002460.XSHE 赣锋锂业\n", 165 | "20180213 002588.XSHE 史丹利\n", 166 | "20180213 002644.XSHE 佛慈制药\n", 167 | "20180213 002727.XSHE 一心堂\n" 168 | ] 169 | } 170 | ], 171 | "source": [ 172 | "%%cython\n", 173 | "cdef int add(int x, int y):\n", 174 | " return x + y\n", 175 | "\n", 176 | "#CCI选股!\n", 177 | "#from matplotlib import rcParams\n", 178 | "#import matplotlib.pyplot as plt\n", 179 | "#import numpy as np\n", 180 | "#np.seterr(all='ignore')\n", 181 | "#rcParams['figure.figsize'] = (14, 6)\n", 182 | "from cython import * #cython 计算加速模块\n", 183 | "from funcat import * #FUNCAT的同花顺/通达信指标模块:和:&,或:|,其他基本相同。可以使用指标选股!!!\n", 184 | "from tushare import * #TUSHARE数据连接更新。\n", 185 | "from rqalpha import * #RQALPHA本地数据连接,通过 rqalpha update_bundle 8点后更新全部数据库\n", 186 | "\n", 187 | "#from pytdx import * #通达信数据更新模块到QUANTAXIS的mongoDB\n", 188 | "#from jaqs import * #QunatOS的jaqs客户端在线。\n", 189 | "#from abupy import * #ABUPY本地化,数据在线下载更新,数据在线下载在根目录abu下\n", 190 | "#from quantaxis import * #加载QUANTAXIS数据库模块,首先需要开启mongoDB+web服务器,数据更新通过通达信服务器。\n", 191 | "#from hikyuu import * #HIKYUU本地化,数据库在根目录的stock。通过通达信导入。\n", 192 | "\n", 193 | "import time\n", 194 | "import datetime #读取/设定数据库时间区域,当前股票,选股时间段。 \n", 195 | "\n", 196 | "n1 = (time.strftime(\"20%y-%m-%d\"))## 20yy-mm-dd格式,输出当日日期\n", 197 | "print (\"《设定测试》读取当日时间格式:n1\",n1) #当日时间格式:yyyy-mm-dd\n", 198 | "n2 = (time.strftime(\"20%y%m%d\"))## 20yymmdd格式,输出当日日期\n", 199 | "print (\"《设定测试》读取当日时间格式:n2\",n2) #当日时间格式:yyyymmdd\n", 200 | "def getYesterday(): \n", 201 | " today=datetime.date.today() \n", 202 | " oneday=datetime.timedelta(days=10) \n", 203 | " yesterday=today-oneday \n", 204 | " return yesterday\n", 205 | "n3 = (getYesterday())# 输出前二天日期\n", 206 | "print (\"《设定测试》读取前二日时间格式:n3\",n3) #前日时间格式:yyyy-mm-dd\n", 207 | "i = datetime.datetime.now()#当前日期\n", 208 | "\n", 209 | "n4 = (\"%s%s%s\" % (i.year, i.month, i.day) )\n", 210 | "print (\"《设定测试》读取当日时间格式:n4\",n4) #当日时间格式:yyyymmdd\n", 211 | "\n", 212 | "n5 = (\"%s\" % i.isoformat() )\n", 213 | "print (\"《设定测试》读取当日时间格式:n5\",n5) #当日时间格式:yyyy-mm-dd:...\n", 214 | "\n", 215 | "n8=\"20180201\"#开始时间\n", 216 | "print (\"《设定测试》手动设定选股开始时间格式:n8\",n8)\n", 217 | "\n", 218 | "n9=\"20180209\"#结束时间\n", 219 | "print (\"《设定测试》手动设定选股结束时间格式:n9\",n9)\n", 220 | "\n", 221 | "def getYesterday(): \n", 222 | " today=datetime.date.today() \n", 223 | " oneday=datetime.timedelta(days=200) \n", 224 | " yesterday=today-oneday \n", 225 | " return yesterday\n", 226 | "n10 = (getYesterday())# 输出前200天日期\n", 227 | "#n10=\"20170101\"#设定起始时间\n", 228 | "print (\"《设定测试》自动设定数据起始设定前推200天:n10\",n10)\n", 229 | "\n", 230 | "x1=\"000001.XSHG\" #用rqalpha本地数据需要代码后缀!!!!XSHE=深圳,XSHG=上海\n", 231 | "print (\"《设定测试》设定股票代码\",x1)\n", 232 | "\n", 233 | "from funcat.data.tushare_backend import TushareDataBackend\n", 234 | "from funcat.data.rqalpha_data_backend import RQAlphaDataBackend\n", 235 | "backend = \"rqalpha\" #设定数据库连接:rqalpha tushare\n", 236 | "if backend == \"rqalpha\":\n", 237 | " set_data_backend(RQAlphaDataBackend(\"~/.rqalpha/bundle\"))\n", 238 | "elif backend == \"tushare\":\n", 239 | " set_data_backend(TushareDataBackend())\n", 240 | "set_start_date(n10)\n", 241 | "\n", 242 | "S(x1) # 设置当前关注股票\n", 243 | "T(n9) # 设置当前观察日期\n", 244 | "\n", 245 | "print (\"《数据测试》打印 开盘 最高 最低 收盘 成交量\",O, H, L, C, V) # 打印 Open High Low Close\n", 246 | "print (\"《数据测试》当天涨幅\",C / C[1] - 1) # 当天涨幅\n", 247 | "print (\"《数据测试》打印60日均线\",MA(C, 60)) # 打印60日均线\n", 248 | "print (\"《数据测试》判断收盘价是否大于60日均线\",C > MA(C, 60)) # 判断收盘价是否大于60日均线\n", 249 | "print (\"《数据测试》30日最高价\",HHV(H, 30)) # 30日最高价\n", 250 | "print (\"《数据测试》最近30日,收盘价 Close 大于60日均线的天数\",COUNT(C > MA(C, 60), 30)) # 最近30日,收盘价 Close 大于60日均线的天数\n", 251 | "print (\"《数据测试》10日均线上穿\",CROSS(MA(C, 10), MA(C, 20))) # 10日均线上穿\n", 252 | "print (\"《数据测试》最近10天收阳线的天数\",COUNT(C > O, 10)) # 最近10天收阳线的天数\n", 253 | "print (\"《数据测试》最近60天K线实体的最高价\",HHV(MAX(O, C), 60)) # 最近60天K线实体的最高价\n", 254 | "print (\"《数据测试》5日均线上穿10日均线\",CROSS(MA(C, 5), MA(C, 10))) # 5日均线上穿10日均线\n", 255 | "\n", 256 | "#CCI指标 方差函数模块\n", 257 | "\n", 258 | "\n", 259 | "'''\n", 260 | "def AVEDEV(value,N):\n", 261 | " mean = value/N\n", 262 | " for i in range(1,N):\n", 263 | " mean += REF(value,i)/N\n", 264 | " sum_ = ABS(value-mean)\n", 265 | " for i in range(1,N):\n", 266 | " sum_ += ABS(REF(value,i)-mean)\n", 267 | " return sum_/N\n", 268 | "\n", 269 | "def AVEDEV(value,N):\n", 270 | " mean = value/N\n", 271 | " for i in range(1,N):\n", 272 | " mean += REF(value,i)/N\n", 273 | " sum_ = ABS(value-mean)\n", 274 | " for i in range(1,N):\n", 275 | " sum_ += ABS(REF(value,i)-mean)\n", 276 | " return sum_/N\n", 277 | "'''\n", 278 | "print (\"《RQALPHA本地化开始CCI选股》读取开始时间:==》n5\",n5) \n", 279 | "# 选股CCI OK!!!\n", 280 | "\n", 281 | "\n", 282 | "select(\n", 283 | " lambda : CROSS(((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14))) or ((((((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14)))+((V-MA(V,14))/(0.015*AVEDEV(V,14))))-MA((((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14)))+((V-MA(V,14))/(0.015*AVEDEV(V,14)))),14))/(0.015*AVEDEV((((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14)))+((V-MA(V,14))/(0.015*AVEDEV(V,14)))),14))))\n", 284 | "\n", 285 | ",101 or -101),\n", 286 | " start_date=(n3), end_date=(n2),)\n", 287 | "\n", 288 | "print (\"《结束选股》读取结束时间:==》n5\",n5) " 289 | ] 290 | }, 291 | { 292 | "cell_type": "code", 293 | "execution_count": null, 294 | "metadata": { 295 | "collapsed": true 296 | }, 297 | "outputs": [], 298 | "source": [ 299 | "import cython\n", 300 | "cython.__version__" 301 | ] 302 | }, 303 | { 304 | "cell_type": "code", 305 | "execution_count": null, 306 | "metadata": { 307 | "collapsed": true 308 | }, 309 | "outputs": [], 310 | "source": [ 311 | "from cython import * " 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": null, 317 | "metadata": { 318 | "collapsed": true 319 | }, 320 | "outputs": [], 321 | "source": [] 322 | } 323 | ], 324 | "metadata": { 325 | "kernelspec": { 326 | "display_name": "Python 3", 327 | "language": "python", 328 | "name": "python3" 329 | }, 330 | "language_info": { 331 | "codemirror_mode": { 332 | "name": "ipython", 333 | "version": 3 334 | }, 335 | "file_extension": ".py", 336 | "mimetype": "text/x-python", 337 | "name": "python", 338 | "nbconvert_exporter": "python", 339 | "pygments_lexer": "ipython3", 340 | "version": "3.5.4" 341 | } 342 | }, 343 | "nbformat": 4, 344 | "nbformat_minor": 2 345 | } 346 | -------------------------------------------------------------------------------- /rqalpha量化/回测 /Untitled1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 2 6 | } 7 | -------------------------------------------------------------------------------- /rqalpha量化/回测 /Untitled2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [] 9 | } 10 | ], 11 | "metadata": { 12 | "kernelspec": { 13 | "display_name": "Python 3", 14 | "language": "python", 15 | "name": "python3" 16 | }, 17 | "language_info": { 18 | "codemirror_mode": { 19 | "name": "ipython", 20 | "version": 3 21 | }, 22 | "file_extension": ".py", 23 | "mimetype": "text/x-python", 24 | "name": "python", 25 | "nbconvert_exporter": "python", 26 | "pygments_lexer": "ipython3", 27 | "version": "3.5.4" 28 | } 29 | }, 30 | "nbformat": 4, 31 | "nbformat_minor": 2 32 | } 33 | -------------------------------------------------------------------------------- /rqalpha量化/回测 /回测1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "ename": "IOError", 10 | "evalue": "[Errno 2] No such file or directory: 'config'", 11 | "output_type": "error", 12 | "traceback": [ 13 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 14 | "\u001b[0;31mIOError\u001b[0m Traceback (most recent call last)", 15 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;31m#congfig是我自己弄个一个配置文件,用来存放输出路径等\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"config\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m'rt'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mjsonFile\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 13\u001b[0m \u001b[0mval\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mjsonFile\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 14\u001b[0m \u001b[0mconfig\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mjson\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mloads\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mval\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m;\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 16 | "\u001b[0;31mIOError\u001b[0m: [Errno 2] No such file or directory: 'config'" 17 | ] 18 | } 19 | ], 20 | "source": [ 21 | "import tushare as ts\n", 22 | "import pandas as pd\n", 23 | "import time\n", 24 | "\n", 25 | "try:\n", 26 | " import json\n", 27 | "except ImportError:\n", 28 | " import simplejson as json\n", 29 | "\n", 30 | "#congfig是我自己弄个一个配置文件,用来存放输出路径等\n", 31 | "\n", 32 | "with open(\"config\",'rt') as jsonFile:\n", 33 | " val = jsonFile.read()\n", 34 | " config = json.loads(val);\n", 35 | "\n", 36 | "allData = ts.get_today_all()\n", 37 | "upDate = time.strftime(\"%Y-%m-%d\",time.localtime())\n", 38 | "upFileName = \"UP\"+upDate+\".csv\"\n", 39 | "\n", 40 | "allDataFileName = \"allData\"+upDate+\".csv\"\n", 41 | "\n", 42 | "outputAllDataFileDir = config['outputDir'] + \"/\" + allDataFileName\n", 43 | "\n", 44 | "outputUpDataFileDir = config['outputDir'] + \"/\" + upFileName\n", 45 | "\n", 46 | "upData = allData[allData.changepercent > 9.9]\n", 47 | "\n", 48 | "upData.to_csv(outputUpDataFileDir,encoding='gbk')\n", 49 | "allData.to_csv(outputAllDataFileDir,encoding='gbk')\n", 50 | "\n", 51 | "outputAllDataFileDir = config['outputDir'] + \"/\" + allDataFileName\n", 52 | "\n", 53 | "upData = pd.read_csv(outputUpDataFileDir,encoding='gbk',index_col =0,dtype={'code':str})\n", 54 | "\n", 55 | "print upData['code']" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [] 64 | } 65 | ], 66 | "metadata": { 67 | "kernelspec": { 68 | "display_name": "Python 3", 69 | "language": "python", 70 | "name": "python3" 71 | }, 72 | "language_info": { 73 | "codemirror_mode": { 74 | "name": "ipython", 75 | "version": 2 76 | }, 77 | "file_extension": ".py", 78 | "mimetype": "text/x-python", 79 | "name": "python", 80 | "nbconvert_exporter": "python", 81 | "pygments_lexer": "ipython2", 82 | "version": "2.7.13" 83 | } 84 | }, 85 | "nbformat": 4, 86 | "nbformat_minor": 2 87 | } 88 | -------------------------------------------------------------------------------- /rqalpha量化/回测 /回测3.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stderr", 10 | "output_type": "stream", 11 | "text": [ 12 | "/Users/zy/anaconda3/envs/ths-27/lib/python2.7/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: The finance module has been deprecated in mpl 2.0 and will be removed in mpl 2.2. Please use the module mpl_finance instead.\n", 13 | " warnings.warn(message, mplDeprecation, stacklevel=1)\n" 14 | ] 15 | }, 16 | { 17 | "ename": "KeyError", 18 | "evalue": "'BB'", 19 | "output_type": "error", 20 | "traceback": [ 21 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 22 | "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", 23 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 50\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 51\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m'__main__'\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 52\u001b[0;31m \u001b[0mset_symbols\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'BB.SHFE-1.Minute'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 53\u001b[0m \u001b[0;31m# 创建组合策略\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 54\u001b[0m \u001b[0;31m# 初始资金5000, 两个策略的资金配比为0.2:0.8\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 24 | "\u001b[0;32m/Users/zy/anaconda3/envs/ths-27/lib/python2.7/site-packages/quantdigger/engine/qd.pyc\u001b[0m in \u001b[0;36mset_symbols\u001b[0;34m(pcontracts, dt_start, dt_end, n, spec_date)\u001b[0m\n\u001b[1;32m 17\u001b[0m \"\"\"\n\u001b[1;32m 18\u001b[0m \u001b[0;32mglobal\u001b[0m \u001b[0m_simulator\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 19\u001b[0;31m \u001b[0m_simulator\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mExecuteUnit\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mpcontracts\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdt_start\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdt_end\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mspec_date\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 20\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0m_simulator\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 21\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", 25 | "\u001b[0;32m/Users/zy/anaconda3/envs/ths-27/lib/python2.7/site-packages/quantdigger/engine/execute_unit.pyc\u001b[0m in \u001b[0;36m__init__\u001b[0;34m(self, pcontracts, dt_start, dt_end, n, spec_date)\u001b[0m\n\u001b[1;32m 31\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_data_manager\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mDataManager\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 32\u001b[0m \u001b[0;31m# str(PContract): DataWrapper\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 33\u001b[0;31m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpcontracts\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_parse_pcontracts\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpcontracts\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 34\u001b[0m self._all_data, self._max_window = self._load_data(self.pcontracts,\n\u001b[1;32m 35\u001b[0m \u001b[0mdt_start\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 26 | "\u001b[0;32m/Users/zy/anaconda3/envs/ths-27/lib/python2.7/site-packages/quantdigger/engine/execute_unit.pyc\u001b[0m in \u001b[0;36m_parse_pcontracts\u001b[0;34m(self, pcontracts)\u001b[0m\n\u001b[1;32m 71\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 72\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 73\u001b[0;31m \u001b[0mpcons\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcode2strpcon\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mcode\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 74\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mIndexError\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 75\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mIndexError\u001b[0m \u001b[0;31m# 本地不含该文件\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 27 | "\u001b[0;31mKeyError\u001b[0m: 'BB'" 28 | ] 29 | } 30 | ], 31 | "source": [ 32 | "#from quantdigger.engine.series import NumberSeries\n", 33 | "#from quantdigger.indicators.common import MA\n", 34 | "#from quantdigger.util import pcontract\n", 35 | "from quantdigger import *\n", 36 | "import six\n", 37 | "\n", 38 | "class DemoStrategy(Strategy):\n", 39 | " \"\"\" 策略A1 \"\"\"\n", 40 | "\n", 41 | " def on_init(self, ctx):\n", 42 | " \"\"\"初始化数据\"\"\"\n", 43 | " ctx.ma10 = MA(ctx.close, 10, 'ma10', 'y', 2)\n", 44 | " ctx.ma20 = MA(ctx.close, 20, 'ma20', 'b', 2)\n", 45 | "\n", 46 | " def on_symbol(self, ctx):\n", 47 | " \"\"\" 选股 \"\"\"\n", 48 | " return\n", 49 | "\n", 50 | " def on_bar(self, ctx):\n", 51 | " if ctx.curbar > 20:\n", 52 | " if ctx.ma10[2] < ctx.ma20[2] and ctx.ma10[1] > ctx.ma20[1]:\n", 53 | " ctx.buy(ctx.close, 1)\n", 54 | " elif ctx.pos() > 0 and ctx.ma10[2] > ctx.ma20[2] and \\\n", 55 | " ctx.ma10[1] < ctx.ma20[1]:\n", 56 | " ctx.sell(ctx.close, ctx.pos())\n", 57 | "\n", 58 | " def on_exit(self, ctx):\n", 59 | " return\n", 60 | "\n", 61 | "class DemoStrategy2(Strategy):\n", 62 | " \"\"\" 策略A2 \"\"\"\n", 63 | "\n", 64 | " def on_init(self, ctx):\n", 65 | " \"\"\"初始化数据\"\"\"\n", 66 | " ctx.ma5 = MA(ctx.close, 5, 'ma5', 'y', 2)\n", 67 | " ctx.ma10 = MA(ctx.close, 10, 'ma10', 'black', 2)\n", 68 | "\n", 69 | " def on_symbol(self, ctx):\n", 70 | " \"\"\" 选股 \"\"\"\n", 71 | " return\n", 72 | "\n", 73 | " def on_bar(self, ctx):\n", 74 | " if ctx.curbar > 10:\n", 75 | " if ctx.ma5[2] < ctx.ma10[2] and ctx.ma5[1] > ctx.ma10[1]:\n", 76 | " ctx.buy(ctx.close, 1)\n", 77 | " elif ctx.pos() > 0 and ctx.ma5[2] > ctx.ma10[2] and \\\n", 78 | " ctx.ma5[1] < ctx.ma10[1]:\n", 79 | " ctx.sell(ctx.close, ctx.pos())\n", 80 | "\n", 81 | " def on_exit(self, ctx):\n", 82 | " return\n", 83 | "\n", 84 | "if __name__ == '__main__':\n", 85 | " set_symbols(['BB.SHFE-1.Minute'], 0)\n", 86 | " # 创建组合策略\n", 87 | " # 初始资金5000, 两个策略的资金配比为0.2:0.8\n", 88 | " profile = add_strategy([DemoStrategy('A1'), DemoStrategy2('A2')], { 'captial': 5000,\n", 89 | " 'ratio': [0.2, 0.8] })\n", 90 | " run()\n", 91 | "\n", 92 | " # 绘制k线,交易信号线\n", 93 | " from quantdigger.digger import finance, plotting\n", 94 | " plotting.plot_strategy(profile.data(0), profile.indicators(1), profile.deals(1))\n", 95 | " # 绘制策略A1, 策略A2, 组合的资金曲线\n", 96 | " curve0 = finance.create_equity_curve(profile.all_holdings(0))\n", 97 | " curve1 = finance.create_equity_curve(profile.all_holdings(1))\n", 98 | " curve = finance.create_equity_curve(profile.all_holdings())\n", 99 | " plotting.plot_curves([curve0.equity, curve1.equity, curve.equity],\n", 100 | " colors=['r', 'g', 'b'],\n", 101 | " names=[profile.name(0), profile.name(1), 'A0'])\n", 102 | " # 绘制净值曲线\n", 103 | " plotting.plot_curves([curve.networth])\n", 104 | " # 打印统计信息\n", 105 | " six.print_(finance.summary_stats(curve, 252*4*60))" 106 | ] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "execution_count": null, 111 | "metadata": {}, 112 | "outputs": [], 113 | "source": [] 114 | } 115 | ], 116 | "metadata": { 117 | "kernelspec": { 118 | "display_name": "Python 3", 119 | "language": "python", 120 | "name": "python3" 121 | }, 122 | "language_info": { 123 | "codemirror_mode": { 124 | "name": "ipython", 125 | "version": 2 126 | }, 127 | "file_extension": ".py", 128 | "mimetype": "text/x-python", 129 | "name": "python", 130 | "nbconvert_exporter": "python", 131 | "pygments_lexer": "ipython2", 132 | "version": "2.7.13" 133 | } 134 | }, 135 | "nbformat": 4, 136 | "nbformat_minor": 2 137 | } 138 | -------------------------------------------------------------------------------- /rqalpha量化/实例/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/rqalpha量化/实例/.DS_Store -------------------------------------------------------------------------------- /rqalpha量化/实例/Untitled的副本.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 3, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from matplotlib import rcParams\n", 10 | "import matplotlib.pyplot as plt\n", 11 | "import numpy as np\n", 12 | "\n", 13 | "np.seterr(all='ignore')\n", 14 | "rcParams['figure.figsize'] = (14, 6)\n", 15 | "\n", 16 | "#扩展MOD\n", 17 | "from funcat import * #FUNCAT的同花顺/通达信指标模块:和:&,或:|,其他基本相同。可以使用指标选股!!!\n", 18 | "#from pytdx import * #通达信数据更新模块到QUANTAXIS的mongoDB\n", 19 | "from tushare import * #TUSHARE数据连接更新。\n", 20 | "from rqalpha import * #RQALPHA本地数据连接,通过 rqalpha update_bundle 8点后更新全部数据库" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 5, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "import datetime\n", 30 | "import numpy as np\n", 31 | "import pandas as pd\n", 32 | "import talib\n", 33 | "\n", 34 | "#问题是如何拿到每周数据 price的\n", 35 | "def init(context):\n", 36 | " context.stocks = index_components('000300.XSHG')\n", 37 | " scheduler.run_daily(sell,time_rule=market_close(minute = 20))\n", 38 | " scheduler.run_daily(buy,time_rule = market_open(hour =1))\n", 39 | "\n", 40 | "def stocks_list(context,bar_dict):\n", 41 | " buy_list= []\n", 42 | " for stock in context.stocks:\n", 43 | " hist_high = history_bars(stock,30,'1d',fields='high')\n", 44 | " hist_low = history_bars(stock,30,'1d',fields='low')\n", 45 | " hist_close = history_bars(stock,30,'1d',fields='close')\n", 46 | " hist_volume = history_bars(stock,30,'1d',fields='volume')\n", 47 | " \n", 48 | " #求周线的kd金叉\n", 49 | " hist_m_high = history_bars(stock,150,'1d',fields='high')[::5]\n", 50 | " hist_m_low = history_bars(stock,150,'1d',fields='low')[::5]\n", 51 | " hist_m_close = history_bars(stock,150,'1d',fields='close')[::5]\n", 52 | " \n", 53 | " \n", 54 | " slowk,slowd = talib.STOCH(hist_high,hist_low,hist_close,fastk_period = 9,slowk_period = 3,slowk_matype=0,slowd_period=3,slowd_matype=0)\n", 55 | " \n", 56 | " slowk_m,slowd_m = talib.STOCH(hist_m_high,hist_m_low,hist_m_close,fastk_period = 9,slowk_period = 3,slowk_matype=0,slowd_period=3,slowd_matype=0)\n", 57 | " \n", 58 | " \n", 59 | " #k和d在小于35的地方金叉了\n", 60 | " if slowk[-1]<35 or slowd[-1]<35:\n", 61 | " if slowk[-1]>slowd[-1] and slowk[-2]hist_volume[-2]: #量比增加了\n", 63 | " if slowk_m[-1]<40:\n", 64 | " if slowk_m[-1]-slowd_m[-1]>6:\n", 65 | " print('day high',stock,hist_high,hist_low,hist_close)\n", 66 | " print ('月high',stock,hist_m_high,hist_m_low,hist_m_close)\n", 67 | " print ('buy',stock,slowk_m)\n", 68 | " buy_list.append(stock)\n", 69 | " print('st to buy',len(buy_list))\n", 70 | " return buy_list\n", 71 | "\n", 72 | "def sell(context,bar_dict):\n", 73 | " for stock in context.portfolio.positions.keys():\n", 74 | " hist_high = history_bars(stock,150,'1d',fields='high')[::5]\n", 75 | " hist_low = history_bars(stock,150,'1d',fields='low')[::5]\n", 76 | " hist_close = history_bars(stock,150,'1d',fields='close')[::5]\n", 77 | " slowk,slowd = talib.STOCH(hist_high,hist_low,hist_close,fastk_period = 9,slowk_period = 3,slowk_matype=0,slowd_period=3,slowd_matype=0)\n", 78 | " if slowk[-1]0:\n", 86 | " weight = 0.98*cash/len(stock_to_buy)\n", 87 | " for i in stock_to_buy:\n", 88 | " try:\n", 89 | " order_target_value(i,weight,style = LimitOrder(bar_dict[i].limit_up))\n", 90 | " except:\n", 91 | " order_target_value(i,weight)\n", 92 | " \n", 93 | " \n", 94 | " \n", 95 | " \n", 96 | " \n", 97 | " \n", 98 | " \n", 99 | "\n" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": null, 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [] 108 | } 109 | ], 110 | "metadata": { 111 | "kernelspec": { 112 | "display_name": "Python 3", 113 | "language": "python", 114 | "name": "python3" 115 | }, 116 | "language_info": { 117 | "codemirror_mode": { 118 | "name": "ipython", 119 | "version": 3 120 | }, 121 | "file_extension": ".py", 122 | "mimetype": "text/x-python", 123 | "name": "python", 124 | "nbconvert_exporter": "python", 125 | "pygments_lexer": "ipython3", 126 | "version": "3.5.4" 127 | } 128 | }, 129 | "nbformat": 4, 130 | "nbformat_minor": 2 131 | } 132 | -------------------------------------------------------------------------------- /rqalpha量化/实例/pytdxtest.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 4, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "#coding: utf-8\n", 10 | "\n", 11 | "from collections import OrderedDict\n", 12 | "\n", 13 | "import pandas as pd\n", 14 | "import pytest\n", 15 | "from pytdx.errors import TdxConnectionError, TdxFunctionCallError\n", 16 | "from pytdx.hq import TdxHq_API, TDXParams\n", 17 | "\n", 18 | "\n", 19 | "class Log(object):\n", 20 | " def info(self, *args):\n", 21 | " pass\n", 22 | "\n", 23 | "\n", 24 | "log = Log()\n", 25 | "\n", 26 | "\n", 27 | "# 测试任意组合的选项\n", 28 | "@pytest.mark.parametrize(\"multithread\", [True])\n", 29 | "@pytest.mark.parametrize(\"heartbeat\", [True])\n", 30 | "@pytest.mark.parametrize(\"auto_retry\", [True])\n", 31 | "@pytest.mark.parametrize(\"raise_exception\", [True])\n", 32 | "\n", 33 | "def test_all_functions(multithread, heartbeat, auto_retry, raise_exception):\n", 34 | "\n", 35 | " api = TdxHq_API(multithread=multithread, heartbeat=heartbeat,\n", 36 | " auto_retry=auto_retry, raise_exception=raise_exception)\n", 37 | " with api.connect(time_out=30):\n", 38 | " log.info(\"获取股票行情\")\n", 39 | " stocks = api.get_security_quotes([(0, \"000001\"), (1, \"600300\")])\n", 40 | " assert stocks is not None\n", 41 | " assert type(stocks) is list\n", 42 | "\n", 43 | " # 方法2\n", 44 | " stocks = api.get_security_quotes(0, \"000001\")\n", 45 | " assert stocks is not None\n", 46 | " assert type(stocks) is list\n", 47 | "\n", 48 | " # 方法3\n", 49 | " stocks = api.get_security_quotes((0, \"000001\"))\n", 50 | " assert stocks is not None\n", 51 | " assert type(stocks) is list\n", 52 | "\n", 53 | " log.info(\"获取k线\")\n", 54 | " data = api.get_security_bars(9, 0, '000001', 4, 3)\n", 55 | " assert data is not None\n", 56 | " assert type(data) is list\n", 57 | " assert len(data) == 3\n", 58 | "\n", 59 | " log.info(\"获取 深市 股票数量\")\n", 60 | " assert api.get_security_count(0) > 0\n", 61 | "\n", 62 | " log.info(\"获取股票列表\")\n", 63 | " stocks = api.get_security_list(1, 0)\n", 64 | " assert stocks is not None\n", 65 | " assert type(stocks) is list\n", 66 | " assert len(stocks) > 0\n", 67 | "\n", 68 | " log.info(\"获取指数k线\")\n", 69 | " data = api.get_index_bars(9, 1, '000001', 1, 2)\n", 70 | " assert data is not None\n", 71 | " assert type(data) is list\n", 72 | " assert len(data) == 2\n", 73 | "\n", 74 | " log.info(\"查询分时行情\")\n", 75 | " data = api.get_minute_time_data(TDXParams.MARKET_SH, '600300')\n", 76 | " assert data is not None\n", 77 | "\n", 78 | " log.info(\"查询历史分时行情\")\n", 79 | " data = api.get_history_minute_time_data(\n", 80 | " TDXParams.MARKET_SH, '600300', 20161209)\n", 81 | " assert data is not None\n", 82 | " assert type(data) is list\n", 83 | " assert len(data) > 0\n", 84 | "\n", 85 | " log.info(\"查询分时成交\")\n", 86 | " data = api.get_transaction_data(TDXParams.MARKET_SZ, '000001', 0, 30)\n", 87 | " assert data is not None\n", 88 | " assert type(data) is list\n", 89 | "\n", 90 | " log.info(\"查询历史分时成交\")\n", 91 | " data = api.get_history_transaction_data(\n", 92 | " TDXParams.MARKET_SZ, '000001', 0, 10, 20170209)\n", 93 | "\n", 94 | " assert data is not None\n", 95 | " assert type(data) is list\n", 96 | " assert len(data) == 10\n", 97 | "\n", 98 | " log.info(\"查询公司信息目录\")\n", 99 | " data = api.get_company_info_category(TDXParams.MARKET_SZ, '000001')\n", 100 | " assert data is not None\n", 101 | " assert type(data) is list\n", 102 | " assert len(data) > 0\n", 103 | "\n", 104 | " start = data[0]['start']\n", 105 | " length = data[0]['length']\n", 106 | " log.info(\"读取公司信息-最新提示\")\n", 107 | " data = api.get_company_info_content(\n", 108 | " 0, '000001', '000001.txt', start, length)\n", 109 | " assert data is not None\n", 110 | " assert len(data) > 0\n", 111 | "\n", 112 | " log.info(\"读取除权除息信息\")\n", 113 | " data = api.get_xdxr_info(1, '600300')\n", 114 | " assert data is not None\n", 115 | " assert type(data) is list\n", 116 | " assert len(data) > 0\n", 117 | "\n", 118 | " log.info(\"读取财务信息\")\n", 119 | " data = api.get_finance_info(0, '000001')\n", 120 | " assert data is not None\n", 121 | " assert type(data) is OrderedDict\n", 122 | " assert len(data) > 0\n", 123 | "\n", 124 | " log.info(\"日线级别k线获取函数\")\n", 125 | " data = api.get_k_data('000001', '2017-07-01', '2017-07-10')\n", 126 | " assert type(data) is pd.DataFrame\n", 127 | " assert len(data) == 6\n", 128 | "\n", 129 | " log.info(\"获取板块信息\")\n", 130 | " data = api.get_and_parse_block_info(TDXParams.BLOCK_FG)\n", 131 | " assert data is not None\n", 132 | " assert type(data) is list\n", 133 | " assert len(data) > 0\n", 134 | "\n", 135 | "\n", 136 | "def test_raise_excepiton():\n", 137 | " api = TdxHq_API(raise_exception=True)\n", 138 | " with pytest.raises(TdxConnectionError):\n", 139 | " with api.connect('8.8.8.8'):\n", 140 | " pass\n" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "metadata": {}, 147 | "outputs": [], 148 | "source": [] 149 | } 150 | ], 151 | "metadata": { 152 | "kernelspec": { 153 | "display_name": "Python 3", 154 | "language": "python", 155 | "name": "python3" 156 | }, 157 | "language_info": { 158 | "codemirror_mode": { 159 | "name": "ipython", 160 | "version": 3 161 | }, 162 | "file_extension": ".py", 163 | "mimetype": "text/x-python", 164 | "name": "python", 165 | "nbconvert_exporter": "python", 166 | "pygments_lexer": "ipython3", 167 | "version": "3.5.4" 168 | } 169 | }, 170 | "nbformat": 4, 171 | "nbformat_minor": 2 172 | } 173 | -------------------------------------------------------------------------------- /rqalpha量化/实例/test.py: -------------------------------------------------------------------------------- 1 | from rqalpha.api import * 2 | -------------------------------------------------------------------------------- /rqalpha量化/实例/ths api.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 5, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from matplotlib import rcParams\n", 10 | "import matplotlib.pyplot as plt\n", 11 | "import numpy as np\n", 12 | "\n", 13 | "np.seterr(all='ignore')\n", 14 | "rcParams['figure.figsize'] = (14, 6)" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 6, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "from funcat import *\n", 24 | "from pytdx import *\n", 25 | "from tushare import *\n", 26 | "from rqalpha import *\n", 27 | "#from jaqs import *\n", 28 | "#from abupy import *\n", 29 | "#from quantaxis import *\n", 30 | "#from hikyuu import *" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 7, 36 | "metadata": {}, 37 | "outputs": [ 38 | { 39 | "name": "stdout", 40 | "output_type": "stream", 41 | "text": [ 42 | "读取当日时间格式n1 2018-02-02\n", 43 | "读取当日时间格式n2 20180202\n", 44 | "读取前一日时间格式n3 2018-02-01\n", 45 | "读取当日时间格式n4 201822\n", 46 | "读取当日时间格式n5 2018-02-02T07:38:32.334222\n", 47 | "手动设定选股开始时间格式n8 20180201\n", 48 | "手动设定选股结束时间格式n9 20180201\n", 49 | "手动设定数据更新设定起始时间格式n10 20160101\n", 50 | "设定股票代码 000001.XSHG 603377.XSHG\n" 51 | ] 52 | } 53 | ], 54 | "source": [ 55 | "import time\n", 56 | "import datetime\n", 57 | "n1 = (time.strftime(\"20%y-%m-%d\"))## 20yy-mm-dd格式,输出当日日期\n", 58 | "n2 = (time.strftime(\"20%y%m%d\"))## 20yymmdd格式,输出当日日期\n", 59 | "#print (time.strftime(\"20%y-%m-%d\")) ## dd/mm/yyyy格式,输出当日日期\n", 60 | "#print (time.strftime(\"20%y%m%d\"))\n", 61 | "def getYesterday(): \n", 62 | " today=datetime.date.today() \n", 63 | " oneday=datetime.timedelta(days=1) \n", 64 | " yesterday=today-oneday \n", 65 | " return yesterday\n", 66 | "n3 = (getYesterday())# 输出前一天日期\n", 67 | "i = datetime.datetime.now()#当前日期\n", 68 | "n4 = (\"%s%s%s\" % (i.year, i.month, i.day) )\n", 69 | "n5 = (\"%s\" % i.isoformat() )\n", 70 | "print (\"读取当日时间格式n1\",n1) #当日时间格式:yyyy-mm-dd\n", 71 | "print (\"读取当日时间格式n2\",n2) #当日时间格式:yyyymmdd\n", 72 | "print (\"读取前一日时间格式n3\",n3) #前日时间格式:yyyy-mm-dd\n", 73 | "print (\"读取当日时间格式n4\",n4) #当日时间格式:yyyymmdd\n", 74 | "print (\"读取当日时间格式n5\",n5) #当日时间格式:yyyy-mm-dd:...\n", 75 | "n8=\"20180201\"#开始时间\n", 76 | "print (\"手动设定选股开始时间格式n8\",n8)\n", 77 | "n9=\"20180201\"#结束时间\n", 78 | "print (\"手动设定选股结束时间格式n9\",n9)\n", 79 | "n10=\"20160101\"#设定起始时间\n", 80 | "print (\"手动设定数据更新设定起始时间格式n10\",n10)\n", 81 | "x1=\"000001.XSHG\"\n", 82 | "x2=\"603377.XSHG\"\n", 83 | "print (\"设定股票代码\",x1,x2)" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": 8, 89 | "metadata": {}, 90 | "outputs": [], 91 | "source": [ 92 | "from funcat.data.tushare_backend import TushareDataBackend\n", 93 | "from funcat.data.rqalpha_data_backend import RQAlphaDataBackend\n", 94 | "\n", 95 | "backend = \"tushare\"\n", 96 | "\n", 97 | "if backend == \"rqalpha\":\n", 98 | " set_data_backend(RQAlphaDataBackend(\"~/.rqalpha/bundle\"))\n", 99 | "elif backend == \"tushare\":\n", 100 | " set_data_backend(TushareDataBackend())\n", 101 | "\n", 102 | "set_start_date(n10)\n", 103 | "S(x1) # 设置当前关注股票\n", 104 | "T(n9) # 设置当前观察日期" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": 9, 110 | "metadata": {}, 111 | "outputs": [ 112 | { 113 | "name": "stdout", 114 | "output_type": "stream", 115 | "text": [ 116 | "打印 开盘 最高 最低 收盘 成交量 3478.67 3495.09 3424.42 3446.98 260504707.0\n", 117 | "当天涨幅 -0.00972469209929816\n", 118 | "打印60日均线 3380.675999999998\n", 119 | "判断收盘价是否大于60日均线 True\n", 120 | "30日最高价 3587.03\n", 121 | "最近30日,收盘价 Close 大于60日均线的天数 22\n", 122 | "10日均线上穿 False\n", 123 | "最近10天收阳线的天数 6\n", 124 | "最近60天K线实体的最高价 3563.64\n", 125 | "5日均线上穿10日均线 False\n" 126 | ] 127 | } 128 | ], 129 | "source": [ 130 | "print (\"打印 开盘 最高 最低 收盘 成交量\",O, H, L, C, V) # 打印 Open High Low Close\n", 131 | "print (\"当天涨幅\",C / C[1] - 1) # 当天涨幅\n", 132 | "print (\"打印60日均线\",MA(C, 60)) # 打印60日均线\n", 133 | "print (\"判断收盘价是否大于60日均线\",C > MA(C, 60)) # 判断收盘价是否大于60日均线\n", 134 | "print (\"30日最高价\",HHV(H, 30)) # 30日最高价\n", 135 | "print (\"最近30日,收盘价 Close 大于60日均线的天数\",COUNT(C > MA(C, 60), 30)) # 最近30日,收盘价 Close 大于60日均线的天数\n", 136 | "print (\"10日均线上穿\",CROSS(MA(C, 10), MA(C, 20))) # 10日均线上穿\n", 137 | "print (\"最近10天收阳线的天数\",COUNT(C > O, 10)) # 最近10天收阳线的天数\n", 138 | "print (\"最近60天K线实体的最高价\",HHV(MAX(O, C), 60)) # 最近60天K线实体的最高价\n", 139 | "print (\"5日均线上穿10日均线\",CROSS(MA(C, 5), MA(C, 10))) # 5日均线上穿10日均线\n", 140 | "\n" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "metadata": {}, 147 | "outputs": [], 148 | "source": [] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": 17, 153 | "metadata": {}, 154 | "outputs": [ 155 | { 156 | "ename": "NameError", 157 | "evalue": "name 'K' is not defined", 158 | "output_type": "error", 159 | "traceback": [ 160 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 161 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", 162 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 19\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 20\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mK\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mD\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mJ\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 21\u001b[0;31m \u001b[0mprint\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mK\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mD\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mJ\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 22\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mDMI\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mM1\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m14\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mM2\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m6\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 163 | "\u001b[0;31mNameError\u001b[0m: name 'K' is not defined" 164 | ] 165 | } 166 | ], 167 | "source": [ 168 | "# -*- coding: utf-8 -*-\n", 169 | "\"\"\"\n", 170 | "from .api import (\n", 171 | " OPEN, HIGH, LOW, CLOSE, VOLUME, VOL,\n", 172 | " ABS, MAX, HHV, LLV,\n", 173 | " REF, IF, SUM, STD,\n", 174 | " MA, EMA, SMA,\n", 175 | ")\n", 176 | "\n", 177 | "\"\"\"\n", 178 | "def KDJ(N=9, M1=3, M2=3):\n", 179 | " \"\"\"\n", 180 | " KDJ 随机指标\n", 181 | " \"\"\"\n", 182 | " RSV = (CLOSE - LLV(LOW, N)) / (HHV(HIGH, N) - LLV(LOW, N)) * 100\n", 183 | " K = EMA(RSV, (M1 * 2 - 1))\n", 184 | " D = EMA(K, (M2 * 2 - 1))\n", 185 | " J = K * 3 - D * 2\n", 186 | "\n", 187 | " return K, D, J\n", 188 | "print (K,D,J)\n", 189 | "\n", 190 | "def DMI(M1=14, M2=6):\n", 191 | " \"\"\"\n", 192 | " DMI 趋向指标\n", 193 | " \"\"\"\n", 194 | " TR = SUM(MAX(MAX(HIGH - LOW, ABS(HIGH - REF(CLOSE, 1))), ABS(LOW - REF(CLOSE, 1))), M1)\n", 195 | " HD = HIGH - REF(HIGH, 1)\n", 196 | " LD = REF(LOW, 1) - LOW\n", 197 | "\n", 198 | " DMP = SUM(IF((HD > 0) & (HD > LD), HD, 0), M1)\n", 199 | " DMM = SUM(IF((LD > 0) & (LD > HD), LD, 0), M1)\n", 200 | " DI1 = DMP * 100 / TR\n", 201 | " DI2 = DMM * 100 / TR\n", 202 | " ADX = MA(ABS(DI2 - DI1) / (DI1 + DI2) * 100, M2)\n", 203 | " ADXR = (ADX + REF(ADX, M2)) / 2\n", 204 | "\n", 205 | " return DI1, DI2, ADX, ADXR\n", 206 | "\n", 207 | "\n", 208 | "def MACD(SHORT=12, LONG=26, M=9):\n", 209 | " \"\"\"\n", 210 | " MACD 指数平滑移动平均线\n", 211 | " \"\"\"\n", 212 | " DIFF = EMA(CLOSE, SHORT) - EMA(CLOSE, LONG)\n", 213 | " DEA = EMA(DIFF, M)\n", 214 | " MACD = (DIFF - DEA) * 2\n", 215 | "\n", 216 | " return MACD\n", 217 | "\n", 218 | "\n", 219 | "def RSI(N1=6, N2=12, N3=24):\n", 220 | " \"\"\"\n", 221 | " RSI 相对强弱指标\n", 222 | " \"\"\"\n", 223 | " LC = REF(CLOSE, 1)\n", 224 | " RSI1 = SMA(MAX(CLOSE - LC, 0), N1, 1) / SMA(ABS(CLOSE - LC), N1, 1) * 100\n", 225 | " RSI2 = SMA(MAX(CLOSE - LC, 0), N2, 1) / SMA(ABS(CLOSE - LC), N2, 1) * 100\n", 226 | " RSI3 = SMA(MAX(CLOSE - LC, 0), N3, 1) / SMA(ABS(CLOSE - LC), N3, 1) * 100\n", 227 | "\n", 228 | " return RSI1, RSI2, RSI3\n", 229 | "\n", 230 | "\n", 231 | "def BOLL(N=20, P=2):\n", 232 | " \"\"\"\n", 233 | " BOLL 布林带\n", 234 | " \"\"\"\n", 235 | " MID = MA(CLOSE, N)\n", 236 | " UPPER = MID + STD(CLOSE, N) * P\n", 237 | " LOWER = MID - STD(CLOSE, N) * P\n", 238 | "\n", 239 | " return UPPER, MID, LOWER\n", 240 | "\n", 241 | "\n", 242 | "def WR(N=10, N1=6):\n", 243 | " \"\"\"\n", 244 | " W&R 威廉指标\n", 245 | " \"\"\"\n", 246 | " WR1 = (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N)) * 100\n", 247 | " WR2 = (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1)) * 100\n", 248 | "\n", 249 | " return WR1, WR2\n", 250 | "\n", 251 | "\n", 252 | "def BIAS(L1=5, L4=3, L5=10):\n", 253 | " \"\"\"\n", 254 | " BIAS 乖离率\n", 255 | " \"\"\"\n", 256 | " BIAS = (CLOSE - MA(CLOSE, L1)) / MA(CLOSE, L1) * 100\n", 257 | " BIAS2 = (CLOSE - MA(CLOSE, L4)) / MA(CLOSE, L4) * 100\n", 258 | " BIAS3 = (CLOSE - MA(CLOSE, L5)) / MA(CLOSE, L5) * 100\n", 259 | "\n", 260 | " return BIAS, BIAS2, BIAS3\n", 261 | "\n", 262 | "\n", 263 | "def ASI(M1=26, M2=10):\n", 264 | " \"\"\"\n", 265 | " ASI 震动升降指标\n", 266 | " \"\"\"\n", 267 | " LC = REF(CLOSE, 1)\n", 268 | " AA = ABS(HIGH - LC)\n", 269 | " BB = ABS(LOW - LC)\n", 270 | " CC = ABS(HIGH - REF(LOW, 1))\n", 271 | " DD = ABS(LC - REF(OPEN, 1))\n", 272 | " R = IF((AA > BB) & (AA > CC), AA + BB / 2 + DD / 4, IF((BB > CC) & (BB > AA), BB + AA / 2 + DD / 4, CC + DD / 4))\n", 273 | " X = (CLOSE - LC + (CLOSE - OPEN) / 2 + LC - REF(OPEN, 1))\n", 274 | " SI = X * 16 / R * MAX(AA, BB)\n", 275 | " ASI = SUM(SI, M1)\n", 276 | " ASIT = MA(ASI, M2)\n", 277 | "\n", 278 | " return ASI, ASIT\n", 279 | "\n", 280 | "\n", 281 | "def VR(M1=26):\n", 282 | " \"\"\"\n", 283 | " VR容量比率\n", 284 | " \"\"\"\n", 285 | " LC = REF(CLOSE, 1)\n", 286 | " VR = SUM(IF(CLOSE > LC, VOL, 0), M1) / SUM(IF(CLOSE <= LC, VOL, 0), M1) * 100\n", 287 | "\n", 288 | " return VR\n", 289 | "\n", 290 | "\n", 291 | "def ARBR(M1=26):\n", 292 | " \"\"\"\n", 293 | " ARBR人气意愿指标\n", 294 | " \"\"\"\n", 295 | " AR = SUM(HIGH - OPEN, M1) / SUM(OPEN - LOW, M1) * 100\n", 296 | " BR = SUM(MAX(0, HIGH - REF(CLOSE, 1)), M1) / SUM(MAX(0, REF(CLOSE, 1) - LOW), M1) * 100\n", 297 | "\n", 298 | " return AR, BR\n", 299 | "\n", 300 | "\n", 301 | "def DPO(M1=20, M2=10, M3=6):\n", 302 | " DPO = CLOSE - REF(MA(CLOSE, M1), M2)\n", 303 | " MADPO = MA(DPO, M3)\n", 304 | "\n", 305 | " return DPO, MADPO\n", 306 | "\n", 307 | "\n", 308 | "def TRIX(M1=12, M2=20):\n", 309 | " TR = EMA(EMA(EMA(CLOSE, M1), M1), M1)\n", 310 | " TRIX = (TR - REF(TR, 1)) / REF(TR, 1) * 100\n", 311 | " TRMA = MA(TRIX, M2)\n", 312 | "\n", 313 | " return TRIX, TRMA\n" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": 14, 319 | "metadata": {}, 320 | "outputs": [ 321 | { 322 | "name": "stdout", 323 | "output_type": "stream", 324 | "text": [ 325 | "\n" 326 | ] 327 | } 328 | ], 329 | "source": [ 330 | "\n" 331 | ] 332 | }, 333 | { 334 | "cell_type": "code", 335 | "execution_count": null, 336 | "metadata": {}, 337 | "outputs": [], 338 | "source": [] 339 | } 340 | ], 341 | "metadata": { 342 | "kernelspec": { 343 | "display_name": "Python 3", 344 | "language": "python", 345 | "name": "python3" 346 | }, 347 | "language_info": { 348 | "codemirror_mode": { 349 | "name": "ipython", 350 | "version": 3 351 | }, 352 | "file_extension": ".py", 353 | "mimetype": "text/x-python", 354 | "name": "python", 355 | "nbconvert_exporter": "python", 356 | "pygments_lexer": "ipython3", 357 | "version": "3.5.4" 358 | } 359 | }, 360 | "nbformat": 4, 361 | "nbformat_minor": 2 362 | } 363 | -------------------------------------------------------------------------------- /rqalpha量化/实例/ths-rqalpha.py: -------------------------------------------------------------------------------- 1 | 2 | # coding: utf-8 3 | 4 | # In[1]: 5 | 6 | 7 | from matplotlib import rcParams 8 | import matplotlib.pyplot as plt 9 | import numpy as np 10 | 11 | np.seterr(all='ignore') 12 | rcParams['figure.figsize'] = (14, 6) 13 | 14 | 15 | # In[2]: 16 | 17 | 18 | from funcat import * 19 | from pytdx import * 20 | from tushare import * 21 | from rqalpha import * 22 | 23 | 24 | # In[3]: 25 | 26 | 27 | import time 28 | import datetime 29 | n1 = (time.strftime("20%y-%m-%d"))## 20yy-mm-dd格式,输出当日日期 30 | n2 = (time.strftime("20%y%m%d"))## 20yymmdd格式,输出当日日期 31 | #print (time.strftime("20%y-%m-%d")) ## dd/mm/yyyy格式,输出当日日期 32 | #print (time.strftime("20%y%m%d")) 33 | def getYesterday(): 34 | today=datetime.date.today() 35 | oneday=datetime.timedelta(days=1) 36 | yesterday=today-oneday 37 | return yesterday 38 | n3 = (getYesterday())# 输出前一天日期 39 | i = datetime.datetime.now()#当前日期 40 | n4 = ("%s%s%s" % (i.year, i.month, i.day) ) 41 | n5 = ("%s" % i.isoformat() ) 42 | print ("读取当日时间格式n1",n1) #当日时间格式:yyyy-mm-dd 43 | print ("读取当日时间格式n2",n2) #当日时间格式:yyyymmdd 44 | print ("读取前一日时间格式n3",n3) #前日时间格式:yyyy-mm-dd 45 | print ("读取当日时间格式n4",n4) #当日时间格式:yyyymmdd 46 | print ("读取当日时间格式n5",n5) #当日时间格式:yyyy-mm-dd:... 47 | n8="20180201"#开始时间 48 | print ("手动设定选股开始时间格式n8",n8) 49 | n9="20180201"#结束时间 50 | print ("手动设定选股结束时间格式n9",n9) 51 | n10="20160101"#设定起始时间 52 | print ("手动设定数据更新设定起始时间格式n10",n10) 53 | x1="000001.XSHG" 54 | x2="603377.XSHG" 55 | print ("设定股票代码",x1,x2) 56 | 57 | 58 | # In[4]: 59 | 60 | 61 | from funcat.data.tushare_backend import TushareDataBackend 62 | from funcat.data.rqalpha_data_backend import RQAlphaDataBackend 63 | 64 | backend = "rqalpha" 65 | 66 | if backend == "rqalpha": 67 | set_data_backend(RQAlphaDataBackend("~/.rqalpha/bundle")) 68 | elif backend == "tushare": 69 | set_data_backend(TushareDataBackend()) 70 | 71 | set_start_date(n10) 72 | S(x1) # 设置当前关注股票 73 | T(n9) # 设置当前观察日期 74 | 75 | 76 | # In[5]: 77 | 78 | 79 | #import RQAlpha update_bundle 80 | 81 | 82 | # In[6]: 83 | 84 | 85 | print ("打印 开盘 最高 最低 收盘 成交量",O, H, L, C, V) # 打印 Open High Low Close 86 | print ("当天涨幅",C / C[1] - 1) # 当天涨幅 87 | print ("打印60日均线",MA(C, 60)) # 打印60日均线 88 | print ("判断收盘价是否大于60日均线",C > MA(C, 60)) # 判断收盘价是否大于60日均线 89 | print ("30日最高价",HHV(H, 30)) # 30日最高价 90 | print ("最近30日,收盘价 Close 大于60日均线的天数",COUNT(C > MA(C, 60), 30)) # 最近30日,收盘价 Close 大于60日均线的天数 91 | print ("10日均线上穿",CROSS(MA(C, 10), MA(C, 20))) # 10日均线上穿 92 | print ("最近10天收阳线的天数",COUNT(C > O, 10)) # 最近10天收阳线的天数 93 | print ("最近60天K线实体的最高价",HHV(MAX(O, C), 60)) # 最近60天K线实体的最高价 94 | print ("5日均线上穿10日均线",CROSS(MA(C, 5), MA(C, 10))) # 5日均线上穿10日均线 95 | 96 | 97 | # In[7]: 98 | 99 | 100 | #0x02 均线金叉死叉 101 | ax = plt.subplot() 102 | ma1 = MA(L,1) 103 | ma3 = MA(H,3) 104 | ma5 = MA(H,5) 105 | ma7 = MA(H,7) 106 | ma11 = MA(H,11) 107 | ma22 = MA(H,22) 108 | ma66 = MA(H,66) 109 | buy_signal = CROSS(ma1, ma7) 110 | sell_signal = CROSS(ma7, ma1) 111 | plt.plot(C.series, label="H", linewidth=2) 112 | plt.plot(ma1.series, label="ma1", alpha=0.7) 113 | plt.plot(ma3.series, label="ma3", alpha=0.7) 114 | plt.plot(ma5.series, label="ma5", alpha=0.7) 115 | plt.plot(ma7.series, label="ma7", alpha=0.7) 116 | plt.plot(ma11.series, label="ma11", alpha=0.7) 117 | plt.plot(ma22.series, label="ma22", alpha=0.7) 118 | plt.plot(ma66.series, label="ma66", alpha=0.7) 119 | plt.plot(np.where(buy_signal.series)[0], C.series[np.where(buy_signal.series)[0]], "^", label="buy", markersize=12, color="red") 120 | plt.plot(np.where(sell_signal.series)[0], C.series[np.where(sell_signal.series)[0]], "v", label="sell", markersize=12, color="green") 121 | plt.legend(loc="best") 122 | plt.show() 123 | 124 | 125 | # In[8]: 126 | 127 | 128 | N, M1, M2 = 27, 9, 3 129 | RSV = (CLOSE - LLV(LOW, N)) / (HHV(HIGH, N) - LLV(LOW, N)) * 100 130 | K = EMA(RSV, (M1 * 2 - 1)) 131 | D = EMA(K, (M2 * 2 - 1)) 132 | J = K * 3 - D * 2 133 | print(K, D, J) 134 | f, (ax1, ax2,) = plt.subplots(2, 1) 135 | ax1.plot(L.series, label="L") 136 | ax1.plot(MA(L, 7).series, label="ma7") 137 | ax1.plot(MA(H, 11).series, label="ma11") 138 | ax1.plot(MA(H, 22).series, label="ma22") 139 | ax1.plot(MA(H, 66).series, label="ma66") 140 | ax1.set_xlim(22) 141 | ax2.plot(K.series, label="K", linewidth=2) 142 | ax2.plot(D.series, label="D", alpha=0.7) 143 | ax2.plot(J.series, label="J", alpha=0.7) 144 | ax2.set_xlim(22) 145 | buy_signal = CROSS(J, K) 146 | sell_signal = CROSS(K, J) 147 | plt.plot(np.where(buy_signal.series)[0], K.series[np.where(buy_signal.series)[0]], "^", label="buy", markersize=12, color="red") 148 | plt.plot(np.where(sell_signal.series)[0], J.series[np.where(sell_signal.series)[0]], "v", label="sell", markersize=12, color="green") 149 | plt.legend(loc="best") 150 | plt.show() 151 | 152 | 153 | # In[9]: 154 | 155 | 156 | #0x03 DMA指标(Different of Moving Average)DMA指标(Different of Moving Average) 157 | #又叫平行线差指标,是目前股市分析技术指标中的一种中短期指标,它常用于大盘指数和个股的研判。 158 | M1 = 10 159 | M2 = 50 160 | M3 = 10 161 | DDD = MA(CLOSE, M1) - MA(CLOSE, M2) 162 | AMA = MA(DDD, M3) 163 | print(DDD, AMA) 164 | f, (ax1, ax2) = plt.subplots(2, 1) 165 | ax1.plot(L.series, label="L") 166 | ax1.plot(MA(L, 7).series, label="ma7") 167 | ax1.plot(MA(H, 11).series, label="ma11") 168 | ax1.plot(MA(H, 22).series, label="ma22") 169 | ax1.plot(MA(H, 66).series, label="ma66") 170 | ax1.set_xlim(22) 171 | ax2.plot(DDD.series, label="DDD") 172 | ax2.plot(AMA.series, label="AMA") 173 | ax2.set_xlim(22) 174 | buy_signal = CROSS(DDD, AMA) 175 | sell_signal = CROSS(AMA, DDD) 176 | plt.plot(np.where(buy_signal.series)[0], AMA.series[np.where(buy_signal.series)[0]], "^", label="buy", markersize=12, color="red") 177 | plt.plot(np.where(sell_signal.series)[0], DDD.series[np.where(sell_signal.series)[0]], "v", label="sell", markersize=12, color="green") 178 | plt.legend(loc="best") 179 | plt.show() 180 | 181 | 182 | # In[ ]: 183 | 184 | 185 | 186 | 187 | 188 | # In[10]: 189 | 190 | 191 | # 选出涨停股 192 | select( 193 | lambda : C / C[1] - 1 >= 0.0995, 194 | start_date=(n8), 195 | end_date=(n9), 196 | ) 197 | 198 | 199 | # In[11]: 200 | 201 | 202 | # 选出最近30天K线实体最高价最低价差7%以内,最近100天K线实体最高价最低价差25%以内, 203 | # 最近10天,收盘价大于60日均线的天数大于3天 204 | select( 205 | lambda : ((HHV(MAX(C, O), 30) / LLV(MIN(C, O), 30) - 1 < 0.07) 206 | & (HHV(MAX(C, O), 100) / LLV(MIN(C, O), 100) - 1 > 0.25) 207 | & (COUNT(C > MA(C, 60), 10) > 3) 208 | ), 209 | start_date=(n8), 210 | end_date=(n9), 211 | ) 212 | 213 | 214 | # In[12]: 215 | 216 | 217 | # 选出最近3天每天的成交量小于20日成交量均线,最近3天最低价低于20日均线,最高价高于20日均线 218 | # 自定义选股回调函数 219 | def callback(date, order_book_id, symbol): 220 | print("Cool, 在", date, "选出", order_book_id, symbol) 221 | 222 | 223 | select( 224 | lambda : (EVERY(V < MA(V, 20) / 2, 3) & EVERY(L < MA(C, 20), 3) & EVERY(H > MA(C, 20), 3)), 225 | start_date=(n8), 226 | end_date=(n9), 227 | callback=callback, 228 | ) 229 | 230 | 231 | # In[ ]: 232 | 233 | 234 | 235 | 236 | 237 | # In[ ]: 238 | 239 | 240 | 241 | 242 | -------------------------------------------------------------------------------- /rqalpha量化/实例/ths-tushare.py: -------------------------------------------------------------------------------- 1 | 2 | # coding: utf-8 3 | 4 | # In[1]: 5 | 6 | 7 | from matplotlib import rcParams 8 | import matplotlib.pyplot as plt 9 | import numpy as np 10 | 11 | np.seterr(all='ignore') 12 | rcParams['figure.figsize'] = (14, 6) 13 | 14 | 15 | # In[2]: 16 | 17 | 18 | from funcat import * 19 | from pytdx import * 20 | from tushare import * 21 | from rqalpha import * 22 | 23 | 24 | # In[3]: 25 | 26 | 27 | import time 28 | import datetime 29 | n1 = (time.strftime("20%y-%m-%d"))## 20yy-mm-dd格式,输出当日日期 30 | n2 = (time.strftime("20%y%m%d"))## 20yymmdd格式,输出当日日期 31 | #print (time.strftime("20%y-%m-%d")) ## dd/mm/yyyy格式,输出当日日期 32 | #print (time.strftime("20%y%m%d")) 33 | def getYesterday(): 34 | today=datetime.date.today() 35 | oneday=datetime.timedelta(days=1) 36 | yesterday=today-oneday 37 | return yesterday 38 | n3 = (getYesterday())# 输出前一天日期 39 | i = datetime.datetime.now()#当前日期 40 | n4 = ("%s%s%s" % (i.year, i.month, i.day) ) 41 | n5 = ("%s" % i.isoformat() ) 42 | print ("读取当日时间格式n1",n1) #当日时间格式:yyyy-mm-dd 43 | print ("读取当日时间格式n2",n2) #当日时间格式:yyyymmdd 44 | print ("读取前一日时间格式n3",n3) #前日时间格式:yyyy-mm-dd 45 | print ("读取当日时间格式n4",n4) #当日时间格式:yyyymmdd 46 | print ("读取当日时间格式n5",n5) #当日时间格式:yyyy-mm-dd:... 47 | n8="20180201"#开始时间 48 | print ("手动设定选股开始时间格式n8",n8) 49 | n9="20180201"#结束时间 50 | print ("手动设定选股结束时间格式n9",n9) 51 | n10="20160101"#设定起始时间 52 | print ("手动设定数据更新设定起始时间格式n10",n10) 53 | x1="000001.XSHG" 54 | x2="603377.XSHG" 55 | print ("设定股票代码",x1,x2) 56 | 57 | 58 | # In[4]: 59 | 60 | 61 | from funcat.data.tushare_backend import TushareDataBackend 62 | from funcat.data.rqalpha_data_backend import RQAlphaDataBackend 63 | 64 | backend = "tushare" 65 | 66 | if backend == "rqalpha": 67 | set_data_backend(RQAlphaDataBackend("~/.rqalpha/bundle")) 68 | elif backend == "tushare": 69 | set_data_backend(TushareDataBackend()) 70 | 71 | set_start_date(n10) 72 | S(x1) # 设置当前关注股票 73 | T(n9) # 设置当前观察日期 74 | 75 | 76 | # In[5]: 77 | 78 | 79 | #import RQAlpha update_bundle 80 | 81 | 82 | # In[6]: 83 | 84 | 85 | print ("打印 开盘 最高 最低 收盘 成交量",O, H, L, C, V) # 打印 Open High Low Close 86 | print ("当天涨幅",C / C[1] - 1) # 当天涨幅 87 | print ("打印60日均线",MA(C, 60)) # 打印60日均线 88 | print ("判断收盘价是否大于60日均线",C > MA(C, 60)) # 判断收盘价是否大于60日均线 89 | print ("30日最高价",HHV(H, 30)) # 30日最高价 90 | print ("最近30日,收盘价 Close 大于60日均线的天数",COUNT(C > MA(C, 60), 30)) # 最近30日,收盘价 Close 大于60日均线的天数 91 | print ("10日均线上穿",CROSS(MA(C, 10), MA(C, 20))) # 10日均线上穿 92 | print ("最近10天收阳线的天数",COUNT(C > O, 10)) # 最近10天收阳线的天数 93 | print ("最近60天K线实体的最高价",HHV(MAX(O, C), 60)) # 最近60天K线实体的最高价 94 | print ("5日均线上穿10日均线",CROSS(MA(C, 5), MA(C, 10))) # 5日均线上穿10日均线 95 | 96 | 97 | # In[7]: 98 | 99 | 100 | #0x02 均线金叉死叉 101 | ax = plt.subplot() 102 | ma1 = MA(L,1) 103 | ma3 = MA(H,3) 104 | ma5 = MA(H,5) 105 | ma7 = MA(H,7) 106 | ma11 = MA(H,11) 107 | ma22 = MA(H,22) 108 | ma66 = MA(H,66) 109 | buy_signal = CROSS(ma1, ma7) 110 | sell_signal = CROSS(ma7, ma1) 111 | plt.plot(C.series, label="H", linewidth=2) 112 | plt.plot(ma1.series, label="ma1", alpha=0.7) 113 | plt.plot(ma3.series, label="ma3", alpha=0.7) 114 | plt.plot(ma5.series, label="ma5", alpha=0.7) 115 | plt.plot(ma7.series, label="ma7", alpha=0.7) 116 | plt.plot(ma11.series, label="ma11", alpha=0.7) 117 | plt.plot(ma22.series, label="ma22", alpha=0.7) 118 | plt.plot(ma66.series, label="ma66", alpha=0.7) 119 | plt.plot(np.where(buy_signal.series)[0], C.series[np.where(buy_signal.series)[0]], "^", label="buy", markersize=12, color="red") 120 | plt.plot(np.where(sell_signal.series)[0], C.series[np.where(sell_signal.series)[0]], "v", label="sell", markersize=12, color="green") 121 | plt.legend(loc="best") 122 | plt.show() 123 | 124 | 125 | # In[8]: 126 | 127 | 128 | N, M1, M2 = 27, 9, 3 129 | RSV = (CLOSE - LLV(LOW, N)) / (HHV(HIGH, N) - LLV(LOW, N)) * 100 130 | K = EMA(RSV, (M1 * 2 - 1)) 131 | D = EMA(K, (M2 * 2 - 1)) 132 | J = K * 3 - D * 2 133 | print(K, D, J) 134 | f, (ax1, ax2,) = plt.subplots(2, 1) 135 | ax1.plot(L.series, label="L") 136 | ax1.plot(MA(L, 7).series, label="ma7") 137 | ax1.plot(MA(H, 11).series, label="ma11") 138 | ax1.plot(MA(H, 22).series, label="ma22") 139 | ax1.plot(MA(H, 66).series, label="ma66") 140 | ax1.set_xlim(22) 141 | ax2.plot(K.series, label="K", linewidth=2) 142 | ax2.plot(D.series, label="D", alpha=0.7) 143 | ax2.plot(J.series, label="J", alpha=0.7) 144 | ax2.set_xlim(22) 145 | buy_signal = CROSS(J, K) 146 | sell_signal = CROSS(K, J) 147 | plt.plot(np.where(buy_signal.series)[0], K.series[np.where(buy_signal.series)[0]], "^", label="buy", markersize=12, color="red") 148 | plt.plot(np.where(sell_signal.series)[0], J.series[np.where(sell_signal.series)[0]], "v", label="sell", markersize=12, color="green") 149 | plt.legend(loc="best") 150 | plt.show() 151 | 152 | 153 | # In[ ]: 154 | 155 | 156 | #0x03 DMA指标(Different of Moving Average)DMA指标(Different of Moving Average) 157 | #又叫平行线差指标,是目前股市分析技术指标中的一种中短期指标,它常用于大盘指数和个股的研判。 158 | M1 = 10 159 | M2 = 50 160 | M3 = 10 161 | DDD = MA(CLOSE, M1) - MA(CLOSE, M2) 162 | AMA = MA(DDD, M3) 163 | print(DDD, AMA) 164 | f, (ax1, ax2) = plt.subplots(2, 1) 165 | ax1.plot(L.series, label="L") 166 | ax1.plot(MA(L, 7).series, label="ma7") 167 | ax1.plot(MA(H, 11).series, label="ma11") 168 | ax1.plot(MA(H, 22).series, label="ma22") 169 | ax1.plot(MA(H, 66).series, label="ma66") 170 | ax1.set_xlim(22) 171 | ax2.plot(DDD.series, label="DDD") 172 | ax2.plot(AMA.series, label="AMA") 173 | ax2.set_xlim(22) 174 | buy_signal = CROSS(DDD, AMA) 175 | sell_signal = CROSS(AMA, DDD) 176 | plt.plot(np.where(buy_signal.series)[0], AMA.series[np.where(buy_signal.series)[0]], "^", label="buy", markersize=12, color="red") 177 | plt.plot(np.where(sell_signal.series)[0], DDD.series[np.where(sell_signal.series)[0]], "v", label="sell", markersize=12, color="green") 178 | plt.legend(loc="best") 179 | plt.show() 180 | 181 | 182 | # In[ ]: 183 | 184 | 185 | 186 | 187 | 188 | # In[ ]: 189 | 190 | 191 | # 选出涨停股 192 | select( 193 | lambda : C / C[1] - 1 >= 0.0995, 194 | start_date=(n8), 195 | end_date=(n9), 196 | ) 197 | 198 | 199 | # In[ ]: 200 | 201 | 202 | # 选出最近30天K线实体最高价最低价差7%以内,最近100天K线实体最高价最低价差25%以内, 203 | # 最近10天,收盘价大于60日均线的天数大于3天 204 | select( 205 | lambda : ((HHV(MAX(C, O), 30) / LLV(MIN(C, O), 30) - 1 < 0.07) 206 | & (HHV(MAX(C, O), 100) / LLV(MIN(C, O), 100) - 1 > 0.25) 207 | & (COUNT(C > MA(C, 60), 10) > 3) 208 | ), 209 | start_date=(n8), 210 | end_date=(n9), 211 | ) 212 | 213 | 214 | # In[ ]: 215 | 216 | 217 | # 选出最近3天每天的成交量小于20日成交量均线,最近3天最低价低于20日均线,最高价高于20日均线 218 | # 自定义选股回调函数 219 | def callback(date, order_book_id, symbol): 220 | print("Cool, 在", date, "选出", order_book_id, symbol) 221 | 222 | 223 | select( 224 | lambda : (EVERY(V < MA(V, 20) / 2, 3) & EVERY(L < MA(C, 20), 3) & EVERY(H > MA(C, 20), 3)), 225 | start_date=(n8), 226 | end_date=(n9), 227 | callback=callback, 228 | ) 229 | 230 | 231 | # In[ ]: 232 | 233 | 234 | 235 | 236 | 237 | # In[ ]: 238 | 239 | 240 | 241 | 242 | -------------------------------------------------------------------------------- /rqalpha量化/实例/ths.py: -------------------------------------------------------------------------------- 1 | 2 | # coding: utf-8 3 | 4 | # In[1]: 5 | 6 | 7 | from matplotlib import rcParams 8 | import matplotlib.pyplot as plt 9 | import numpy as np 10 | 11 | np.seterr(all='ignore') 12 | rcParams['figure.figsize'] = (14, 6) 13 | 14 | 15 | # In[ ]: 16 | 17 | 18 | from funcat import * 19 | from pytdx import * 20 | from tushare import * 21 | from rqalpha import * 22 | #from jaqs import * 23 | #from abupy import * 24 | #from quantaxis import * 25 | #from hikyuu import * 26 | 27 | 28 | # In[ ]: 29 | 30 | 31 | import time 32 | import datetime 33 | n1 = (time.strftime("20%y-%m-%d"))## 20yy-mm-dd格式,输出当日日期 34 | n2 = (time.strftime("20%y%m%d"))## 20yymmdd格式,输出当日日期 35 | #print (time.strftime("20%y-%m-%d")) ## dd/mm/yyyy格式,输出当日日期 36 | #print (time.strftime("20%y%m%d")) 37 | def getYesterday(): 38 | today=datetime.date.today() 39 | oneday=datetime.timedelta(days=1) 40 | yesterday=today-oneday 41 | return yesterday 42 | n3 = (getYesterday())# 输出前一天日期 43 | i = datetime.datetime.now()#当前日期 44 | n4 = ("%s%s%s" % (i.year, i.month, i.day) ) 45 | n5 = ("%s" % i.isoformat() ) 46 | print ("读取当日时间格式n1",n1) #当日时间格式:yyyy-mm-dd 47 | print ("读取当日时间格式n2",n2) #当日时间格式:yyyymmdd 48 | print ("读取前一日时间格式n3",n3) #前日时间格式:yyyy-mm-dd 49 | print ("读取当日时间格式n4",n4) #当日时间格式:yyyymmdd 50 | print ("读取当日时间格式n5",n5) #当日时间格式:yyyy-mm-dd:... 51 | n8="20180201"#开始时间 52 | print ("手动设定选股开始时间格式n8",n8) 53 | n9="20180201"#结束时间 54 | print ("手动设定选股结束时间格式n9",n9) 55 | n10="20160101"#设定起始时间 56 | print ("手动设定数据更新设定起始时间格式n10",n10) 57 | x1="000001.XSHG" 58 | x2="603377.XSHG" 59 | print ("设定股票代码",x1,x2) 60 | 61 | 62 | # In[4]: 63 | 64 | 65 | from funcat.data.tushare_backend import TushareDataBackend 66 | from funcat.data.rqalpha_data_backend import RQAlphaDataBackend 67 | 68 | backend = "tushare" 69 | 70 | if backend == "rqalpha": 71 | set_data_backend(RQAlphaDataBackend("~/.rqalpha/bundle")) 72 | elif backend == "tushare": 73 | set_data_backend(TushareDataBackend()) 74 | 75 | set_start_date(n10) 76 | S(x1) # 设置当前关注股票 77 | T(n9) # 设置当前观察日期 78 | 79 | 80 | # In[5]: 81 | 82 | 83 | #import RQAlpha update_bundle 84 | 85 | 86 | # In[6]: 87 | 88 | 89 | print ("打印 开盘 最高 最低 收盘 成交量",O, H, L, C, V) # 打印 Open High Low Close 90 | print ("当天涨幅",C / C[1] - 1) # 当天涨幅 91 | print ("打印60日均线",MA(C, 60)) # 打印60日均线 92 | print ("判断收盘价是否大于60日均线",C > MA(C, 60)) # 判断收盘价是否大于60日均线 93 | print ("30日最高价",HHV(H, 30)) # 30日最高价 94 | print ("最近30日,收盘价 Close 大于60日均线的天数",COUNT(C > MA(C, 60), 30)) # 最近30日,收盘价 Close 大于60日均线的天数 95 | print ("10日均线上穿",CROSS(MA(C, 10), MA(C, 20))) # 10日均线上穿 96 | print ("最近10天收阳线的天数",COUNT(C > O, 10)) # 最近10天收阳线的天数 97 | print ("最近60天K线实体的最高价",HHV(MAX(O, C), 60)) # 最近60天K线实体的最高价 98 | print ("5日均线上穿10日均线",CROSS(MA(C, 5), MA(C, 10))) # 5日均线上穿10日均线 99 | 100 | 101 | # In[7]: 102 | 103 | 104 | #0x02 均线金叉死叉 105 | ax = plt.subplot() 106 | ma1 = MA(L,1) 107 | ma3 = MA(H,3) 108 | ma5 = MA(H,5) 109 | ma7 = MA(H,7) 110 | ma11 = MA(H,11) 111 | ma22 = MA(H,22) 112 | ma66 = MA(H,66) 113 | buy_signal = CROSS(ma1, ma7) 114 | sell_signal = CROSS(ma7, ma1) 115 | plt.plot(C.series, label="H", linewidth=2) 116 | plt.plot(ma1.series, label="ma1", alpha=0.7) 117 | plt.plot(ma3.series, label="ma3", alpha=0.7) 118 | plt.plot(ma5.series, label="ma5", alpha=0.7) 119 | plt.plot(ma7.series, label="ma7", alpha=0.7) 120 | plt.plot(ma11.series, label="ma11", alpha=0.7) 121 | plt.plot(ma22.series, label="ma22", alpha=0.7) 122 | plt.plot(ma66.series, label="ma66", alpha=0.7) 123 | plt.plot(np.where(buy_signal.series)[0], C.series[np.where(buy_signal.series)[0]], "^", label="buy", markersize=12, color="red") 124 | plt.plot(np.where(sell_signal.series)[0], C.series[np.where(sell_signal.series)[0]], "v", label="sell", markersize=12, color="green") 125 | plt.legend(loc="best") 126 | plt.show() 127 | 128 | 129 | # In[8]: 130 | 131 | 132 | N, M1, M2 = 27, 9, 3 133 | RSV = (CLOSE - LLV(LOW, N)) / (HHV(HIGH, N) - LLV(LOW, N)) * 100 134 | K = EMA(RSV, (M1 * 2 - 1)) 135 | D = EMA(K, (M2 * 2 - 1)) 136 | J = K * 3 - D * 2 137 | print(K, D, J) 138 | f, (ax1, ax2,) = plt.subplots(2, 1) 139 | ax1.plot(L.series, label="L") 140 | ax1.plot(MA(L, 7).series, label="ma7") 141 | ax1.plot(MA(H, 11).series, label="ma11") 142 | ax1.plot(MA(H, 22).series, label="ma22") 143 | ax1.plot(MA(H, 66).series, label="ma66") 144 | ax1.set_xlim(22) 145 | ax2.plot(K.series, label="K", linewidth=2) 146 | ax2.plot(D.series, label="D", alpha=0.7) 147 | ax2.plot(J.series, label="J", alpha=0.7) 148 | ax2.set_xlim(22) 149 | buy_signal = CROSS(J, K) 150 | sell_signal = CROSS(K, J) 151 | plt.plot(np.where(buy_signal.series)[0], K.series[np.where(buy_signal.series)[0]], "^", label="buy", markersize=12, color="red") 152 | plt.plot(np.where(sell_signal.series)[0], J.series[np.where(sell_signal.series)[0]], "v", label="sell", markersize=12, color="green") 153 | plt.legend(loc="best") 154 | plt.show() 155 | 156 | 157 | # In[ ]: 158 | 159 | 160 | #0x03 DMA指标(Different of Moving Average)DMA指标(Different of Moving Average) 161 | #又叫平行线差指标,是目前股市分析技术指标中的一种中短期指标,它常用于大盘指数和个股的研判。 162 | M1 = 10 163 | M2 = 50 164 | M3 = 10 165 | DDD = MA(CLOSE, M1) - MA(CLOSE, M2) 166 | AMA = MA(DDD, M3) 167 | print(DDD, AMA) 168 | f, (ax1, ax2) = plt.subplots(2, 1) 169 | ax1.plot(L.series, label="L") 170 | ax1.plot(MA(L, 7).series, label="ma7") 171 | ax1.plot(MA(H, 11).series, label="ma11") 172 | ax1.plot(MA(H, 22).series, label="ma22") 173 | ax1.plot(MA(H, 66).series, label="ma66") 174 | ax1.set_xlim(22) 175 | ax2.plot(DDD.series, label="DDD") 176 | ax2.plot(AMA.series, label="AMA") 177 | ax2.set_xlim(22) 178 | buy_signal = CROSS(DDD, AMA) 179 | sell_signal = CROSS(AMA, DDD) 180 | plt.plot(np.where(buy_signal.series)[0], AMA.series[np.where(buy_signal.series)[0]], "^", label="buy", markersize=12, color="red") 181 | plt.plot(np.where(sell_signal.series)[0], DDD.series[np.where(sell_signal.series)[0]], "v", label="sell", markersize=12, color="green") 182 | plt.legend(loc="best") 183 | plt.show() 184 | 185 | 186 | # In[ ]: 187 | 188 | 189 | 190 | 191 | 192 | # In[ ]: 193 | 194 | 195 | # 选出涨停股 196 | select( 197 | lambda : C / C[1] - 1 >= 0.0995, 198 | start_date=(n8), 199 | end_date=(n9), 200 | ) 201 | 202 | 203 | # In[ ]: 204 | 205 | 206 | # 选出最近30天K线实体最高价最低价差7%以内,最近100天K线实体最高价最低价差25%以内, 207 | # 最近10天,收盘价大于60日均线的天数大于3天 208 | select( 209 | lambda : ((HHV(MAX(C, O), 30) / LLV(MIN(C, O), 30) - 1 < 0.07) 210 | & (HHV(MAX(C, O), 100) / LLV(MIN(C, O), 100) - 1 > 0.25) 211 | & (COUNT(C > MA(C, 60), 10) > 3) 212 | ), 213 | start_date=(n8), 214 | end_date=(n9), 215 | ) 216 | 217 | 218 | # In[ ]: 219 | 220 | 221 | # 选出最近3天每天的成交量小于20日成交量均线,最近3天最低价低于20日均线,最高价高于20日均线 222 | # 自定义选股回调函数 223 | def callback(date, order_book_id, symbol): 224 | print("Cool, 在", date, "选出", order_book_id, symbol) 225 | 226 | 227 | select( 228 | lambda : (EVERY(V < MA(V, 20) / 2, 3) & EVERY(L < MA(C, 20), 3) & EVERY(H > MA(C, 20), 3)), 229 | start_date=(n8), 230 | end_date=(n9), 231 | callback=callback, 232 | ) 233 | 234 | 235 | # In[ ]: 236 | 237 | 238 | 239 | 240 | 241 | # In[ ]: 242 | 243 | 244 | 245 | 246 | -------------------------------------------------------------------------------- /rqalpha量化/实例/zt.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | from matplotlib import rcParams 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | np.seterr(all='ignore') 6 | rcParams['figure.figsize'] = (14, 6) 7 | from funcat import * #FUNCAT的同花顺/通达信指标模块:和:&,或:|,其他基本相同。可以使用指标选股!!! 8 | from tushare import * #TUSHARE数据连接更新。 9 | from rqalpha import * #RQALPHA本地数据连接,通过 rqalpha update_bundle 8点后更新全部数据库 10 | from funcat.data.tushare_backend import TushareDataBackend 11 | from funcat.data.rqalpha_data_backend import RQAlphaDataBackend 12 | backend = "rqalpha" 13 | if backend == "rqalpha": 14 | set_data_backend(RQAlphaDataBackend("~/.rqalpha/bundle")) 15 | elif backend == "tushare": 16 | set_data_backend(TushareDataBackend()) 17 | set_start_date(20170101) 18 | #S("000001.XSHG") # 设置当前关注股票 19 | #T("20080202") # 设置当前观察日期 20 | 21 | def callback(date, order_book_id,symbol): 22 | print(date,order_book_id,symbol) 23 | select( 24 | lambda : O / H[1] - 1 >= 0.0995, 25 | start_date=("20180205"), 26 | end_date=("20180206"), 27 | callback=callback, 28 | ) 29 | 30 | -------------------------------------------------------------------------------- /rqalpha量化/选股/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/rqalpha量化/选股/.DS_Store -------------------------------------------------------------------------------- /rqalpha量化/选股/CCI选股TU.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "读取当日时间格式n1 2018-11-22\n", 13 | "读取当日时间格式n2 20181122\n", 14 | "读取前一日时间格式n3 2018-11-21\n", 15 | "读取当日时间格式n4 20181122\n", 16 | "读取当日时间格式n5 2018-11-22T18:48:02.952736\n", 17 | "手动设定选股开始时间格式n8 20180202\n", 18 | "手动设定选股结束时间格式n9 20180202\n", 19 | "手动设定数据更新设定起始时间格式n10 20170101\n", 20 | "设定股票代码 000001.XSHG\n", 21 | "打印 开盘 最高 最低 收盘 成交量 2619.82 2653.8 2617.78 2651.51 182596447.0\n", 22 | "当天涨幅 0.002139199123155189\n", 23 | "打印60日均线 2671.3789999999985\n", 24 | "判断收盘价是否大于60日均线 False\n", 25 | "30日最高价 2703.51\n", 26 | "最近30日,收盘价 Close 大于60日均线的天数 2\n", 27 | "10日均线上穿 False\n", 28 | "最近10天收阳线的天数 6\n", 29 | "最近60天K线实体的最高价 2821.35\n", 30 | "5日均线上穿10日均线 False\n", 31 | "《RQALPHA本地化开始CCI选股》读取开始时间:==》n5 2018-11-22T18:48:02.952736\n", 32 | "lambda : CROSS(((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14))) or ((((((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14)))+((V-MA(V,14))/(0.015*AVEDEV(V,14))))-MA((((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14)))+((V-MA(V,14))/(0.015*AVEDEV(V,14)))),14))/(0.015*AVEDEV((((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14)))+((V-MA(V,14))/(0.015*AVEDEV(V,14)))),14))))\n", 33 | "\n", 34 | ",101 or -101),\n", 35 | "[20181122]\n" 36 | ] 37 | } 38 | ], 39 | "source": [ 40 | "from matplotlib import rcParams\n", 41 | "import matplotlib.pyplot as plt\n", 42 | "import numpy as np\n", 43 | "\n", 44 | "np.seterr(all='ignore')\n", 45 | "rcParams['figure.figsize'] = (14, 6)\n", 46 | "\n", 47 | "#扩展MOD\n", 48 | "from funcat import * #FUNCAT的同花顺/通达信指标模块:和:&,或:|,其他基本相同。可以使用指标选股!!!\n", 49 | "#from pytdx import * #通达信数据更新模块到QUANTAXIS的mongoDB\n", 50 | "from tushare import * #TUSHARE数据连接更新。\n", 51 | "from rqalpha import * #RQALPHA本地数据连接,通过 rqalpha update_bundle 8点后更新全部数据库\n", 52 | "#from jaqs import * #QunatOS的jaqs客户端在线。\n", 53 | "#from abupy import * #ABUPY本地化,数据在线下载更新,数据在线下载在根目录abu下\n", 54 | "#from quantaxis import * #加载QUANTAXIS数据库模块,首先需要开启mongoDB+web服务器,数据更新通过通达信服务器。\n", 55 | "#from hikyuu import * #HIKYUU本地化,数据库在根目录的stock。通过通达信导入。\n", 56 | "\n", 57 | "#读取/设定数据库时间区域,当前股票,选股时间段。 \n", 58 | "import time\n", 59 | "import datetime\n", 60 | "n1 = (time.strftime(\"20%y-%m-%d\"))## 20yy-mm-dd格式,输出当日日期\n", 61 | "print (\"读取当日时间格式n1\",n1) #当日时间格式:yyyy-mm-dd\n", 62 | "n2 = (time.strftime(\"20%y%m%d\"))## 20yymmdd格式,输出当日日期\n", 63 | "print (\"读取当日时间格式n2\",n2) #当日时间格式:yyyymmdd\n", 64 | "def getYesterday(): \n", 65 | " today=datetime.date.today() \n", 66 | " oneday=datetime.timedelta(days=1) \n", 67 | " yesterday=today-oneday \n", 68 | " return yesterday\n", 69 | "n3 = (getYesterday())# 输出前一天日期\n", 70 | "print (\"读取前一日时间格式n3\",n3) #前日时间格式:yyyy-mm-dd\n", 71 | "i = datetime.datetime.now()#当前日期\n", 72 | "n4 = (\"%s%s%s\" % (i.year, i.month, i.day) )\n", 73 | "print (\"读取当日时间格式n4\",n4) #当日时间格式:yyyymmdd\n", 74 | "n5 = (\"%s\" % i.isoformat() )\n", 75 | "print (\"读取当日时间格式n5\",n5) #当日时间格式:yyyy-mm-dd:...\n", 76 | "n8=\"20180202\"#开始时间\n", 77 | "\n", 78 | "print (\"手动设定选股开始时间格式n8\",n8)\n", 79 | "n9=\"20180202\"#结束时间\n", 80 | "\n", 81 | "print (\"手动设定选股结束时间格式n9\",n9)\n", 82 | "n10=\"20170101\"#设定起始时间\n", 83 | "\n", 84 | "print (\"手动设定数据更新设定起始时间格式n10\",n10)\n", 85 | "x1=\"000001.XSHG\"\n", 86 | "print (\"设定股票代码\",x1)\n", 87 | "\n", 88 | "#设定数据库连接:RQALPHA/TUSHARE\n", 89 | "from funcat.data.tushare_backend import TushareDataBackend\n", 90 | "from funcat.data.rqalpha_data_backend import RQAlphaDataBackend\n", 91 | "backend = \"tushare\"\n", 92 | "if backend == \"rqalpha\":\n", 93 | " set_data_backend(RQAlphaDataBackend(\"~/.rqalpha/bundle\"))\n", 94 | "elif backend == \"tushare\":\n", 95 | " set_data_backend(TushareDataBackend())\n", 96 | "set_start_date(n10)\n", 97 | "\n", 98 | "#当前股票最新数据显示。\n", 99 | "S(x1) # 设置当前关注股票\n", 100 | "T(n3) # 设置当前观察日期\n", 101 | "\n", 102 | "print (\"打印 开盘 最高 最低 收盘 成交量\",O, H, L, C, V) # 打印 Open High Low Close\n", 103 | "print (\"当天涨幅\",C / C[1] - 1) # 当天涨幅\n", 104 | "print (\"打印60日均线\",MA(C, 60)) # 打印60日均线\n", 105 | "print (\"判断收盘价是否大于60日均线\",C > MA(C, 60)) # 判断收盘价是否大于60日均线\n", 106 | "print (\"30日最高价\",HHV(H, 30)) # 30日最高价\n", 107 | "print (\"最近30日,收盘价 Close 大于60日均线的天数\",COUNT(C > MA(C, 60), 30)) # 最近30日,收盘价 Close 大于60日均线的天数\n", 108 | "print (\"10日均线上穿\",CROSS(MA(C, 10), MA(C, 20))) # 10日均线上穿\n", 109 | "print (\"最近10天收阳线的天数\",COUNT(C > O, 10)) # 最近10天收阳线的天数\n", 110 | "print (\"最近60天K线实体的最高价\",HHV(MAX(O, C), 60)) # 最近60天K线实体的最高价\n", 111 | "print (\"5日均线上穿10日均线\",CROSS(MA(C, 5), MA(C, 10))) # 5日均线上穿10日均线\n", 112 | "\n", 113 | "\n", 114 | "#CCI指标 方差函数模块\n", 115 | "def AVEDEV(value,N):\n", 116 | " mean = value/N\n", 117 | " for i in range(1,N):\n", 118 | " mean += REF(value,i)/N\n", 119 | " sum_ = ABS(value-mean)\n", 120 | " for i in range(1,N):\n", 121 | " sum_ += ABS(REF(value,i)-mean)\n", 122 | " \n", 123 | " return sum_/N\n", 124 | "print (\"《RQALPHA本地化开始CCI选股》读取开始时间:==》n5\",n5) \n", 125 | "# 选股CCI OK!!!\n", 126 | "select(\n", 127 | " lambda : CROSS(((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14))) or ((((((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14)))+((V-MA(V,14))/(0.015*AVEDEV(V,14))))-MA((((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14)))+((V-MA(V,14))/(0.015*AVEDEV(V,14)))),14))/(0.015*AVEDEV((((((H+L+C)/3)-MA(((H+L+C)/3),14))/(0.015*AVEDEV(((H+L+C)/3),14)))+((V-MA(V,14))/(0.015*AVEDEV(V,14)))),14))))\n", 128 | "\n", 129 | ",101 or -101),\n", 130 | " start_date=(n3),end_date=(n2),)\n", 131 | "\n", 132 | "\n", 133 | "print (\"《结束选股》读取结束时间:==》n5\",n5) \n" 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "metadata": { 140 | "collapsed": true 141 | }, 142 | "outputs": [], 143 | "source": [] 144 | } 145 | ], 146 | "metadata": { 147 | "kernelspec": { 148 | "display_name": "Python 3", 149 | "language": "python", 150 | "name": "python3" 151 | }, 152 | "language_info": { 153 | "codemirror_mode": { 154 | "name": "ipython", 155 | "version": 3 156 | }, 157 | "file_extension": ".py", 158 | "mimetype": "text/x-python", 159 | "name": "python", 160 | "nbconvert_exporter": "python", 161 | "pygments_lexer": "ipython3", 162 | "version": "3.6.5" 163 | } 164 | }, 165 | "nbformat": 4, 166 | "nbformat_minor": 2 167 | } 168 | -------------------------------------------------------------------------------- /rqalpha量化/选股/KDJ 选股RQ.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 2, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "读取当日时间格式n1 2018-11-22\n", 13 | "读取当日时间格式n2 20181122\n", 14 | "读取前二日时间格式n3 2018-11-21\n", 15 | "读取当日时间格式n4 20181122\n", 16 | "读取当日时间格式n5 2018-11-22T19:52:00.668250\n", 17 | "手动设定选股开始时间格式n8 20180201\n", 18 | "手动设定选股结束时间格式n9 20180209\n", 19 | "手动设定数据更新设定起始时间格式n10 20170101\n", 20 | "设定股票代码 000001.XSHG\n", 21 | "打印 开盘 最高 最低 收盘 成交量 3172.85 3180.11 3062.74 3129.85 25638917600.0\n", 22 | "当天涨幅 -0.04052666268144278\n", 23 | "打印60日均线 3372.0388333333312\n", 24 | "判断收盘价是否大于60日均线 False\n", 25 | "30日最高价 3587.03\n", 26 | "最近30日,收盘价 Close 大于60日均线的天数 24\n", 27 | "10日均线上穿 False\n", 28 | "最近10天收阳线的天数 3\n", 29 | "最近60天K线实体的最高价 3563.64\n", 30 | "5日均线上穿10日均线 False\n", 31 | "《选股》读取时间:==》n5 2018-11-22T19:52:00.668250\n", 32 | "lambda : (CROSS(IF((EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))<50,((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1)))*3-(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))*2)\n", 33 | "\n", 34 | ",(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))),(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))) and CROSS(IF((EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))<50,(EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1)))*3-(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))*2)\n", 35 | "\n", 36 | "),(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))))\n", 37 | "[20181122]\n", 38 | "No data for 000003.XSHE\n", 39 | "No data for 000013.XSHE\n", 40 | "No data for 000015.XSHE\n", 41 | "No data for 000047.XSHE\n", 42 | "20181122 000056.XSHE 皇庭国际\n", 43 | "No data for 000405.XSHE\n", 44 | "No data for 000412.XSHE\n", 45 | "No data for 000508.XSHE\n", 46 | "No data for 000542.XSHE\n", 47 | "No data for 000556.XSHE\n", 48 | "No data for 000588.XSHE\n", 49 | "No data for 000621.XSHE\n", 50 | "No data for 000653.XSHE\n", 51 | "No data for 000658.XSHE\n", 52 | "No data for 000660.XSHE\n", 53 | "No data for 000675.XSHE\n", 54 | "20181122 000688.XSHE 国城矿业\n", 55 | "No data for 000689.XSHE\n", 56 | "No data for 000730.XSHE\n", 57 | "20181122 000893.XSHE *ST东凌\n", 58 | "20181122 002015.XSHE 霞客环保\n", 59 | "20181122 002047.XSHE 宝鹰股份\n", 60 | "20181122 002198.XSHE 嘉应制药\n", 61 | "No data for 002257.XSHE\n", 62 | "20181122 002301.XSHE 齐心集团\n", 63 | "No data for 002525.XSHE\n", 64 | "20181122 002617.XSHE 露笑科技\n", 65 | "No data for 002710.XSHE\n", 66 | "No data for 002720.XSHE\n", 67 | "No data for 002941.XSHE\n", 68 | "No data for 002942.XSHE\n", 69 | "No data for 002943.XSHE\n", 70 | "20181122 300023.XSHE 宝德股份\n", 71 | "20181122 300143.XSHE 星普医科\n", 72 | "No data for 300361.XSHE\n", 73 | "20181122 300420.XSHE 五洋停车\n", 74 | "No data for 300646.XSHE\n", 75 | "No data for 300728.XSHE\n", 76 | "No data for 300752.XSHE\n", 77 | "No data for 600349.XSHG\n", 78 | "No data for 600625.XSHG\n", 79 | "No data for 600632.XSHG\n", 80 | "No data for 600646.XSHG\n", 81 | "No data for 600669.XSHG\n", 82 | "No data for 600670.XSHG\n", 83 | "No data for 600709.XSHG\n", 84 | "20181122 600777.XSHG 新潮能源\n", 85 | "No data for 600813.XSHG\n", 86 | "No data for 600878.XSHG\n", 87 | "No data for 601206.XSHG\n", 88 | "No data for 601860.XSHG\n", 89 | "20181122 601933.XSHG 永辉超市\n", 90 | "20181122 603012.XSHG 创力集团\n", 91 | "No data for 603187.XSHG\n", 92 | "20181122 603196.XSHG 日播时尚\n", 93 | "No data for 603302.XSHG\n", 94 | "[20181121]\n", 95 | "20181121 000526.XSHE 紫光学大\n", 96 | "\n", 97 | "《结束选股》读取结束时间:==》n5 2018-11-22T19:52:00.668250\n" 98 | ] 99 | } 100 | ], 101 | "source": [ 102 | "from matplotlib import rcParams\n", 103 | "import matplotlib.pyplot as plt\n", 104 | "import numpy as np\n", 105 | "\n", 106 | "np.seterr(all='ignore')\n", 107 | "rcParams['figure.figsize'] = (14, 6)\n", 108 | "\n", 109 | "#扩展MOD\n", 110 | "from funcat import * #FUNCAT的同花顺/通达信指标模块:和:&,或:|,其他基本相同。可以使用指标选股!!!\n", 111 | "#from pytdx import * #通达信数据更新模块到QUANTAXIS的mongoDB\n", 112 | "from tushare import * #TUSHARE数据连接更新。\n", 113 | "from rqalpha import * #RQALPHA本地数据连接,通过 rqalpha update_bundle 8点后更新全部数据库\n", 114 | "#from jaqs import * #QunatOS的jaqs客户端在线。\n", 115 | "#from abupy import * #ABUPY本地化,数据在线下载更新,数据在线下载在根目录abu下\n", 116 | "#from quantaxis import * #加载QUANTAXIS数据库模块,首先需要开启mongoDB+web服务器,数据更新通过通达信服务器。\n", 117 | "#from hikyuu import * #HIKYUU本地化,数据库在根目录的stock。通过通达信导入。\n", 118 | "\n", 119 | "#读取/设定数据库时间区域,当前股票,选股时间段。 \n", 120 | "import time\n", 121 | "import datetime\n", 122 | "n1 = (time.strftime(\"20%y-%m-%d\"))## 20yy-mm-dd格式,输出当日日期\n", 123 | "print (\"读取当日时间格式n1\",n1) #当日时间格式:yyyy-mm-dd\n", 124 | "n2 = (time.strftime(\"20%y%m%d\"))## 20yymmdd格式,输出当日日期\n", 125 | "print (\"读取当日时间格式n2\",n2) #当日时间格式:yyyymmdd\n", 126 | "def getYesterday(): \n", 127 | " today=datetime.date.today() \n", 128 | " oneday=datetime.timedelta(days=1) \n", 129 | " yesterday=today-oneday \n", 130 | " return yesterday\n", 131 | "n3 = (getYesterday())# 输出前N天日期\n", 132 | "print (\"读取前二日时间格式n3\",n3) #前日时间格式:yyyy-mm-dd\n", 133 | "i = datetime.datetime.now()#当前日期\n", 134 | "n4 = (\"%s%s%s\" % (i.year, i.month, i.day) )\n", 135 | "print (\"读取当日时间格式n4\",n4) #当日时间格式:yyyymmdd\n", 136 | "n5 = (\"%s\" % i.isoformat() )\n", 137 | "print (\"读取当日时间格式n5\",n5) #当日时间格式:yyyy-mm-dd:...\n", 138 | "\n", 139 | "n8=\"20180201\"#开始时间\n", 140 | "print (\"手动设定选股开始时间格式n8\",n8)\n", 141 | "\n", 142 | "n9=\"20180209\"#结束时间\n", 143 | "print (\"手动设定选股结束时间格式n9\",n9)\n", 144 | "\n", 145 | "n10=\"20170101\"#设定起始时间\n", 146 | "print (\"手动设定数据更新设定起始时间格式n10\",n10)\n", 147 | "x1=\"000001.XSHG\"\n", 148 | "print (\"设定股票代码\",x1)\n", 149 | "\n", 150 | "#设定数据库连接:RQALPHA/TUSHARE\n", 151 | "from funcat.data.tushare_backend import TushareDataBackend\n", 152 | "from funcat.data.rqalpha_data_backend import RQAlphaDataBackend\n", 153 | "backend = \"rqalpha\"\n", 154 | "if backend == \"rqalpha\":\n", 155 | " set_data_backend(RQAlphaDataBackend(\"~/.rqalpha/bundle\"))\n", 156 | "elif backend == \"tushare\":\n", 157 | " set_data_backend(TushareDataBackend())\n", 158 | "set_start_date(n10)\n", 159 | "\n", 160 | "#当前股票最新数据显示。\n", 161 | "S(x1) # 设置当前关注股票\n", 162 | "T(n9) # 设置当前观察日期\n", 163 | "\n", 164 | "print (\"打印 开盘 最高 最低 收盘 成交量\",O, H, L, C, V) # 打印 Open High Low Close\n", 165 | "print (\"当天涨幅\",C / C[1] - 1) # 当天涨幅\n", 166 | "print (\"打印60日均线\",MA(C, 60)) # 打印60日均线\n", 167 | "print (\"判断收盘价是否大于60日均线\",C > MA(C, 60)) # 判断收盘价是否大于60日均线\n", 168 | "print (\"30日最高价\",HHV(H, 30)) # 30日最高价\n", 169 | "print (\"最近30日,收盘价 Close 大于60日均线的天数\",COUNT(C > MA(C, 60), 30)) # 最近30日,收盘价 Close 大于60日均线的天数\n", 170 | "print (\"10日均线上穿\",CROSS(MA(C, 10), MA(C, 20))) # 10日均线上穿\n", 171 | "print (\"最近10天收阳线的天数\",COUNT(C > O, 10)) # 最近10天收阳线的天数\n", 172 | "print (\"最近60天K线实体的最高价\",HHV(MAX(O, C), 60)) # 最近60天K线实体的最高价\n", 173 | "print (\"5日均线上穿10日均线\",CROSS(MA(C, 5), MA(C, 10))) # 5日均线上穿10日均线\n", 174 | "\n", 175 | "print (\"《选股》读取时间:==》n5\",n5) \n", 176 | "#####kdj选股 !!!\n", 177 | "\n", 178 | "\n", 179 | "select(\n", 180 | " lambda : (CROSS(IF((EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))<50,((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1)))*3-(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))*2)\n", 181 | "\n", 182 | ",(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))),(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))) and CROSS(IF((EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))<50,(EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1)))*3-(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))*2)\n", 183 | "\n", 184 | "),(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))))\n", 185 | "\n", 186 | "\n", 187 | ",\n", 188 | " start_date=(n3), end_date=(n2),\n", 189 | ") \n", 190 | "\n", 191 | "print (\"《结束选股》读取结束时间:==》n5\",n5) \n" 192 | ] 193 | }, 194 | { 195 | "cell_type": "code", 196 | "execution_count": null, 197 | "metadata": { 198 | "collapsed": true 199 | }, 200 | "outputs": [], 201 | "source": [] 202 | } 203 | ], 204 | "metadata": { 205 | "kernelspec": { 206 | "display_name": "Python 3", 207 | "language": "python", 208 | "name": "python3" 209 | }, 210 | "language_info": { 211 | "codemirror_mode": { 212 | "name": "ipython", 213 | "version": 3 214 | }, 215 | "file_extension": ".py", 216 | "mimetype": "text/x-python", 217 | "name": "python", 218 | "nbconvert_exporter": "python", 219 | "pygments_lexer": "ipython3", 220 | "version": "3.6.5" 221 | } 222 | }, 223 | "nbformat": 4, 224 | "nbformat_minor": 2 225 | } 226 | -------------------------------------------------------------------------------- /rqalpha量化/选股/KDJ 选股TU.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from matplotlib import rcParams\n", 10 | "import matplotlib.pyplot as plt\n", 11 | "import numpy as np\n", 12 | "\n", 13 | "np.seterr(all='ignore')\n", 14 | "rcParams['figure.figsize'] = (14, 6)\n", 15 | "\n", 16 | "#扩展MOD\n", 17 | "from funcat import * #FUNCAT的同花顺/通达信指标模块:和:&,或:|,其他基本相同。可以使用指标选股!!!\n", 18 | "#from pytdx import * #通达信数据更新模块到QUANTAXIS的mongoDB\n", 19 | "from tushare import * #TUSHARE数据连接更新。\n", 20 | "from rqalpha import * #RQALPHA本地数据连接,通过 rqalpha update_bundle 8点后更新全部数据库\n", 21 | "#from jaqs import * #QunatOS的jaqs客户端在线。\n", 22 | "#from abupy import * #ABUPY本地化,数据在线下载更新,数据在线下载在根目录abu下\n", 23 | "#from quantaxis import * #加载QUANTAXIS数据库模块,首先需要开启mongoDB+web服务器,数据更新通过通达信服务器。\n", 24 | "#from hikyuu import * #HIKYUU本地化,数据库在根目录的stock。通过通达信导入。\n", 25 | "\n", 26 | "#读取/设定数据库时间区域,当前股票,选股时间段。 \n", 27 | "import time\n", 28 | "import datetime\n", 29 | "n1 = (time.strftime(\"20%y-%m-%d\"))## 20yy-mm-dd格式,输出当日日期\n", 30 | "print (\"读取当日时间格式n1\",n1) #当日时间格式:yyyy-mm-dd\n", 31 | "n2 = (time.strftime(\"20%y%m%d\"))## 20yymmdd格式,输出当日日期\n", 32 | "print (\"读取当日时间格式n2\",n2) #当日时间格式:yyyymmdd\n", 33 | "def getYesterday(): \n", 34 | " today=datetime.date.today() \n", 35 | " oneday=datetime.timedelta(days=1) \n", 36 | " yesterday=today-oneday \n", 37 | " return yesterday\n", 38 | "n3 = (getYesterday())# 输出前一天日期\n", 39 | "print (\"读取前一日时间格式n3\",n3) #前日时间格式:yyyy-mm-dd\n", 40 | "i = datetime.datetime.now()#当前日期\n", 41 | "n4 = (\"%s%s%s\" % (i.year, i.month, i.day) )\n", 42 | "print (\"读取当日时间格式n4\",n4) #当日时间格式:yyyymmdd\n", 43 | "n5 = (\"%s\" % i.isoformat() )\n", 44 | "print (\"读取当日时间格式n5\",n5) #当日时间格式:yyyy-mm-dd:...\n", 45 | "\n", 46 | "n8=\"20180205\"#开始时间\n", 47 | "print (\"手动设定选股开始时间格式n8\",n8)\n", 48 | "\n", 49 | "n9=\"20180205\"#结束时间\n", 50 | "print (\"手动设定选股结束时间格式n9\",n9)\n", 51 | "\n", 52 | "n10=\"20170101\"#设定起始时间\n", 53 | "print (\"手动设定数据更新设定起始时间格式n10\",n10)\n", 54 | "x1=\"000001\"\n", 55 | "print (\"设定股票代码\",x1)\n", 56 | "\n", 57 | "#设定数据库连接:RQALPHA/TUSHARE\n", 58 | "from funcat.data.tushare_backend import TushareDataBackend\n", 59 | "from funcat.data.rqalpha_data_backend import RQAlphaDataBackend\n", 60 | "backend = \"tushare\"\n", 61 | "if backend == \"rqalpha\":\n", 62 | " set_data_backend(RQAlphaDataBackend(\"~/.rqalpha/bundle\"))\n", 63 | "elif backend == \"tushare\":\n", 64 | " set_data_backend(TushareDataBackend())\n", 65 | "set_start_date(n10)\n", 66 | "\n", 67 | "#当前股票最新数据显示。\n", 68 | "S(x1) # 设置当前关注股票\n", 69 | "T(n3) # 设置当前观察日期\n", 70 | "\n", 71 | "print (\"打印 开盘 最高 最低 收盘 成交量\",O, H, L, C, V) # 打印 Open High Low Close\n", 72 | "print (\"当天涨幅\",C / C[1] - 1) # 当天涨幅\n", 73 | "print (\"打印60日均线\",MA(C, 60)) # 打印60日均线\n", 74 | "print (\"判断收盘价是否大于60日均线\",C > MA(C, 60)) # 判断收盘价是否大于60日均线\n", 75 | "print (\"30日最高价\",HHV(H, 30)) # 30日最高价\n", 76 | "print (\"最近30日,收盘价 Close 大于60日均线的天数\",COUNT(C > MA(C, 60), 30)) # 最近30日,收盘价 Close 大于60日均线的天数\n", 77 | "print (\"10日均线上穿\",CROSS(MA(C, 10), MA(C, 20))) # 10日均线上穿\n", 78 | "print (\"最近10天收阳线的天数\",COUNT(C > O, 10)) # 最近10天收阳线的天数\n", 79 | "print (\"最近60天K线实体的最高价\",HHV(MAX(O, C), 60)) # 最近60天K线实体的最高价\n", 80 | "print (\"5日均线上穿10日均线\",CROSS(MA(C, 5), MA(C, 10))) # 5日均线上穿10日均线\n", 81 | "\n", 82 | "print (\"《选股》读取时间:==》n5\",n5) \n", 83 | "#####kdj选股 !!!\n", 84 | "\n", 85 | "\n", 86 | "select(\n", 87 | " lambda : (CROSS(IF((EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))<50,((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1)))*3-(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))*2)\n", 88 | "\n", 89 | ",(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))),(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))) and CROSS(IF((EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))<50,(EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1)))*3-(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))*2)\n", 90 | "\n", 91 | "),(EMA((EMA(((HHV(L,1)-LLV(L,27))/(HHV(H,27)-LLV(L,27))*100),(9*2-1))),(3*2-1)))))\n", 92 | "\n", 93 | "\n", 94 | ",\n", 95 | " start_date=(n3), end_date=(n2),\n", 96 | ") \n", 97 | "\n", 98 | "print (\"《结束选股》读取结束时间:==》n5\",n5) \n" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "execution_count": null, 111 | "metadata": {}, 112 | "outputs": [], 113 | "source": [] 114 | } 115 | ], 116 | "metadata": { 117 | "kernelspec": { 118 | "display_name": "Python 3", 119 | "language": "python", 120 | "name": "python3" 121 | }, 122 | "language_info": { 123 | "codemirror_mode": { 124 | "name": "ipython", 125 | "version": 2 126 | }, 127 | "file_extension": ".py", 128 | "mimetype": "text/x-python", 129 | "name": "python", 130 | "nbconvert_exporter": "python", 131 | "pygments_lexer": "ipython2", 132 | "version": "2.7.13" 133 | } 134 | }, 135 | "nbformat": 4, 136 | "nbformat_minor": 2 137 | } 138 | -------------------------------------------------------------------------------- /rqalpha量化/选股/选股成交量BOLL.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "读取当日时间格式n1 2018-11-22\n", 13 | "读取当日时间格式n2 20181122\n", 14 | "读取前二日时间格式n3 2018-11-21\n", 15 | "读取当日时间格式n4 20181122\n", 16 | "读取当日时间格式n5 2018-11-22T21:56:20.045339\n", 17 | "手动设定选股开始时间格式n8 20180201\n", 18 | "手动设定选股结束时间格式n9 20180209\n", 19 | "手动设定数据更新设定起始时间格式n10 20170101\n", 20 | "设定股票代码 000001.XSHG\n", 21 | "打印 开盘 最高 最低 收盘 成交量 3172.85 3180.11 3062.74 3129.85 25638917600.0\n", 22 | "当天涨幅 -0.04052666268144278\n", 23 | "打印60日均线 3372.0388333333312\n", 24 | "判断收盘价是否大于60日均线 False\n", 25 | "30日最高价 3587.03\n", 26 | "最近30日,收盘价 Close 大于60日均线的天数 24\n", 27 | "10日均线上穿 False\n", 28 | "最近10天收阳线的天数 3\n", 29 | "最近60天K线实体的最高价 3563.64\n", 30 | "5日均线上穿10日均线 False\n", 31 | "《选股》读取时间:==》n5 2018-11-22T21:56:20.045339\n", 32 | "lambda : CROSS((V/L), ((MA(((V/H)+(V/L))/2,27))-STD((V/H),27)*1.618)) ,\n", 33 | "[20181122]\n", 34 | "No data for 000003.XSHE\n", 35 | "No data for 000013.XSHE\n", 36 | "No data for 000015.XSHE\n", 37 | "No data for 000047.XSHE\n", 38 | "20181122 000089.XSHE 深圳机场\n", 39 | "No data for 000405.XSHE\n", 40 | "No data for 000412.XSHE\n", 41 | "No data for 000508.XSHE\n", 42 | "No data for 000542.XSHE\n", 43 | "No data for 000556.XSHE\n", 44 | "No data for 000588.XSHE\n", 45 | "No data for 000621.XSHE\n", 46 | "No data for 000653.XSHE\n", 47 | "No data for 000658.XSHE\n", 48 | "No data for 000660.XSHE\n", 49 | "No data for 000675.XSHE\n", 50 | "No data for 000689.XSHE\n", 51 | "No data for 000730.XSHE\n", 52 | "20181122 000979.XSHE 中弘退\n", 53 | "20181122 002229.XSHE 鸿博股份\n", 54 | "No data for 002257.XSHE\n", 55 | "No data for 002525.XSHE\n", 56 | "20181122 002618.XSHE 丹邦科技\n", 57 | "20181122 002700.XSHE 新疆浩源\n", 58 | "No data for 002710.XSHE\n", 59 | "No data for 002720.XSHE\n", 60 | "20181122 002792.XSHE 通宇通讯\n", 61 | "20181122 002795.XSHE 永和智控\n" 62 | ] 63 | } 64 | ], 65 | "source": [ 66 | "from matplotlib import rcParams\n", 67 | "import matplotlib.pyplot as plt\n", 68 | "import numpy as np\n", 69 | "\n", 70 | "np.seterr(all='ignore')\n", 71 | "rcParams['figure.figsize'] = (14, 6)\n", 72 | "\n", 73 | "#扩展MOD\n", 74 | "from funcat import * #FUNCAT的同花顺/通达信指标模块:和:&,或:|,其他基本相同。可以使用指标选股!!!\n", 75 | "#from pytdx import * #通达信数据更新模块到QUANTAXIS的mongoDB\n", 76 | "from tushare import * #TUSHARE数据连接更新。\n", 77 | "from rqalpha import * #RQALPHA本地数据连接,通过 rqalpha update_bundle 8点后更新全部数据库\n", 78 | "#from jaqs import * #QunatOS的jaqs客户端在线。\n", 79 | "#from abupy import * #ABUPY本地化,数据在线下载更新,数据在线下载在根目录abu下\n", 80 | "#from quantaxis import * #加载QUANTAXIS数据库模块,首先需要开启mongoDB+web服务器,数据更新通过通达信服务器。\n", 81 | "#from hikyuu import * #HIKYUU本地化,数据库在根目录的stock。通过通达信导入。\n", 82 | "\n", 83 | "#读取/设定数据库时间区域,当前股票,选股时间段。 \n", 84 | "import time\n", 85 | "import datetime\n", 86 | "n1 = (time.strftime(\"20%y-%m-%d\"))## 20yy-mm-dd格式,输出当日日期\n", 87 | "print (\"读取当日时间格式n1\",n1) #当日时间格式:yyyy-mm-dd\n", 88 | "n2 = (time.strftime(\"20%y%m%d\"))## 20yymmdd格式,输出当日日期\n", 89 | "print (\"读取当日时间格式n2\",n2) #当日时间格式:yyyymmdd\n", 90 | "def getYesterday(): \n", 91 | " today=datetime.date.today() \n", 92 | " oneday=datetime.timedelta(days=1) \n", 93 | " yesterday=today-oneday \n", 94 | " return yesterday\n", 95 | "n3 = (getYesterday())# 输出前N天日期\n", 96 | "print (\"读取前二日时间格式n3\",n3) #前日时间格式:yyyy-mm-dd\n", 97 | "i = datetime.datetime.now()#当前日期\n", 98 | "n4 = (\"%s%s%s\" % (i.year, i.month, i.day) )\n", 99 | "print (\"读取当日时间格式n4\",n4) #当日时间格式:yyyymmdd\n", 100 | "n5 = (\"%s\" % i.isoformat() )\n", 101 | "print (\"读取当日时间格式n5\",n5) #当日时间格式:yyyy-mm-dd:...\n", 102 | "\n", 103 | "n8=\"20180201\"#开始时间\n", 104 | "print (\"手动设定选股开始时间格式n8\",n8)\n", 105 | "\n", 106 | "n9=\"20180209\"#结束时间\n", 107 | "print (\"手动设定选股结束时间格式n9\",n9)\n", 108 | "\n", 109 | "n10=\"20170101\"#设定起始时间\n", 110 | "print (\"手动设定数据更新设定起始时间格式n10\",n10)\n", 111 | "x1=\"000001.XSHG\"\n", 112 | "print (\"设定股票代码\",x1)\n", 113 | "\n", 114 | "#设定数据库连接:RQALPHA/TUSHARE\n", 115 | "from funcat.data.tushare_backend import TushareDataBackend\n", 116 | "from funcat.data.rqalpha_data_backend import RQAlphaDataBackend\n", 117 | "backend = \"rqalpha\"\n", 118 | "if backend == \"rqalpha\":\n", 119 | " set_data_backend(RQAlphaDataBackend(\"~/.rqalpha/bundle\"))\n", 120 | "elif backend == \"tushare\":\n", 121 | " set_data_backend(TushareDataBackend())\n", 122 | "set_start_date(n10)\n", 123 | "\n", 124 | "#当前股票最新数据显示。\n", 125 | "S(x1) # 设置当前关注股票\n", 126 | "T(n9) # 设置当前观察日期\n", 127 | "\n", 128 | "print (\"打印 开盘 最高 最低 收盘 成交量\",O, H, L, C, V) # 打印 Open High Low Close\n", 129 | "print (\"当天涨幅\",C / C[1] - 1) # 当天涨幅\n", 130 | "print (\"打印60日均线\",MA(C, 60)) # 打印60日均线\n", 131 | "print (\"判断收盘价是否大于60日均线\",C > MA(C, 60)) # 判断收盘价是否大于60日均线\n", 132 | "print (\"30日最高价\",HHV(H, 30)) # 30日最高价\n", 133 | "print (\"最近30日,收盘价 Close 大于60日均线的天数\",COUNT(C > MA(C, 60), 30)) # 最近30日,收盘价 Close 大于60日均线的天数\n", 134 | "print (\"10日均线上穿\",CROSS(MA(C, 10), MA(C, 20))) # 10日均线上穿\n", 135 | "print (\"最近10天收阳线的天数\",COUNT(C > O, 10)) # 最近10天收阳线的天数\n", 136 | "print (\"最近60天K线实体的最高价\",HHV(MAX(O, C), 60)) # 最近60天K线实体的最高价\n", 137 | "print (\"5日均线上穿10日均线\",CROSS(MA(C, 5), MA(C, 10))) # 5日均线上穿10日均线\n", 138 | "\n", 139 | "print (\"《选股》读取时间:==》n5\",n5) \n", 140 | "# 选股成交量BOLL OK!!!\n", 141 | "select(\n", 142 | " lambda : CROSS((V/L), ((MA(((V/H)+(V/L))/2,27))-STD((V/H),27)*1.618)) ,\n", 143 | " start_date=(n3), end_date=(n2),)\n", 144 | "\n", 145 | "print (\"《结束选股》读取结束时间:==》n5\",n5) " 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": null, 151 | "metadata": { 152 | "collapsed": true 153 | }, 154 | "outputs": [], 155 | "source": [] 156 | } 157 | ], 158 | "metadata": { 159 | "kernelspec": { 160 | "display_name": "Python 3", 161 | "language": "python", 162 | "name": "python3" 163 | } 164 | }, 165 | "nbformat": 4, 166 | "nbformat_minor": 2 167 | } 168 | -------------------------------------------------------------------------------- /untitled.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/untitled.txt -------------------------------------------------------------------------------- /京东量化/jd回测.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/京东量化/jd回测.xlsx -------------------------------------------------------------------------------- /京东量化/jd源码.txt: -------------------------------------------------------------------------------- 1 | import pandas 2 | import numpy 3 | import datetime 4 | import math 5 | 6 | # 初始化信息 7 | def init(context): 8 | #滑点默认值2‰ 9 | context.set_slippage(0.002) 10 | #交易费默认值0.25‰ 11 | context.set_commission(0.0025) 12 | #基准默认沪深300 13 | context.set_benchmark("000300.SH") 14 | #context.set_benchmark("000905.SH") 15 | #context.set_benchmark("399333.SH") 16 | 17 | #def init(context): 18 | #调仓 19 | task.daily(rebalance,time_rule=market_open(minute=1)) 20 | #task.weekly() 21 | #task.monthly(rebalance,1) 22 | #每天开盘前进行选股 23 | def before_trade(context): 24 | context.stock_list = choose_stock() 25 | 26 | #策略买入信号函数 27 | 28 | def buy_stock(context,stock ,data_dict): 29 | #max_position = 0.618/8 #最大买入仓位 30 | stock_buy_num =5 #最多买入5支股票 31 | max_position =0.618 #0.618/(8*1.618) #最大买入仓位 32 | #max_position = 0.618/(stock_buy_num*2) #最大买入仓位 33 | stock_percentage = 0.0618 #0.618/(8*1.618) #每支股票买入的最大仓位 34 | 35 | if len(context.portfolio.positions) < stock_buy_num: 36 | cash = context.portfolio.cash #当前投资当前投资组合剩余现金 37 | portfolio_value = context.portfolio.portfolio_value #总资产包含剩余现金与市场价值 38 | quantity = context.portfolio.positions[stock].quantity #总股数 39 | price_value = data_dict[stock].last #新价格 40 | p_value = price_value*quantity #价格*股数=总市值 41 | stock_position = p_value/portfolio_value #*0.618 #总市值/总资产 42 | if p_value/portfolio_value < max_position and cash/portfolio_value > max_position: 43 | order_target_percent(stock, max_position) #*stock_percentage) #买入股票 44 | order_target_percent(stock, stock_percentage) #买入股票 45 | 46 | #策略卖出信号函数 47 | 48 | def sell_stock(context,stock_list,data_dict): 49 | for stock in list(context.portfolio.positions.keys()): 50 | if not (stock in stock_list): 51 | order_target_value(stock,0) #如果不在股票列表中则全部卖出 52 | print(context.portfolio.positions[stock]) 53 | 54 | # 卖出逻辑 55 | def clear_position(context, data_dict): 56 | for security_code in context.portfolio.positions.keys(): 57 | current_hold_security = context.portfolio.positions[security_code] 58 | current_hold_security_cost = get_cost(current_hold_security) 59 | current_security_price = data_dict[security_code].last 60 | current_security_high = data_dict[security_code].high 61 | current_security = data_dict[security_code] 62 | 63 | 64 | # 日或分钟历史数据,实时数据更新 65 | 66 | def handle_data(context, data_dict): 67 | #option_stock(context,data_dict) 68 | pass 69 | 70 | #操作股票 71 | def option_stock(context,data_dict): 72 | stock_list = context.stock_list 73 | sell_stock(context,stock_list,data_dict) #先卖出股票再买入 74 | for stock in stock_list: 75 | buy_stock(context,stock,data_dict) #买入股票 76 | 77 | def before_trade(context): 78 | stock_num = 10 79 | #每日选股 80 | dataframe = get_fundamentals( 81 | query( 82 | fundamentals.financial_analysis_indicator.earnings_per_share, 83 | fundamentals.equity_valuation_indicator.pe_ratio, 84 | fundamentals.financial_analysis_indicator.return_on_asset, 85 | ) 86 | .filter( 87 | fundamentals.equity_valuation_indicator.pe_ratio<200 88 | ) 89 | .filter( 90 | fundamentals.financial_analysis_indicator.earnings_per_share>0.309 91 | ) 92 | .filter( 93 | fundamentals.financial_analysis_indicator.return_on_asset>0.0618 94 | ) 95 | #.filter( 96 | # fundamentals.equity_valuation_indicator.a_share_market_val_2 #总市值 97 | #) 98 | .filter( 99 | 1*100000000> fundamentals.equity_valuation_indicator.a_share_market_val_2 < 2000*100000000 #总市值200亿 100 | ) 101 | .order_by( 102 | fundamentals.equity_valuation_indicator.a_share_market_val_2.asc() #<100*100000000 103 | ).limit( 104 | 10 105 | ) 106 | ) 107 | context.dataframe = dataframe 108 | context.stocks = context.dataframe.columns.values 109 | logger.info(context.stocks) 110 | logger.info(dataframe) 111 | 112 | 113 | #调仓 114 | def rebalance(context,data_dict): 115 | for stock in context.portfolio.positions: 116 | if stock not in context.dataframe: 117 | order_target_percent(stock, 0) 118 | if len(context.stocks) == 0: 119 | weight = 0 120 | else: 121 | weight = 1 122 | for stock in context.dataframe: 123 | if weight != 0 and stock in context.dataframe: 124 | order_target_percent(stock,(weight/20)*1.618) 125 | 126 | # 过滤掉退市的,ST的 127 | def filterate_special_list(context, asc_security_list): 128 | for security_code in asc_security_list: 129 | if is_st(security_code) or is_delisting(security_code): 130 | continue 131 | else: 132 | context.candidate_security.append(security_code) 133 | 134 | #过滤ST、新股的一些代码如下 135 | #去除st 新股 136 | def buy_lists(stock_list,context,data_dict): 137 | stock_list = [] 138 | for stock in stock_list: 139 | if up_day(stock,context) > 180: #新股大于80天 140 | if not is_buy_stock(stock,data_dict): 141 | if len(new_list) < 5000 : #LIST里面存储的股票 142 | new_list.append(stock) 143 | return stock_list 144 | 145 | #去除不需要的股票,停牌、退市、st创业版股票 146 | #如果是停牌、退市、st创业版股票,则返回True 147 | def is_buy_stock(stock,data_dict): 148 | result = False 149 | # 0可以交易;1停牌无法交易 150 | if data_dict[stock].sf == 1: 151 | result = True 152 | # 去除退市的 153 | elif is_delisting(stock): 154 | result = True 155 | # 去除st 156 | elif is_st(stock): 157 | result = True 158 | return result 159 | 160 | #返回上市时到现在一共多少天 161 | def up_day(stock,context): 162 | up_time = get_securities (stock).listed_date 163 | today = context.now 164 | print(up_time,today) 165 | days = (today - up_time).days #上市距离现在的时间 166 | return days 167 | # 简单的判断股灾(昨天大盘收盘跌幅高于2%) 168 | def is_disaster(context): 169 | now = context.now 170 | yesterday_open = get_history(1,'1d','open')['000300.SH'].values 171 | yesterday_close = get_history(1,'1d','close')['000300.SH'].values 172 | yesterday_open_1 = get_history(1,'1d','open')['000001.SH'].values 173 | yesterday_close_1 = get_history(1,'1d','close')['000001.SH'].values 174 | 175 | range_of_price_drop = (yesterday_close-yesterday_open)/yesterday_open # 跌幅 176 | range_of_price_drop_1 = (yesterday_close_1-yesterday_open_1)/yesterday_open 177 | # 跌幅 178 | 179 | result = 0 180 | 181 | if (range_of_price_drop <= -0.01 or range_of_price_drop_1 <= -0.01): # 跌幅超过2% 182 | if context.last_disater is not None: 183 | if (now - context.last_disater).days <= 5: 184 | result = 1 185 | else: 186 | result = 0 187 | else: 188 | pass 189 | context.last_disater = now 190 | 191 | return result 192 | 193 | # 对所有股票进行平仓操作, 默认彻底清仓 194 | def thorough_clear_position(context): 195 | for security_code in context.portfolio.positions.keys(): 196 | order_target_value(security_code, 0) 197 | 198 | #判断成本价和持仓天数更新: 199 | for stk in context.portfolio.positions.keys(): 200 | if context.portfolio.positions[stk].quantity==0: 201 | continue 202 | else: 203 | stkInfo = {} 204 | stkInfo['avgCost'] = context.portfolio.positions[stk].bought_value/context.portfolio.positions[stk].bought_quantity 205 | stkInfo['holdDays'] = 1 206 | context.curPflInfo[stk] = stkInfo 207 | 208 | # context.set_benchmark("000001.SZ") 209 | #这里选了000001.SZ作为参考基准,大家可以根据自己的不同需要进行修改; 210 | #context.buyList = [] 211 | #制定了一个买股的集合单子;存放在buyList里面的就是我们选出来后的要买的股 212 | #context.curPflInfo = {} 213 | #curPflInfo 的key为当前持仓股票,value为股票信息 214 | #如 context.curPflInfo = {'000001.XSHE':{'time':1,'avgCost':9.5}} 215 | #avgCost是平均成本 216 | #context.holdSize = 10 217 | #持仓数 218 | #context.weight = 0 219 | #新买个股的初始仓位 每天开盘前初始化 220 | context.stpPftPrice = 0.05 221 | #止盈,可以是值,也可以是百分比制; 222 | context.stpLosRate = -0.05 223 | #止损,和止盈同样的道理 224 | #context.orderList = [] 225 | #下单集合 226 | def filterStAndPaused(stkList,data_dict): 227 | #过滤st和停牌股票 228 | stkList = [stk for stk in stkList if not is_st(stk) and data_dict[stk].sf==0] 229 | return stkList 230 | def filterLimitStk(stk,data_dict,context): 231 | #过滤涨跌停股票 232 | yesterday = get_history(2,'1d', 'close')[stk].values[-1] 233 | zt = round(1.10 * yesterday,2) 234 | dt = round(0.97 * yesterday,2) 235 | if dt < data_dict[stk].last < zt : 236 | return True 237 | else : 238 | return False 239 | 240 | popList=[] 241 | for stk in context.curPflInfo.keys(): 242 | if (data_dict[stk].close / context.curPflInfo[stk]['avgCost']) -1 >= context.stpPftPrice: 243 | #如果 当前价和成本价的差价大于预定值 则卖出 244 | order_target_value(stk, 0) 245 | print ('止盈卖出 :', stk) 246 | popList.append(stk) 247 | for stk in popList: 248 | context.curPflInfo.pop(stk) 249 | 250 | 251 | popList = [] 252 | for stk in context.curPflInfo.keys(): 253 | if (context.curPflInfo[stk]['avgCost']==0): 254 | popList.append(stk) 255 | continue 256 | if (data_dict[stk].close / context.curPflInfo[stk]['avgCost']) -1 <= context.stpLosRate: 257 | #如果当前亏损大于预定值 则止损卖出 258 | order_target_value(stk, 0) 259 | if now.hour ==14 and now.minute == 55 : 260 | print ('止损卖出 :', stk) 261 | popList.append(stk) 262 | for stk in popList: 263 | context.curPflInfo.pop(stk) -------------------------------------------------------------------------------- /希尔伯特变换.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "import QUANTAXIS as QA\n", 12 | "\n", 13 | "# 获取全市场的股票代码信息列表\n", 14 | "QA_code_list = QA.QA_fetch_stock_list_adv()\n", 15 | "#QA_code_list\n", 16 | "#QA全市场code列表\n", 17 | "QA_code = QA_code_list.code.tolist() \n", 18 | "#QA_code\n", 19 | "#QA全市场name列表\n", 20 | "QA_name = QA_code_list.name.tolist() \n", 21 | "#QA_name \n", 22 | "#训练起始时间\n", 23 | "start_date='2015-06-01'\n", 24 | "end_date='2017-06-01'\n", 25 | "#inst = D.instruments(start_date, end_date, market='CN_STOCK_A')\n", 26 | "#print(inst)\n", 27 | "#instruments = ['600519']\n", 28 | "instruments = QA_code\n", 29 | "hists = QA.QA_fetch_stock_day_adv(instruments, start_date, end_date).data\n", 30 | "hist = hists" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 5, 36 | "metadata": {}, 37 | "outputs": [ 38 | { 39 | "ename": "AttributeError", 40 | "evalue": "QA_DataStruct_* Class Currently has no attribute set_index", 41 | "output_type": "error", 42 | "traceback": [ 43 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 44 | "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", 45 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;31m#history_data = D.history_data(instruments, '2012-06-01', end_date, fields=['open','close'])\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0mhistory_data\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mQA\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mQA_fetch_stock_day_adv\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minstruments\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstart_date\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mend_date\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0mhistory_data\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_index\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'date'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0minplace\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 11\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0mhistory_data\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'ma_20'\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mhistory_data\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mclose\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrolling\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m20\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmean\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# 计算MA20\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 46 | "\u001b[0;32m/Volumes/QuantOsUSB/QuantOsUSB/kivy.app/Contents/Resources/venv/lib/python3.6/site-packages/QUANTAXIS/QAData/base_datastruct.py\u001b[0m in \u001b[0;36m__getattr__\u001b[0;34m(self, attr)\u001b[0m\n\u001b[1;32m 215\u001b[0m \u001b[0;31m# except:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 216\u001b[0m raise AttributeError(\n\u001b[0;32m--> 217\u001b[0;31m 'QA_DataStruct_* Class Currently has no attribute {}'.format(attr))\n\u001b[0m\u001b[1;32m 218\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 219\u001b[0m '''\n", 47 | "\u001b[0;31mAttributeError\u001b[0m: QA_DataStruct_* Class Currently has no attribute set_index" 48 | ] 49 | } 50 | ], 51 | "source": [ 52 | "import numpy as np\n", 53 | "from scipy.signal import hilbert\n", 54 | "#start_date = '2013-01-01'\n", 55 | "#end_date = '2017-10-23'\n", 56 | "benchmark = '000300.INDX' # 基准:HS300\n", 57 | "instruments = ['000001'] # 标的:HS300 ETF\n", 58 | "capital_base = 100000\n", 59 | "#history_data = D.history_data(instruments, '2012-06-01', end_date, fields=['open','close'])\n", 60 | "history_data = QA.QA_fetch_stock_day_adv(instruments, start_date, end_date)\n", 61 | "history_data.set_index('date',inplace=True)\n", 62 | "\n", 63 | "history_data['ma_20'] = history_data.close.rolling(20).mean() # 计算MA20\n", 64 | "history_data['dsR'] = history_data['ma_20']-history_data['ma_20'].shift(1) # 计算差分\n", 65 | "history_data['idsR'] = np.nan\n", 66 | "for n in range(120,len(history_data)): # 计算最近100天的Hilbert变换\n", 67 | " history_data['idsR'][n] = np.imag(hilbert(history_data['dsR'][n-100:n+1]))[-1]\n", 68 | " \n", 69 | "def initialize(context): \n", 70 | " context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0003, min_cost=5)) \n", 71 | " #print (history_data)\n", 72 | " \n", 73 | "def handle_data(context, data): \n", 74 | " instrument = context.symbol(instruments[0])\n", 75 | " dataTmp = history_data.ix[data.current_dt.date()]\n", 76 | " cur_position = context.portfolio.positions[instrument].amount \n", 77 | " \n", 78 | " if dataTmp['idsR'] > 0 and cur_position == 0: # 虚部大于0,买入\n", 79 | " order_target_percent(instrument, 1)\n", 80 | " elif dataTmp['idsR'] < 0 and cur_position > 0: # 虚部小于0,卖出\n", 81 | " order_target_percent(instrument, 0)\n", 82 | " \n", 83 | "\n", 84 | "\n", 85 | "\n" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "metadata": { 92 | "collapsed": true 93 | }, 94 | "outputs": [], 95 | "source": [ 96 | "m = M.trade.v2(\n", 97 | " instruments=instruments,\n", 98 | " start_date=start_date,\n", 99 | " end_date=end_date,\n", 100 | " initialize=initialize,\n", 101 | " handle_data=handle_data,\n", 102 | " order_price_field_buy='open',\n", 103 | " order_price_field_sell='open',\n", 104 | " volume_limit=0,\n", 105 | " capital_base=capital_base,\n", 106 | " benchmark=benchmark,\n", 107 | ")" 108 | ] 109 | } 110 | ], 111 | "metadata": { 112 | "kernelspec": { 113 | "display_name": "Python 3", 114 | "language": "python", 115 | "name": "python3" 116 | }, 117 | "language_info": { 118 | "codemirror_mode": { 119 | "name": "ipython", 120 | "version": 3 121 | }, 122 | "file_extension": ".py", 123 | "mimetype": "text/x-python", 124 | "name": "python", 125 | "nbconvert_exporter": "python", 126 | "pygments_lexer": "ipython3", 127 | "version": "3.6.5" 128 | } 129 | }, 130 | "nbformat": 4, 131 | "nbformat_minor": 2 132 | } 133 | -------------------------------------------------------------------------------- /跨平台量化环境综合对抗测试.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stderr", 10 | "output_type": "stream", 11 | "text": [ 12 | "[INFO ] [Logger ] Record log in /Users/zy/.kivy/logs/kivy_18-12-12_1.txt\n", 13 | "[INFO ] [Kivy ] v1.10.1\n", 14 | "[INFO ] [Python ] v3.6.5 (default, Jun 21 2018, 07:41:06) \n", 15 | "[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)]\n", 16 | "[INFO ] [Factory ] 194 symbols loaded\n", 17 | "[INFO ] [Image ] Providers: img_tex, img_imageio, img_dds, img_sdl2, img_pil, img_gif (img_ffpyplayer ignored)\n" 18 | ] 19 | }, 20 | { 21 | "name": "stdout", 22 | "output_type": "stream", 23 | "text": [ 24 | "kivy 1.10.1\n" 25 | ] 26 | } 27 | ], 28 | "source": [ 29 | "#测试模块多环境整合!!!\n", 30 | "from kivy.app import App #kivy跨平台编译环境\n", 31 | "import kivy \n", 32 | "print (\"kivy\",kivy.__version__)" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 1, 38 | "metadata": { 39 | "scrolled": true 40 | }, 41 | "outputs": [ 42 | { 43 | "name": "stderr", 44 | "output_type": "stream", 45 | "text": [ 46 | "UsageError: Cell magic `%%rqalpha` not found.\n" 47 | ] 48 | } 49 | ], 50 | "source": [ 51 | "%%rqalpha -h\n", 52 | "\"\"" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": 2, 58 | "metadata": { 59 | "collapsed": true 60 | }, 61 | "outputs": [], 62 | "source": [ 63 | "%load_ext rqalpha " 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "metadata": { 70 | "collapsed": true 71 | }, 72 | "outputs": [], 73 | "source": [ 74 | "#计划\n", 75 | "\n", 76 | "#1。引入模块三个数据连接RQ+QA+DY。\n", 77 | "\n", 78 | "#2。1。三份全市场风险评估综合+学习+对抗。\n", 79 | "\n", 80 | "#2。2。三份数据选股处理评估+历史时间周期风险分布+学习+对抗。\n", 81 | "\n", 82 | "#3。当前仓计算仓位控制和风险控制。\n", 83 | "\n", 84 | "#4。买入后持股计算风险分类和仓变控制。\n", 85 | "\n", 86 | "#4。1。盈利单锁仓处理和仓控。\n", 87 | "\n", 88 | "#4。2。盈利单复利计划。\n", 89 | "\n", 90 | "#6。浮亏单锁仓处理和仓控。\n", 91 | "\n", 92 | "#7。紧急情况处理。\n", 93 | "\n", 94 | "#8。统计与分析评估\n", 95 | "\n" 96 | ] 97 | } 98 | ], 99 | "metadata": { 100 | "kernelspec": { 101 | "display_name": "Python 3", 102 | "language": "python", 103 | "name": "python3" 104 | }, 105 | "language_info": { 106 | "codemirror_mode": { 107 | "name": "ipython", 108 | "version": 3 109 | }, 110 | "file_extension": ".py", 111 | "mimetype": "text/x-python", 112 | "name": "python", 113 | "nbconvert_exporter": "python", 114 | "pygments_lexer": "ipython3", 115 | "version": "3.6.5" 116 | } 117 | }, 118 | "nbformat": 4, 119 | "nbformat_minor": 2 120 | } 121 | -------------------------------------------------------------------------------- /飞狐指标选股分析/4152B7F78F29352BE9B1E42DA61D2C30.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/飞狐指标选股分析/4152B7F78F29352BE9B1E42DA61D2C30.jpg -------------------------------------------------------------------------------- /飞狐指标选股分析/56E9E52F38417A8F8A6C918B9A0C2FC0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/飞狐指标选股分析/56E9E52F38417A8F8A6C918B9A0C2FC0.jpg -------------------------------------------------------------------------------- /飞狐指标选股分析/5DBFF4F442556A46BB142FC95DCE8AE5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/飞狐指标选股分析/5DBFF4F442556A46BB142FC95DCE8AE5.jpg -------------------------------------------------------------------------------- /飞狐指标选股分析/6F7C1D112F1FC95964A2AFAF1B3A0F09.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/飞狐指标选股分析/6F7C1D112F1FC95964A2AFAF1B3A0F09.jpg -------------------------------------------------------------------------------- /飞狐指标选股分析/706F846AC1D97A880C53BCA56E57ABF6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/飞狐指标选股分析/706F846AC1D97A880C53BCA56E57ABF6.jpg -------------------------------------------------------------------------------- /飞狐指标选股分析/964BDAEE6127C21BD39A23735A4631BF.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/飞狐指标选股分析/964BDAEE6127C21BD39A23735A4631BF.jpg -------------------------------------------------------------------------------- /飞狐指标选股分析/A3EAD336FAA99D0CBF76F5E7B977675C.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/飞狐指标选股分析/A3EAD336FAA99D0CBF76F5E7B977675C.jpg -------------------------------------------------------------------------------- /飞狐指标选股分析/C60D0650ED1E479DFC06AD55F7DB8458.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm58/notebook/9b7688952ad2054038b3a129b545fe65bdfce053/飞狐指标选股分析/C60D0650ED1E479DFC06AD55F7DB8458.jpg --------------------------------------------------------------------------------