forked from QuantFans/quantdigger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_strategy.py
More file actions
100 lines (83 loc) · 3.04 KB
/
Copy pathplot_strategy.py
File metadata and controls
100 lines (83 loc) · 3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# -*- coding: utf-8 -*-
# @file plot_strategy.py
# @brief 策略运行和图表展示
# @author wondereamer
# @version 0.2
# @date 2015-12-09
import six
from quantdigger import (
Strategy,
MA,
DateTimeSeries,
NumberSeries,
set_config,
set_symbols,
add_strategy,
run
)
class DemoStrategy(Strategy):
""" 策略A1 """
def on_init(self, ctx):
"""初始化数据"""
ctx.ma10 = MA(ctx.close, 10, 'ma10', 'y', 1)
ctx.ma20 = MA(ctx.close, 20, 'ma20', 'b', 1)
ctx.dt = DateTimeSeries()
ctx.month_price = NumberSeries()
def on_bar(self, ctx):
ctx.dt.update(ctx.datetime)
if ctx.dt[1].month != ctx.dt[0].month:
ctx.month_price.update(ctx.close)
if ctx.curbar > 20:
if ctx.pos() == 0 and ctx.ma10[2] < ctx.ma20[2] and ctx.ma10[1] > ctx.ma20[1]:
ctx.buy(ctx.close, 1)
ctx.plot_text("buy", 1, ctx.curbar, ctx.close, "buy", 'black', 15)
elif ctx.pos() > 0 and ctx.ma10[2] > ctx.ma20[2] and \
ctx.ma10[1] < ctx.ma20[1]:
ctx.plot_text("sell", 1, ctx.curbar, ctx.close, "sell", 'blue', 15)
ctx.sell(ctx.close, ctx.pos())
ctx.plot_line("month_price", 1, ctx.curbar, ctx.month_price, 'y--', lw=2)
return
def on_exit(self, ctx):
return
class DemoStrategy2(Strategy):
""" 策略A2 """
def on_init(self, ctx):
"""初始化数据"""
ctx.ma50 = MA(ctx.close, 50, 'ma50', 'y', 2)
ctx.ma100 = MA(ctx.close, 100, 'ma100', 'black', 2)
def on_symbol(self, ctx):
pass
def on_bar(self, ctx):
if ctx.curbar > 100:
if ctx.pos() == 0 and ctx.ma50[2] < ctx.ma100[2] and ctx.ma50[1] > ctx.ma100[1]:
ctx.buy(ctx.close, 1)
elif ctx.pos() > 0 and ctx.ma50[2] > ctx.ma100[2] and \
ctx.ma50[1] < ctx.ma100[1]:
ctx.sell(ctx.close, ctx.pos())
return
def on_exit(self, ctx):
return
if __name__ == '__main__':
import timeit
start = timeit.default_timer()
set_config({'source': 'csv'})
set_symbols(['BB.SHFE-1.Day'])
profile = add_strategy([DemoStrategy('A1'), DemoStrategy2('A2')],
{'capital': 50000.0, 'ratio': [0.5, 0.5]})
run()
stop = timeit.default_timer()
print("运行耗时: %d秒" % ((stop - start)))
# 绘制k线,交易信号线
from quantdigger.digger import finance, plotting
s = 0
# 绘制策略A1, 策略A2, 组合的资金曲线
curve0 = finance.create_equity_curve(profile.all_holdings(0))
curve1 = finance.create_equity_curve(profile.all_holdings(1))
curve = finance.create_equity_curve(profile.all_holdings())
plotting.plot_strategy(profile.data(), profile.technicals(0),
profile.deals(0), curve0.equity.values,
profile.marks(0))
# 绘制净值曲线
plotting.plot_curves([curve.networth])
# 打印统计信息
print(finance.summary_stats(curve, 252))