import backtrader as bt
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro.broker.set_cash(100000.00) # 设置初始资金金额
初始资金 = cerebro.broker.getvalue()
print(f'初始资金:{初始资金}')
cerebro.run()
期末资金 = cerebro.broker.getvalue()
print(f'期末资金:{期末资金}')
3:加入交易数据
# -*- coding:utf-8 -*-
import backtrader as bt
#####################
import pandas as pd
import os
import datetime
import matplotlib.pyplot as plt
#####################
class AceStrategy(bt.Strategy):
pass
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro = bt.Cerebro(stdstats=False)
# cerebro.addobserver(bt.observers.Broker)
# cerebro.addobserver(bt.observers.Trades)
# cerebro.addobserver(bt.observers.BuySell)
# cerebro.addobserver(bt.observers.DrawDown)
# cerebro.addobserver(bt.observers.Value)
# cerebro.addobserver(bt.observers.TimeReturn)
cerebro.broker.set_cash(100000.00) # 设置初始资金金额
初始资金 = cerebro.broker.getvalue()
print(f'初始资金:{初始资金}')
#####################
数据地址= os.path.join(os.path.join(os.getcwd(),"数据地址"),"002342.csv") #本次是单个,未来可以用循环遍历,列表表达式用if 过滤CSV
# print(数据地址)
data =pd.read_csv(数据地址,index_col ="date",parse_dates = True)
# data.index=pd.to_datetime(data.date)
# data.drop(columns=["date"],inplace=True)
# print(data)
日线 = bt.feeds.PandasData( dataname=data,
fromdate=datetime.datetime(2020, 1, 1),
todate=datetime.datetime(2020,10, 18)
)
cerebro.adddata(日线)
cerebro.addstrategy(AceStrategy)
#####################
cerebro.run()
期末资金 = cerebro.broker.getvalue()
print(f'期末资金:{期末资金}')
#####################
cerebro.plot(style = "candle")
#####################
4:创建策略_看顺序
# -*- coding:utf-8 -*-
import backtrader as bt
#####################
import pandas as pd
import os
import datetime
class AceStrategy(bt.Strategy):
params = (
('maperiod',20),
)
def log(self):
pass
def __init__(self):
print(f'init___{self.datas[0].datetime.date(0)}')
# self.dataclose = self.datas[0].close
self.sma_5 = bt.indicators.SimpleMovingAverage(
self.data0.close, period=self.params.maperiod)
def start(self):
print(f"start!___{self.datas[0].datetime.date(0)}")
def prenext(self):
print(f"prenext___{self.datas[0].datetime.date(0)}")
def nextstart(self):
print(f'nextstart___{self.datas[0].datetime.date(0)}')
def notify_order(self):
pass
def notify_trade(self):
pass
def next(self):
print(f'next___{self.datas[0].datetime.date(0)}, ma_5:{round(self.sma_5[0],2)}, 前一天MA_5:{round(self.sma_5[-1],2)}')
def stop(self):
print(f"stop___{self.datas[0].datetime.date(0)}")
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro.broker.set_cash(100000.00) # 设置初始资金金额
初始资金 = cerebro.broker.getvalue()
print(f'初始资金:{初始资金}')
数据地址= os.path.join(os.path.join(os.getcwd(),"数据地址"),"002342.csv") #本次是单个,未来可以用循环遍历,列表表达式用if 过滤CSV
# print(数据地址)
data =pd.read_csv(数据地址)
data.index=pd.to_datetime(data.date)
data.drop(columns=["date"],inplace=True)
# print(data)
日线 = bt.feeds.PandasData( dataname=data,
fromdate=datetime.datetime(2020, 9, 10),
todate=datetime.datetime(2020, 10, 20)
)
cerebro.adddata(日线)
cerebro.addstrategy(AceStrategy)
cerebro.run()
期末资金 = cerebro.broker.getvalue()
print(f'期末资金:{期末资金}')
# cerebro.plot()
5:第一个简单策略
# -*- coding:utf-8 -*-
import backtrader as bt
#####################
import pandas as pd
import os
import datetime
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
class AceStrategy(bt.Strategy):
params = (
('maperiod_3', 3),
('maperiod_5',5)
)
def __init__(self):
print(f'init___{self.datas[0].datetime.date(0)}')
self.dataclose = self.datas[0].close
self.sma_3 = bt.indicators.SimpleMovingAverage(
self.datas[0], period=self.params.maperiod_3)
self.sma_5 = bt.indicators.SimpleMovingAverage(
self.datas[0], period=self.params.maperiod_5)
self.order = None
# self.sma_3.plotinfo.plot = False
# self.sma_5.plotinfo.plot = False
def start(self):
pass
def prenext(self):
pass
def nextstart(self):
pass
# def notify_order(self, order):
# if order.status in [order.Submitted, order.Accepted]:
# return
# if order.status in [order.Completed]:
# pass
# self.bar_executed = len(self)
# elif order.status in [order.Canceled, order.Margin, order.Rejected]:
# pass
# self.order = None # 无挂起
def next(self):
# if self.order:
# return
if not self.position:
if self.sma_3[0]>self.sma_5[0]:
self.order = self.buy(size=1000)
print(f"{self.datas[0].datetime.date(0)},买入!价格为{self.dataclose[0]}")
else:
if self.sma_3[0]<self.sma_5[0]:
self.order = self.sell(size=1000)
print(f"{self.datas[0].datetime.date(0)},卖出!价格为{self.dataclose[0]}")
def stop(self):
pass
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro.broker.set_cash(100000.00) # 设置初始资金金额
cerebro = bt.Cerebro(stdstats=False)
cerebro.addobserver(bt.observers.Broker)
# cerebro.addobserver(bt.observers.Trades)
cerebro.addobserver(bt.observers.BuySell)
# cerebro.addobserver(bt.observers.DrawDown)
cerebro.addobserver(bt.observers.Value)
# cerebro.addobserver(bt.observers.TimeReturn)
初始资金 = cerebro.broker.getvalue()
print(f'初始资金:{初始资金}')
数据地址= os.path.join(os.path.join(os.getcwd(),"数据地址"),"002342.csv") #本次是单个,未来可以用循环遍历,列表表达式用if 过滤CSV
# print(数据地址)
data =pd.read_csv(数据地址)
data.index=pd.to_datetime(data.date)
data.drop(columns=["date"],inplace=True)
# print(data)
日线 = bt.feeds.PandasData( dataname=data,
fromdate=datetime.datetime(2020, 1, 1),
todate=datetime.datetime(2020, 10, 12)
)
cerebro.adddata(日线)
cerebro.addstrategy(AceStrategy)
cerebro.run()
期末资金 = cerebro.broker.getvalue()
print(f'期末资金:{期末资金}')
cerebro.plot(style = "candle")
6:编写指标_平台突破
查看代码
# -*- coding:utf-8 -*-
import backtrader as bt
#####################
import pandas as pd
import os
import datetime
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
class Platform(bt.Indicator):
lines = ("上轨","下轨")
def __init__(self):
self.addminperiod(6) #5天的平台
def next(self):
self.上轨[0]= max(self.data.high.get(ago = -1,size =5))
self.下轨[0] = min(self.data.low.get(ago=-1, size=5))
class AceStrategy(bt.Strategy):
def __init__(self):
self.上下轨 = Platform(self.data)
self.买入信号 = bt.indicators.CrossOver(self.datas[0].close,self.上下轨.上轨)
self.卖出信号 = bt.indicators.CrossDown(self.data.close, self.上下轨.下轨)
# self.order = None
self.买入信号.plotinfo.plot = False
self.卖出信号.plotinfo.plot = False
self.上下轨.plotinfo.plotmaster = self.data #类似通达信的 是否在主图显示
# self.卖出信号.plotinfo.plot = False
def start(self):
pass
def prenext(self):
pass
def nextstart(self):
pass
def next(self):
# if self.order:
# return
if not self.position:
if self.买入信号[0] ==1:
self.order = self.buy(size=1000)
print(f"{self.datas[0].datetime.date(0)},买入!价格为{self.data.close[0]}")
else:
if self.卖出信号[0] == 1:
self.order = self.sell(size=1000)
print(f"{self.datas[0].datetime.date(0)},卖出!价格为{self.data.close[0]}")
pass
def stop(self):
if self.position:
self.order = self.sell(size=1000)
print(f"{self.datas[0].datetime.date(0)},卖出!价格为{self.data.close[0]}")
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro.broker.set_cash(100000.00) # 设置初始资金金额
初始资金 = cerebro.broker.getvalue()
print(f'初始资金:{初始资金}')
数据地址= os.path.join(os.path.join(os.getcwd(),"数据地址"),"002342.csv") #本次是单个,未来可以用循环遍历,列表表达式用if 过滤CSV
# print(数据地址)
data =pd.read_csv(数据地址)
data.index=pd.to_datetime(data.date)
data.drop(columns=["date"],inplace=True)
print(data)
日线 = bt.feeds.PandasData( dataname=data,
fromdate=datetime.datetime(2020, 1, 1),
todate=datetime.datetime(2020, 10, 12)
)
cerebro.adddata(日线)
cerebro.addstrategy(AceStrategy)
cerebro.run()
期末资金 = cerebro.broker.getvalue()
print(f'期末资金:{期末资金}')
cerebro.plot(style = "candle")
7:双周期
import backtrader as bt
import pandas as pd
import os
import datetime
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHer']
class Platform(bt.Indicator):
lines = ("上轨","下轨")
params = (
("周期" , 5),
)
def __init__(self):
self.addminperiod(self.params.周期 + 1)
def next(self):
self.上轨[0] = max(self.data.high.get(ago=-1, size=self.params.周期))
self.下轨[0] = min(self.data.low.get(ago=-1, size=self.params.周期))
class AceStrategy(bt.Strategy):
params = (
("周期", 5),
)
def __init__(self):
self.上下轨 = Platform(self.data1 ,周期= self.params.周期)
self.上下轨 = self.上下轨()
self.上下轨.plotinfo.plotmaster = self.data0
self.买入信号 = bt.indicators.CrossOver(self.data0.close,self.上下轨.上轨)
self.卖出信号 = bt.indicators.CrossDown(self.data0.close,self.上下轨.下轨)
self.买入信号.plotinfo.plot = False
self.卖出信号.plotinfo.plot = False
def start(self):
pass
def prenext(self):
print(f'数据准备时间:{self.data0.datetime.datetime(0)}')
def nextstart(self):
pass
def next(self):
# # if self.order:
# # return
if not self.position:
if self.买入信号[0] ==1:
self.order = self.buy(size=1000)
print(f"{self.data1.datetime.date(0)},买入!价格为{self.data0.close[0]}")
else:
if self.卖出信号[0] == 1:
self.order = self.sell(size=1000)
print(f"{self.data1.datetime.date(0)},卖出!价格为{self.data0.close[0]}")
# pass
def stop(self):
if self.position:
self.order = self.sell(size=1000)
print(f"{self.datas[0].datetime.date(0)},卖出!价格为{self.data.close[0]}")
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro.broker.set_cash(100000.0)
数据地址= os.path.join(os.path.join(os.getcwd(),"数据地址"),"002342_30M.csv")
data = pd.read_csv(数据地址,index_col = "date",parse_dates=True)
print(data)
三十分钟线 = bt.feeds.PandasData(dataname=data,
fromdate = datetime.datetime(2020,3,1),
todate = datetime.datetime(2020,10,16),
timeframe = bt.TimeFrame.Minutes,
compression = 30
)
cerebro.adddata(三十分钟线) #self.data
cerebro.resampledata(三十分钟线,timeframe = bt.TimeFrame.Days) #self.data1
cerebro.addstrategy(AceStrategy)
cerebro.run()
期末资金 = cerebro.broker.getvalue()
print(f'期末资金:{期末资金}')
cerebro.plot(style = "candle")
标签:__,self,cerebro,datetime,bt,设置,data,初始,资金 From: https://www.cnblogs.com/lianshanspeak/p/18108142