# coding:utf-8
from vnpy.app.cta_strategy.backtesting import BacktestingEngine
# 包的引入拖刃,先導入回測引擎
from vnpy.app.cta_strategy.strategies.boll_channel_strategy import BollChannelStrategy
# 再導入策略引擎
# 第一部分:標準的回測初始化參數設置
engine = BacktestingEngine()
engine.set_parameters(
vt_symbol="IF1909.CFFEX", # RB1910.SHFE
interval="1m",
start=datetime(2019, 6, 12),
end=datetime(2019, 7, 10),
rate=3.0/10000,
slippage=0.2,
size=300,
pricetick=0.2,
capital=1_000_000,
)
# 回測函數痪宰,可以用來重復使用
def run_backtesting(strategy_class, vt_symbol, interval, start, end, rate, slippage, size, pricetick, capital):
'''
回測函數再层,每添加一個策略就創(chuàng)建其BacktestingEngine對象。
:param strategy_class:
:param setting:
:param vt_symbol:
:param interval:
:param start:
:param end:
:param rate:
:param slippage:
:param size:
:param pricetick:
:param capital:
:return:
'''
engine = BacktestingEngine() # 回測引擎初始化
engine.set_parameters(
vt_symbol=vt_symbol,
interval=interval,
start=start,
end=end,
rate=rate,
slippage=slippage,
size=size,
pricetick=pricetick,
capital=capital
)
engine.load_data_by_mongo(DB_name='VnTrader_1Min_Db', symbol=vt_symbol.split('.')[0]) # 數據修改之后
# 這里要重點說一下了锌历,我在這里是做了修改,直接使用了本地的MongoDB數據庫峦筒。命名規(guī)則可以按照VnTrader_1Min_Db究西,數據庫中的集合名稱為IF1909(vt_symbol="IF1909.CFFEX"),即 " ."前面的部分物喷,針對不同的品種可以修改這里的內容
# engine.load_data() # 這里是源代碼里面的數據載入部分卤材,換成了我自己寫的部分
engine.add_strategy(strategy_class, {}) # 在引擎中創(chuàng)建策略對象
engine.run_backtesting() # 運行回測
df = engine.calculate_result() # 顯示回測結果
return df
df1 = run_backtesting(
strategy_class=BollChannelStrategy,
vt_symbol="IF1909.CFFEX",
interval="1m",
start=datetime(2019, 2, 12),
end=datetime(2019, 7, 10),
rate=0.3/10000,
slippage=0.2,
size=300,
pricetick=0.2,
capital=1_000_000,
)
print(df1)
def show_portafolio(df):
engine = BacktestingEngine()
engine.calculate_statistics(df)
engine.show_chart(df)
現(xiàn)在展示一下回測的統(tǒng)計結果和繪圖:
如下部分添加修改的代碼:
def load_data_by_mongo(self,DB_name,symbol):
self.output("開始加載歷史數據")
db_client = self.connect_mongodb()
# 對如下數據做修改
# db = db_client[self.db_name]
# cl = db[self.cl_name]
# db = db_client['VnTrader_1Min_Db']
# cl = db['IF1909']
db = db_client[DB_name]
cl = db[symbol]
if self.mode == BacktestingMode.BAR:
data_mode = BarData
else:
data_mode = TickData
flt = {'datetime': {'$gte': self.start, '$lt': self.end}}
db_cursor = cl.find(flt).sort('datetime')
print('如下這些內容為數據庫檢測操作!')
print('collection:',cl)
print('開始時間:',self.start)
print('結束時間:',self.end)
print('從MongoDB數據庫查找后的結果:',db_cursor)
for d in db_cursor:
data = self.generate_bar(d)
self.history_data.append(data)
self.output(f"歷史數據加載完成峦失,數據量:{len(self.history_data)}")