Ejemplo n.º 1
0
def runstrat():
    args = parse_args()

    # Create a cerebro entity
    cerebro = bt.Cerebro(stdstats=False)

    # Add a strategy
    cerebro.addstrategy(bt.Strategy)

    # Get the dates from the args
    fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
    todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')

    data = btfeeds.YahooFinanceData(dataname=args.data,
                                    fromdate=fromdate,
                                    todate=todate)

    # Add the resample data instead of the original
    cerebro.adddata(data)

    # Add a simple moving average if requirested
    cerebro.addindicator(btind.SMA, period=args.period)

    # Add a writer with CSV
    if args.writer:
        cerebro.addwriter(bt.WriterFile, csv=args.wrcsv)

    # Run over everything
    cerebro.run()

    # Plot if requested
    if args.plot:
        cerebro.plot(style='bar', numfigs=args.numfigs, volume=False)
Ejemplo n.º 2
0
    def get_data(self, stock):

        # single_data = yahoo.get_historical(self.fromdate, self.todate)
        # df = pd.DataFrame(single_data)
        # df = df.set_index('Date')
        # return(df)
        # Create a Data Feed
        data = btfeeds.YahooFinanceData(dataname=stock,
                                        fromdate=self.fromdate,
                                        todate=self.todate)

        return data
Ejemplo n.º 3
0
    args = parse_args()

    cerebro = bt.Cerebro()
    cerebro.addstrategy(SMACrossOver)
    cerebro.addsizer(bt.sizers.SizerFix, stake=5000)
    comminfo = bt.commissions.CommInfo_Stocks_Perc(commission=args.commperc,
                                                   percabs=True)

    cerebro.broker.addcommissioninfo(comminfo)

    fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
    todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')
    datapath = './raw/KBLI.JK.csv'
    data = btfeeds.YahooFinanceData(
        dataname=datapath,
        fromdate=fromdate,
        todate=todate,
        reverse=False
    )
    cerebro.adddata(data)

    # Set our desired cash start
    cerebro.broker.setcash(10000000.0)

    # Add a writer with CSV
    if args.writer:
        cerebro.addwriter(bt.WriterFile, csv=args.wrcsv)
    print('=======================')
    # Print out the starting conditions
    print('Starting Portfolio Value: {:20,.2f}'.format(cerebro.broker.getvalue()))

    # Run over everything
Ejemplo n.º 4
0
# https: // ithelp.ithome.com.tw/articles/10236961
# data feeds
import datetime
import backtrader as bt
import backtrader.feeds as btfeeds
# 這邊要自主增加哦
import math
# aaaaa
data = btfeeds.YahooFinanceData(dataname='MSFT',
                                fromdate=datetime.datetime(2019, 1, 1),
                                todate=datetime.datetime(2021, 4, 30))

print("data", data)

# sma cross strategy


class SmaCross(bt.Strategy):
    # 交易紀錄
    def log(self, txt, dt=None):
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    # 設定交易參數
    params = dict(ma_period_short=5, ma_period_long=10)

    def __init__(self):
        # 均線交叉策略
        sma1 = bt.ind.SMA(period=self.p.ma_period_short)
        sma2 = bt.ind.SMA(period=self.p.ma_period_long)
        self.crossover = bt.ind.CrossOver(sma1, sma2)
Ejemplo n.º 5
0
#Cerebro is seen as the link between the strategy and the feed
cerebro = bt.Cerebro(stdstats = False)

# I downloaded and pasrsed TSLA data from Yahoo Finance 
#and converted it into a feed for backtrader
data = btfeeds.YahooFinanceData(
    dataname='TSLA',
    #start date
    fromdate=datetime.datetime(2019, 2, 11),
    #end date
    todate=datetime.datetime(2020, 2, 10),
    #all null values are assigned zeros
    nullvalue=0.0,
    # formatting of the date
    dtformat=('%Y-%m-%d'),

    datetime=0,
    high=2,
    low=3,
    open=1,
    close=4,
    volume=5,
    #open interest is not in the csv file so we use -1 to say it's not there
    openinterest=-1
)

size =(16,8)
#setting initial investment
cerebro.broker.set_cash(100000)

# adding the data to cerebro
Ejemplo n.º 6
0
    def next(self):
        if self.rsi > self.p.upper and self.position:
            self.sell()
        elif self.rsi < self.p.lower and not self.position:
            self.buy()

    def stop(self):
        print('period: %s, upper: %s, lower: %s,final_value: %.2f ' %
              (self.p.period, self.p.upper, self.p.lower,
               self.broker.getvalue()))


if __name__ == "__main__":

    cerebro = bt.Cerebro()
    data = btfeeds.YahooFinanceData(dataname='AAPL',
                                    fromdate=datetime.datetime(2019, 1, 1),
                                    todate=datetime.datetime(2019, 12, 31))
    cerebro.adddata(data)

    cerebro.addstrategy(RSI_Sta)
    # cerebro.optstrategy(
    #     RSI_Sta,
    #     period = range(6,16),
    #     upper = range(70,91),
    #     lower = range(10,31)
    # )
    #
    cerebro.run()

    cerebro.plot(style="candle")