[Add] examples folder
This commit is contained in:
parent
40bd01fdff
commit
58a9f56072
93
examples/cta_backtesting/backtesting.ipynb
Normal file
93
examples/cta_backtesting/backtesting.ipynb
Normal file
@ -0,0 +1,93 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"#%%\n",
|
||||
"from vnpy.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting\n",
|
||||
"from vnpy.app.cta_strategy.strategies.atr_rsi_strategy import (\n",
|
||||
" AtrRsiStrategy,\n",
|
||||
")\n",
|
||||
"from datetime import datetime"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"#%%\n",
|
||||
"engine = BacktestingEngine()\n",
|
||||
"engine.set_parameters(\n",
|
||||
" vt_symbol=\"IF88.CFFEX\",\n",
|
||||
" interval=\"1m\",\n",
|
||||
" start=datetime(2019, 1, 1),\n",
|
||||
" end=datetime(2019, 4, 30),\n",
|
||||
" rate=0.3/10000,\n",
|
||||
" slippage=0.2,\n",
|
||||
" size=300,\n",
|
||||
" pricetick=0.2,\n",
|
||||
" capital=1_000_000,\n",
|
||||
")\n",
|
||||
"engine.add_strategy(AtrRsiStrategy, {})"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"scrolled": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"#%%\n",
|
||||
"engine.load_data()\n",
|
||||
"engine.run_backtesting()\n",
|
||||
"df = engine.calculate_result()\n",
|
||||
"engine.calculate_statistics()\n",
|
||||
"engine.show_chart()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"setting = OptimizationSetting()\n",
|
||||
"setting.set_target(\"sharpe_ratio\")\n",
|
||||
"setting.add_parameter(\"atr_length\", 3, 39, 1)\n",
|
||||
"setting.add_parameter(\"atr_ma_length\", 10, 30, 1)\n",
|
||||
"\n",
|
||||
"engine.run_ga_optimization(setting)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.7.1"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
@ -1,279 +0,0 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import random\n",
|
||||
"import multiprocessing\n",
|
||||
"import numpy as np\n",
|
||||
"from deap import creator, base, tools, algorithms\n",
|
||||
"from vnpy.app.cta_strategy.backtesting import BacktestingEngine,OptimizationSetting\n",
|
||||
"from vnpy.app.cta_strategy.strategies.boll_channel_strategy import BollChannelStrategy\n",
|
||||
"from vnpy.app.cta_strategy.strategies.atr_rsi_strategy import AtrRsiStrategy\n",
|
||||
"from datetime import datetime\n",
|
||||
"import multiprocessing #多进程\n",
|
||||
"from functools import lru_cache"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"setting = OptimizationSetting()\n",
|
||||
"#setting.add_parameter('atr_length', 10, 50, 2)\n",
|
||||
"#setting.add_parameter('atr_ma_length', 10, 50, 2)\n",
|
||||
"#setting.add_parameter('rsi_length', 4, 50, 2)\n",
|
||||
"#setting.add_parameter('rsi_entry', 4, 30, 1)\n",
|
||||
"setting.add_parameter('boll_window', 4, 50, 2)\n",
|
||||
"#setting.add_parameter('boll_dev', 4, 50, 2)\n",
|
||||
"setting.add_parameter('cci_window', 4, 50, 2)\n",
|
||||
"setting.add_parameter('atr_window', 4, 50, 2)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"local_setting = setting.generate_setting()\n",
|
||||
"total_sample = len(local_setting)\n",
|
||||
"print(\"数据总体:\",total_sample)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"setting_names = random.choice(local_setting).keys()\n",
|
||||
"setting_names"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def parameter_generate():\n",
|
||||
" setting_param = list(random.choice(local_setting).values())\n",
|
||||
" return setting_param"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"parameter_generate()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"setting=dict(zip(setting_names,parameter_generate()))\n",
|
||||
"setting"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def object_func(strategy_avg):\n",
|
||||
" \"\"\"\"\"\"\n",
|
||||
" return run_backtesting(tuple(strategy_avg))\n",
|
||||
" #return run_backtesting(strategy_avg)\n",
|
||||
" \n",
|
||||
"\n",
|
||||
"@lru_cache(maxsize=1000000)\n",
|
||||
"def run_backtesting(strategy_avg):\n",
|
||||
" # 创建回测引擎对象\n",
|
||||
" engine = BacktestingEngine()\n",
|
||||
" engine.set_parameters(\n",
|
||||
" vt_symbol=\"IF88.CFFEX\",\n",
|
||||
" interval=\"1m\",\n",
|
||||
" start=datetime(2016, 1, 1),\n",
|
||||
" end=datetime(2019, 1,1),\n",
|
||||
" rate=0.3/10000,\n",
|
||||
" slippage=0.2,\n",
|
||||
" size=300,\n",
|
||||
" pricetick=0.2,\n",
|
||||
" capital=1_000_000,\n",
|
||||
" )\n",
|
||||
" \n",
|
||||
" setting=dict(zip(setting_names,strategy_avg))\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" #加载策略 \n",
|
||||
" #engine.initStrategy(TurtleTradingStrategy, setting)\n",
|
||||
" engine.add_strategy(BollChannelStrategy, setting)\n",
|
||||
" engine.load_data()\n",
|
||||
" engine.run_backtesting()\n",
|
||||
" engine.calculate_result()\n",
|
||||
" result = engine.calculate_statistics(output=False)\n",
|
||||
"\n",
|
||||
" return_drawdown_ratio = round(result['return_drawdown_ratio'],2) #收益回撤比\n",
|
||||
" sharpe_ratio= round(result['sharpe_ratio'],2) #夏普比率\n",
|
||||
" return return_drawdown_ratio , sharpe_ratio"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"object_func(parameter_generate())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"target_names = [\"return_drawdown_ratio\" , \"sharpe_ratio\"]\n",
|
||||
"def show_result(hof):\n",
|
||||
" for i in range(len(hof)):\n",
|
||||
" solution = hof[i] \n",
|
||||
" parameter=dict(zip(setting_names,solution))\n",
|
||||
" result=dict(zip(target_names,list(object_func(solution))))\n",
|
||||
" print({**parameter, **result})"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from time import time\n",
|
||||
"#设置优化方向:最大化收益回撤比,最大化夏普比率\n",
|
||||
"creator.create(\"FitnessMax\", base.Fitness, weights=(1.0, 1.0)) # 1.0 求最大值;-1.0 求最小值\n",
|
||||
"creator.create(\"Individual\", list, fitness=creator.FitnessMax)\n",
|
||||
"\n",
|
||||
"def optimize(population=None):\n",
|
||||
" \"\"\"\"\"\" \n",
|
||||
" start = time() \n",
|
||||
" toolbox = base.Toolbox() \n",
|
||||
"\n",
|
||||
" # 初始化 \n",
|
||||
" toolbox.register(\"individual\", tools.initIterate, creator.Individual,parameter_generate) \n",
|
||||
" toolbox.register(\"population\", tools.initRepeat, list, toolbox.individual) \n",
|
||||
" toolbox.register(\"mate\", tools.cxTwoPoint) \n",
|
||||
" toolbox.register(\"mutate\", tools.mutUniformInt,low = 4,up = 40,indpb=1) \n",
|
||||
" toolbox.register(\"evaluate\", object_func) \n",
|
||||
" toolbox.register(\"select\", tools.selNSGA2) \n",
|
||||
" pool = multiprocessing.Pool(multiprocessing.cpu_count())\n",
|
||||
" toolbox.register(\"map\", pool.map)\n",
|
||||
" #toolbox.register(\"map\", futures.map)\n",
|
||||
" \n",
|
||||
" \n",
|
||||
" #遗传算法参数设置\n",
|
||||
" MU = 80 #设置每一代选择的个体数\n",
|
||||
" LAMBDA = 100 #设置每一代产生的子女数\n",
|
||||
" POP=100\n",
|
||||
" CXPB, MUTPB, NGEN = 0.95, 0.05,30 #分别为种群内部个体的交叉概率、变异概率、产生种群代数\n",
|
||||
" \n",
|
||||
" if population==None:\n",
|
||||
" LAMBDA = POP = int(pow(total_sample, 1/2.7))\n",
|
||||
" MU = int(0.8*POP) \n",
|
||||
" \n",
|
||||
" pop = toolbox.population(POP) #设置族群里面的个体数量\n",
|
||||
" hof = tools.ParetoFront() #解的集合:帕累托前沿(非占优最优集)\n",
|
||||
"\n",
|
||||
" stats = tools.Statistics(lambda ind: ind.fitness.values)\n",
|
||||
" np.set_printoptions(suppress=True) #对numpy默认输出的科学计数法转换\n",
|
||||
" stats.register(\"mean\", np.mean, axis=0) #统计目标优化函数结果的平均值\n",
|
||||
" stats.register(\"std\", np.std, axis=0) #统计目标优化函数结果的标准差\n",
|
||||
" stats.register(\"min\", np.min, axis=0) #统计目标优化函数结果的最小值\n",
|
||||
" stats.register(\"max\", np.max, axis=0) #统计目标优化函数结果的最大值\n",
|
||||
" print(\"开始运行遗传算法,每代族群总数:%s, 优良品种筛选个数:%s,迭代次数:%s,交叉概率:%s,突变概率:%s\" %(POP,MU,NGEN,CXPB,MUTPB))\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" #运行算法\n",
|
||||
" algorithms.eaMuPlusLambda(pop, toolbox, MU, LAMBDA, CXPB, MUTPB, NGEN, stats,\n",
|
||||
" halloffame=hof) #esMuPlusLambda是一种基于(μ+λ)选择策略的多目标优化分段遗传算法\n",
|
||||
"\n",
|
||||
" end = time()\n",
|
||||
" cost = int((end - start))\n",
|
||||
"\n",
|
||||
" print(\"遗传算法优化完成,耗时%s秒\"% (cost))\n",
|
||||
" print(\"输出帕累托前沿解集:\")\n",
|
||||
" show_result(hof)\n",
|
||||
" "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"scrolled": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"optimize()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
" MU = 80 #设置每一代选择的个体数\n",
|
||||
" POP = 100 #设置每一代产生的子女数\n",
|
||||
" CXPB, MUTPB, NGEN = 0.95, 0.05,20 \n",
|
||||
" print(\"开始运行遗传算法,每代族群总数:%s, 优良品种筛选个数:%s,迭代次数:%s,交叉概率:%s,突变概率:%s\" %(POP,MU,NGEN,CXPB,MUTPB))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.7.1"
|
||||
},
|
||||
"toc": {
|
||||
"base_numbering": 1,
|
||||
"nav_menu": {},
|
||||
"number_sections": true,
|
||||
"sideBar": true,
|
||||
"skip_h1_title": false,
|
||||
"title_cell": "Table of Contents",
|
||||
"title_sidebar": "Contents",
|
||||
"toc_cell": false,
|
||||
"toc_position": {},
|
||||
"toc_section_display": true,
|
||||
"toc_window_display": false
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
@ -1,189 +0,0 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import random\n",
|
||||
"import multiprocessing\n",
|
||||
"import numpy as np\n",
|
||||
"from deap import creator, base, tools, algorithms\n",
|
||||
"from vnpy.app.cta_strategy.backtesting import BacktestingEngine\n",
|
||||
"from boll_channel_strategy import BollChannelStrategy\n",
|
||||
"from datetime import datetime\n",
|
||||
"import multiprocessing #多进程\n",
|
||||
"from scoop import futures #多进程"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def parameter_generate():\n",
|
||||
" '''\n",
|
||||
" 根据设置的起始值,终止值和步进,随机生成待优化的策略参数\n",
|
||||
" '''\n",
|
||||
" parameter_list = []\n",
|
||||
" p1 = random.randrange(4,50,2) #布林带窗口\n",
|
||||
" p2 = random.randrange(4,50,2) #布林带通道阈值\n",
|
||||
" p3 = random.randrange(4,50,2) #CCI窗口\n",
|
||||
" p4 = random.randrange(18,40,2) #ATR窗口 \n",
|
||||
"\n",
|
||||
" parameter_list.append(p1)\n",
|
||||
" parameter_list.append(p2)\n",
|
||||
" parameter_list.append(p3)\n",
|
||||
" parameter_list.append(p4)\n",
|
||||
"\n",
|
||||
" return parameter_list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def object_func(strategy_avg):\n",
|
||||
" \"\"\"\n",
|
||||
" 本函数为优化目标函数,根据随机生成的策略参数,运行回测后自动返回2个结果指标:收益回撤比和夏普比率\n",
|
||||
" \"\"\"\n",
|
||||
" # 创建回测引擎对象\n",
|
||||
" engine = BacktestingEngine()\n",
|
||||
" engine.set_parameters(\n",
|
||||
" vt_symbol=\"IF88.CFFEX\",\n",
|
||||
" interval=\"1m\",\n",
|
||||
" start=datetime(2018, 9, 1),\n",
|
||||
" end=datetime(2019, 1,1),\n",
|
||||
" rate=0,\n",
|
||||
" slippage=0,\n",
|
||||
" size=300,\n",
|
||||
" pricetick=0.2,\n",
|
||||
" capital=1_000_000,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" setting = {'boll_window': strategy_avg[0], #布林带窗口\n",
|
||||
" 'boll_dev': strategy_avg[1], #布林带通道阈值\n",
|
||||
" 'cci_window': strategy_avg[2], #CCI窗口\n",
|
||||
" 'atr_window': strategy_avg[3],} #ATR窗口 \n",
|
||||
"\n",
|
||||
" #加载策略 \n",
|
||||
" #engine.initStrategy(TurtleTradingStrategy, setting)\n",
|
||||
" engine.add_strategy(BollChannelStrategy, setting)\n",
|
||||
" engine.load_data()\n",
|
||||
" engine.run_backtesting()\n",
|
||||
" engine.calculate_result()\n",
|
||||
" result = engine.calculate_statistics(Output=False)\n",
|
||||
"\n",
|
||||
" return_drawdown_ratio = round(result['return_drawdown_ratio'],2) #收益回撤比\n",
|
||||
" sharpe_ratio= round(result['sharpe_ratio'],2) #夏普比率\n",
|
||||
" return return_drawdown_ratio , sharpe_ratio"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"\n",
|
||||
"#设置优化方向:最大化收益回撤比,最大化夏普比率\n",
|
||||
"creator.create(\"FitnessMulti\", base.Fitness, weights=(1.0, 1.0)) # 1.0 求最大值;-1.0 求最小值\n",
|
||||
"creator.create(\"Individual\", list, fitness=creator.FitnessMulti)\n",
|
||||
"\n",
|
||||
"def optimize():\n",
|
||||
" \"\"\"\"\"\" \n",
|
||||
" toolbox = base.Toolbox() #Toolbox是deap库内置的工具箱,里面包含遗传算法中所用到的各种函数\n",
|
||||
"\n",
|
||||
" # 初始化 \n",
|
||||
" toolbox.register(\"individual\", tools.initIterate, creator.Individual,parameter_generate) # 注册个体:随机生成的策略参数parameter_generate() \n",
|
||||
" toolbox.register(\"population\", tools.initRepeat, list, toolbox.individual) #注册种群:个体形成种群 \n",
|
||||
" toolbox.register(\"mate\", tools.cxTwoPoint) #注册交叉:两点交叉 \n",
|
||||
" toolbox.register(\"mutate\", tools.mutUniformInt,low = 4,up = 40,indpb=0.6) #注册变异:随机生成一定区间内的整数\n",
|
||||
" toolbox.register(\"evaluate\", object_func) #注册评估:优化目标函数object_func() \n",
|
||||
" toolbox.register(\"select\", tools.selNSGA2) #注册选择:NSGA-II(带精英策略的非支配排序的遗传算法)\n",
|
||||
" #pool = multiprocessing.Pool()\n",
|
||||
" #toolbox.register(\"map\", pool.map)\n",
|
||||
" #toolbox.register(\"map\", futures.map)\n",
|
||||
"\n",
|
||||
" #遗传算法参数设置\n",
|
||||
" MU = 40 #设置每一代选择的个体数\n",
|
||||
" LAMBDA = 160 #设置每一代产生的子女数\n",
|
||||
" pop = toolbox.population(400) #设置族群里面的个体数量\n",
|
||||
" CXPB, MUTPB, NGEN = 0.5, 0.35,40 #分别为种群内部个体的交叉概率、变异概率、产生种群代数\n",
|
||||
" hof = tools.ParetoFront() #解的集合:帕累托前沿(非占优最优集)\n",
|
||||
"\n",
|
||||
" #解的集合的描述统计信息\n",
|
||||
" #集合内平均值,标准差,最小值,最大值可以体现集合的收敛程度\n",
|
||||
" #收敛程度低可以增加算法的迭代次数\n",
|
||||
" stats = tools.Statistics(lambda ind: ind.fitness.values)\n",
|
||||
" np.set_printoptions(suppress=True) #对numpy默认输出的科学计数法转换\n",
|
||||
" stats.register(\"mean\", np.mean, axis=0) #统计目标优化函数结果的平均值\n",
|
||||
" stats.register(\"std\", np.std, axis=0) #统计目标优化函数结果的标准差\n",
|
||||
" stats.register(\"min\", np.min, axis=0) #统计目标优化函数结果的最小值\n",
|
||||
" stats.register(\"max\", np.max, axis=0) #统计目标优化函数结果的最大值\n",
|
||||
"\n",
|
||||
" #运行算法\n",
|
||||
" algorithms.eaMuPlusLambda(pop, toolbox, MU, LAMBDA, CXPB, MUTPB, NGEN, stats,\n",
|
||||
" halloffame=hof) #esMuPlusLambda是一种基于(μ+λ)选择策略的多目标优化分段遗传算法\n",
|
||||
"\n",
|
||||
" return pop"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"optimize()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.7.1"
|
||||
},
|
||||
"toc": {
|
||||
"base_numbering": 1,
|
||||
"nav_menu": {},
|
||||
"number_sections": true,
|
||||
"sideBar": true,
|
||||
"skip_h1_title": false,
|
||||
"title_cell": "Table of Contents",
|
||||
"title_sidebar": "Contents",
|
||||
"toc_cell": false,
|
||||
"toc_position": {},
|
||||
"toc_section_display": true,
|
||||
"toc_window_display": false
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
@ -1,65 +0,0 @@
|
||||
from time import time
|
||||
|
||||
import rqdatac as rq
|
||||
|
||||
from vnpy.trader.object import BarData
|
||||
from vnpy.trader.constant import Exchange, Interval
|
||||
from vnpy.trader.database import database_manager
|
||||
|
||||
USERNAME = ""
|
||||
PASSWORD = ""
|
||||
FIELDS = ["open", "high", "low", "close", "volume"]
|
||||
|
||||
rq.init(USERNAME, PASSWORD, ("rqdatad-pro.ricequant.com", 16011))
|
||||
|
||||
|
||||
def generate_bar_from_row(row, symbol, exchange):
|
||||
""""""
|
||||
bar = BarData(
|
||||
symbol=symbol,
|
||||
exchange=Exchange(exchange),
|
||||
interval=Interval.MINUTE,
|
||||
open_price=row["open"],
|
||||
high_price=row["high"],
|
||||
low_price=row["low"],
|
||||
close_price=row["close"],
|
||||
volume=row["volume"],
|
||||
datetime=row.name.to_pydatetime(),
|
||||
gateway_name="DB"
|
||||
)
|
||||
return bar
|
||||
|
||||
|
||||
def download_minute_bar(vt_symbol):
|
||||
"""下载某一合约的分钟线数据"""
|
||||
print(f"开始下载合约数据{vt_symbol}")
|
||||
symbol, exchange = vt_symbol.split(".")
|
||||
|
||||
start = time()
|
||||
|
||||
df = rq.get_price(
|
||||
symbol,
|
||||
frequency="1m",
|
||||
fields=FIELDS,
|
||||
start_date='20100416',
|
||||
end_date='20190416'
|
||||
)
|
||||
|
||||
bars = []
|
||||
for ix, row in df.iterrows():
|
||||
bar = generate_bar_from_row(row, symbol, exchange)
|
||||
bars.append(bar)
|
||||
|
||||
database_manager.save_bar_data(bars)
|
||||
|
||||
end = time()
|
||||
cost = (end - start) * 1000
|
||||
|
||||
print(
|
||||
"合约%s的分钟K线数据下载完成%s - %s,耗时%s毫秒"
|
||||
% (symbol, df.index[0], df.index[-1], cost)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
download_minute_bar("IF88.CFFEX")
|
@ -1,27 +0,0 @@
|
||||
from vnpy.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting
|
||||
from vnpy.app.cta_strategy.strategies.atr_rsi_strategy import (
|
||||
AtrRsiStrategy,
|
||||
)
|
||||
from datetime import datetime
|
||||
|
||||
if __name__ == "__main__":
|
||||
engine = BacktestingEngine()
|
||||
engine.set_parameters(
|
||||
vt_symbol="IF88.CFFEX",
|
||||
interval="1m",
|
||||
start=datetime(2019, 1, 1),
|
||||
end=datetime(2019, 4, 30),
|
||||
rate=0.3 / 10000,
|
||||
slippage=0.2,
|
||||
size=300,
|
||||
pricetick=0.2,
|
||||
capital=1_000_000,
|
||||
)
|
||||
engine.add_strategy(AtrRsiStrategy, {})
|
||||
|
||||
setting = OptimizationSetting()
|
||||
setting.set_target("sharpe_ratio")
|
||||
setting.add_parameter("atr_length", 3, 39, 1)
|
||||
setting.add_parameter("atr_ma_length", 10, 30, 1)
|
||||
|
||||
engine.run_ga_optimization(setting)
|
@ -1,170 +0,0 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"#%%\n",
|
||||
"from vnpy.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting\n",
|
||||
"from vnpy.app.cta_strategy.strategies.atr_rsi_strategy import (\n",
|
||||
" AtrRsiStrategy,\n",
|
||||
")\n",
|
||||
"from datetime import datetime"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"#%%\n",
|
||||
"engine = BacktestingEngine()\n",
|
||||
"engine.set_parameters(\n",
|
||||
" vt_symbol=\"IF88.CFFEX\",\n",
|
||||
" interval=\"1m\",\n",
|
||||
" start=datetime(2019, 1, 1),\n",
|
||||
" end=datetime(2019, 4, 30),\n",
|
||||
" rate=0.3/10000,\n",
|
||||
" slippage=0.2,\n",
|
||||
" size=300,\n",
|
||||
" pricetick=0.2,\n",
|
||||
" capital=1_000_000,\n",
|
||||
")\n",
|
||||
"engine.add_strategy(AtrRsiStrategy, {})"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"scrolled": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"#%%\n",
|
||||
"engine.load_data()\n",
|
||||
"engine.run_backtesting()\n",
|
||||
"df = engine.calculate_result()\n",
|
||||
"engine.calculate_statistics()\n",
|
||||
"engine.show_chart()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"2019-05-03 16:19:04.193703\t开始运行遗传算法,每代族群总数:11, 优良品种筛选个数:8,迭代次数:30,交叉概率:0.95,突变概率:0.050000000000000044\n",
|
||||
"gen\tnevals\tmean \tstd \tmin \tmax \n",
|
||||
"0 \t11 \t[0.58423524]\t[0.30377007]\t[0.13231977]\t[1.2382818]\n",
|
||||
"1 \t11 \t[0.90248989]\t[0.15747112]\t[0.68707859]\t[1.2382818]\n",
|
||||
"2 \t11 \t[1.09406088]\t[0.18860523]\t[0.86284921]\t[1.46762684]\n",
|
||||
"3 \t11 \t[1.21413386]\t[0.12138014]\t[1.02072108]\t[1.46762684]\n",
|
||||
"4 \t11 \t[1.29561806]\t[0.09930932]\t[1.2382818] \t[1.46762684]\n",
|
||||
"5 \t11 \t[1.41029058]\t[0.09930932]\t[1.2382818] \t[1.46762684]\n",
|
||||
"6 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"7 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"8 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"9 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"10 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"11 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"12 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"13 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"14 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"15 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"16 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"17 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"18 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"19 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"20 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"21 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"22 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"23 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"24 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"25 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"26 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"27 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"28 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"29 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"30 \t11 \t[1.46762684]\t[0.] \t[1.46762684]\t[1.46762684]\n",
|
||||
"2019-05-03 16:19:58.256354\t遗传算法优化完成,耗时54秒\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"[({'atr_length': 38, 'atr_ma_length': 25}, 1.4676268402266743)]"
|
||||
]
|
||||
},
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"setting = OptimizationSetting()\n",
|
||||
"setting.set_target(\"sharpe_ratio\")\n",
|
||||
"setting.add_parameter(\"atr_length\", 3, 39, 1)\n",
|
||||
"setting.add_parameter(\"atr_ma_length\", 10, 30, 1)\n",
|
||||
"\n",
|
||||
"engine.run_ga_optimization(setting)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"result = _"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(result)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.7.1"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
Loading…
Reference in New Issue
Block a user