1.环境安装:
在backtrader目录下,新建文件夹,并且命名为juexing2020.com
下载download.py和interface.py文件,并保存到juexing2020.com文件夹
2.实时数据回测
运行download.py:从服务端实时下载股票交易数据,以csv格式保存数据到本地目录
运行backtrader,加载csv数据,进行股票实时回测
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 4 16:20:54 2020
文件名:download
@作者: juexing2020
@微信号:sleeping2020
@博客:https://blog.csdn.net/dreamchina8888
@网站地址:www.juexing2020.com
如果需要正式的授权码,那么请加微信联系!
"""
from interface import StockData
class Download():
def downloadRealTimeData():
filePath='..\\datas\\'#下载数据存储目录
stockCodeList=['000001.sz']#股票代码:股票代码.市场(沪市sh,深市sz)
start_date='2020-06-03'
end_date='2020-12-04'
auth_code='juexing2020.com' #测试的授权码
StockData.getRealTimeData(filePath,auth_code,stockCodeList,start_date,end_date)
if __name__=='__main__':
while 1==1:
Download.downloadRealTimeData()
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 4 16:20:54 2020
文件名:interface.py
@作者: juexing2020
@微信号:sleeping2020
@博客:https://blog.csdn.net/dreamchina8888
@网站地址:www.juexing2020.com
如果需要正式的授权码,那么请加微信联系!
"""
import requests
import pandas as pd
import os
class StockData():
def getRealTimeData(filePath,authcode,stockcodeList,startdate=None,enddate=None):
print(filePath)
'''
获取实时数据
'''
for stockcode in stockcodeList:
filename=filePath+str(stockcode)
stockData=StockDataInterface()
id=StockDataInterface.getMaxId(filename)
dataframe=stockData.getStockDataRealTime(authcode,stockcode,id,startdate,enddate)
StockDataInterface.saveDataframeToCSV(filename,dataframe)
print('数据保存的路径',filename)
class StockDataInterface:
'''
获取实时交易数据接口
'''
def __init__(self):
#交易接口数据
self.domain_url='http://data.juexing2020.com:8888/api/v1/'
def getStockCode(self,auth_code):
url=str(self.domain_url)+"getStockCode?auth_code="+str(auth_code)
request = requests.get(url)
if request.status_code==200:
request.encoding = 'utf-8'
dataframe = pd.read_json(request.text)
return dataframe
print('获取数据失败,状态码是',request.status_code)
def getStockDataDay(self,auth_code,start_date,end_date,stock_code):
url=str(self.domain_url)+"getStockDataDay?auth_code="+str(auth_code)+"&start_date="+str(start_date)+"&end_date="+str(end_date)+"&stock_code="+str(stock_code)
print(url)
request = requests.get(url)
if request.status_code==200:
request.encoding = 'utf-8'
dataframe = pd.read_json(request.text)
return dataframe
print('获取数据失败,状态码是',request.status_code)
def getStockDataRealTime(self,auth_code,stock_code,id=None,start_date=None,end_date=None):
url=str(self.domain_url)+"getStockDataRealTime?auth_code="+str(auth_code)+"&stock_code="+str(stock_code)
if id !=None:
url=url+"&id="+str(id)
if start_date !=None:
url=url+"&start_date="+str(start_date)
if end_date !=None:
url=url+"&end_date="+str(end_date)
print(url)
request = requests.get(url)
if request.status_code==200:
request.encoding = 'utf-8'
dataframe = pd.read_json(request.text)
return dataframe
print('获取数据失败,状态码是',request.status_code)
def saveDataframeToCSV(file_name,data_frame):
'''
保存dataframe 到csv文件
'''
isFile=os.path.isfile(file_name)
if isFile:
data_frame.to_csv(file_name,encoding = 'gbk',mode='a', header=False)
else:
data_frame.to_csv(file_name,encoding = 'gbk')
def getMaxId(file_name):
'''
fname为所读xx.txt文件
输出为:文件第一行和最后一行
'''
maxid=-1
try:
with open(file_name, 'r') as f: #打开文件
lines = f.readlines() #读取所有行
if len(lines)>1:
last_line = lines[-1] #取最后一行
maxid=last_line.split(',')[1]
except Exception:
return maxid
return maxid
3.实时数据回测
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 4 16:20:54 2020
文件名:interface.py
@作者: juexing2020
@微信号:sleeping2020
@博客:https://blog.csdn.net/dreamchina8888
@网站地址:www.juexing2020.com
如果需要正式的授权码,那么请加微信联系!
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime
import backtrader as bt # 引入backtrader框架
class StrategyClass(bt.Strategy):
#'股票策略
def __init__(self):
pass
def next(self):
pass
class Backtrader():
def run(datapath):
cerebro=bt.Cerebro()
data=bt.feeds.GenericCSVData(dataname=datapath,
fromdate = datetime.datetime(2020, 6, 1),
todate = datetime.datetime(2020, 9, 1),
nullvalue=0.0,
dtformat=('%Y-%m-%d %H:%M:%S'),
datetime=2,
open=3,
high=5,
low=6,
close=12,
volume=7,
openinterest=-1)
cerebro.adddata(data)
cerebro.addstrategy(StrategyClass)
#设置金额,默认是100000
cerebro.broker.set_cash(200000)
cerebro.run(maxcpu=1)
cerebro.plot()
if __name__=='__main__':
datapath='.\\datas\\000001.sz'
Backtrader.run(datapath)