Example #1
0
File: 1.py Project: cxn945/quant-dc
def run_strategy():
    # Load the yahoo feed from the CSV file
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV("orcl", "2000.csv")

    # commission
    broker_commission = broker.backtesting.TradePercentage(0.002)
    broker_brk = floatBroker(50000, feed, broker_commission)
#    broker_brk = broker.backtesting.Broker(50000, feed)
    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, "orcl", broker_brk)
    
    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    

    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(myStrategy)
    # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
    plt.getInstrumentSubplot("orcl").addDataSeries("SMA60", myStrategy.getSMA(60))
    plt.getInstrumentSubplot("orcl").addDataSeries("SMA10", myStrategy.getSMA(10))
    plt.getInstrumentSubplot("orcl").addDataSeries("SMA30", myStrategy.getSMA(30))
    # Plot the simple returns on each bar.
    plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())
    
    
    myStrategy.run()
    print("Final portfolio value: $%.2f %.2f %.2f" %(myStrategy.getBroker().getEquity(), myStrategy.getBroker().getCash(), myStrategy.getBroker().getShares('orcl')))
#    myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

    # Plot the strategy.
    plt.plot()
Example #2
0
def run_strategy(smaPeriod, factor1):
    import pandas as pd
    # df_new = pd.DataFrame(columns=('shares_ID', 'total number of trades','Profit times number of trades','Final portfolio value'))
    for (root, dirs, files) in os.walk("E:/SHZQ"):
        for x in range(len(files)):
            feed = GenericBarFeed(Frequency.DAY, None, None)
            feed.addBarsFromCSV("fd", "E:/SHZQ/" + files[x])

            myStrategy = MyStrategy(feed, "fd", smaPeriod, factor1)
            trade_situation = trades.Trades()
            myStrategy.attachAnalyzer(trade_situation)
            myStrategy.run()
            print(files[x] + "Final portfolio value:$%.2f" %
                  myStrategy.getBroker().getEquity())
            print("total number of trades", trade_situation.getCount())
            print("Profit times number of trades ",
                  trade_situation.getProfitableCount())
            print(
                "百分比",
                trade_situation.getProfitableCount() /
                trade_situation.getCount())
            print(trade_situation.getCount())
            df1 = pd.DataFrame({
                "shares_ID": [files[x]],
                'total number of trades': [trade_situation.getCount()],
                'Profit times number of trades':
                trade_situation.getProfitableCount(),
                'Final portfolio value': [myStrategy.getBroker().getEquity()]
            })
Example #3
0
def test():
    # Load the yahoo feed from the CSV file
    instruments = {
        'XAUUSD': {"name":"XAUUSD", "dollar_per_point":100},
    }
    CAPITAL = 2000000
    feed = GenericBarFeed(5 * Frequency.MINUTE)
    indicators = {}
    for i in instruments:
        print i
        csv_name = '%s.csv' % (i)
        #convertTicketStoryCsv(csv_name)
        csv_name_new = "new_" + csv_name
        csv_name = os.path.join("data", csv_name)
        csv_name_new = os.path.join("new", csv_name_new)
        print csv_name_new
        feed.addBarsFromCSV(i, csv_name_new)
        indicators[i] = createIndicatorFromCsv(csv_name_new)
    #pprint(indicators)
    myStrategy = TurtleTrading(feed, instruments, CAPITAL, indicators)
    myStrategy.run()
    final = myStrategy.getBroker().getEquity() - CAPITAL * 99
    profit = final - CAPITAL
    print "Final portfolio value: $%.2f" % final
    print "Profit = %.2f, %.2f " % (profit, 100 * profit / CAPITAL)
Example #4
0
def main(plot):
    symbol = sql_to_csv(True)
    instruments = [symbol, symbol]
    windowSize = 50

    # Download the bars.
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV(symbol, symbol + '.csv')

    strat = StatArb(feed, instruments[0], instruments[1], windowSize)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, False, False, True)
        plt.getOrCreateSubplot("hedge").addDataSeries("Hedge Ratio",
                                                      strat.getHedgeRatioDS())
        plt.getOrCreateSubplot("spread").addDataSeries("Spread",
                                                       strat.getSpreadDS())

    strat.run()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))

    if plot:
        plt.plot()
Example #5
0
def main(plot):
    symbol = sql_to_csv(True)
    instrument = symbol
    entrySMA = 200
    exitSMA = 5
    rsiPeriod = 2
    overBoughtThreshold = 90
    overSoldThreshold = 10

    # Download the bars.
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV(symbol, symbol + '.csv')

    strat = RSI2(feed, instrument, entrySMA, exitSMA, rsiPeriod,
                 overBoughtThreshold, overSoldThreshold)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "Entry SMA", strat.getEntrySMA())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "Exit SMA", strat.getExitSMA())
        plt.getOrCreateSubplot("rsi").addDataSeries("RSI", strat.getRSI())
        plt.getOrCreateSubplot("rsi").addLine(
            "Overbought", overBoughtThreshold)
        plt.getOrCreateSubplot("rsi").addLine("Oversold", overSoldThreshold)

    strat.run()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))

    if plot:
        plt.plot()
Example #6
0
def main(plot):
    """
    """
    # 初始化常量
    instrument = 'BINA--BTC--USDT'
    # 数据
    # 1、从mysql导出csv数据
    # 2、指定数据频率
    # 3、读入csv给feed
    sql_to_csv(True)
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV(instrument, instrument + '.csv')
    # 评价器
    # 1、初始化一个sharpratio评价器
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    # 注入
    # 1、实例化一个策略
    # 2、注入评价器
    strat = close_above_sma(feed, instrument)
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "sma", strat.getSma())

    strat.run()
    plt.plot()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))
Example #7
0
def main(plot):
    symbol = sql_to_csv(True)
    instrument = symbol
    bBandsPeriod = 40

    # Download the bars.
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV(symbol, symbol + '.csv')

    strat = BBands(feed, instrument, bBandsPeriod)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "upper", strat.getBollingerBands().getUpperBand())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "middle", strat.getBollingerBands().getMiddleBand())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "lower", strat.getBollingerBands().getLowerBand())

    strat.run()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))

    if plot:
        plt.plot()
def backtest(strategyClass, is_optimization, is_tick, start_date, end_date,
             symbol, frequency, position_size, lb, i):
    if is_tick:
        feed = bitbf.CSVTradeFeed()
        feed.addBarsFromCSV("../xbtusd_trades.csv",
                            'XBTUSD',
                            fromDateTime=start_date,
                            toDateTime=end_date)
    else:
        feed = GenericBarFeed(bar.Frequency.MINUTE, maxLen=10000)
        feed.setColumnName('datetime', 'Date')
        feed.setDateTimeFormat('%Y-%m-%dT%H:%M:%S.%fZ')
        feed.setBarFilter(csvfeed.DateRangeFilter(start_date, end_date))
        feed.addBarsFromCSV("XBTUSD", "../BITMEX_SPOT_BTC_USD_1MIN.csv")

    if is_optimization:
        strat = local.run(strategyClass,
                          feed,
                          parameters_generator(),
                          workerCount=None,
                          logLevel=10,
                          batchSize=1)
        print(strat.getResult(), strat.getParameters())
    else:
        strat = strategyClass(feed, None, symbol, int(frequency),
                              position_size, lb, i)

        strat.run()
Example #9
0
def main(plot):
    symbol = sql_to_csv(False)
    instrument = symbol
    vwapWindowSize = 5
    threshold = 0.01

    # Download the bars.
    feed = GenericBarFeed(Frequency.DAY, None, None)

    feed.addBarsFromCSV(symbol, symbol + '.csv')

    strat = VWAPMomentum(feed, instrument, vwapWindowSize, threshold)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "vwap", strat.getVWAP())

    strat.run()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))

    if plot:
        plt.plot()
Example #10
0
def run_strategy(signal_period):
    # Load the bar feed from the CSV file
    data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../data/btcusd_1h.csv')
    feed = GenericBarFeed(Frequency.HOUR)
    feed.addBarsFromCSV("BTC", data_path)

    # Evaluate the strategy with the feed's bars.
    strategy = OBVSignalCrossStrategy(feed, "BTC", signal_period=signal_period)

    # Attach a returns analyzers to the strategy.
    returns_analyzer = returns.Returns()
    strategy.attachAnalyzer(returns_analyzer)

    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(strategy)
    # Plot the simple returns on each bar.
    plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returns_analyzer.getReturns())
    # Plot indicators
    plt.getOrCreateSubplot("obv").addDataSeries("OBV", strategy.get_obv())
    plt.getOrCreateSubplot("obv").addDataSeries("Signal", strategy.get_signal())

    strategy.run()
    print("Final portfolio value: $%.2f" % strategy.getBroker().getEquity())

    plt.plot()
Example #11
0
def main(plot):
    bBandsPeriod = 60 * 24 * 2

    # download and load the historic trade data from mtgox
    currency = 'USD'
    instrument = 'BTC'
    startdate = datetime.date(2013, 1, 1)
    enddate = datetime.date.today() - relativedelta(days=1)
    barFrequency = pyalgotrade.barfeed.Frequency.MINUTE

    print '(down-)loading bars'
    feed = GenericBarFeed(barFrequency)
    month = startdate
    while month <= enddate:
        fnamOrig = 'trades-mtgox-%s-%d-%d.csv' % (currency, month.year,
                                                  month.month)
        if barFrequency == pyalgotrade.barfeed.Frequency.MINUTE:
            fnamResa = 'resamp1m-mtgox-%s-%d-%d.csv' % (currency, month.year,
                                                        month.month)
        else:
            fnamResa = 'resamp1h-mtgox-%s-%d-%d.csv' % (currency, month.year,
                                                        month.month)
        if not os.path.exists(fnamOrig):
            print 'downloading ', fnamOrig
            tools.download_trades_by_month(currency, month.year, month.month,
                                           fnamOrig)
        if not os.path.exists(fnamResa):
            print 'resampling ', fnamResa
            feedLocal = barfeed.CSVTradeFeed()
            feedLocal.addBarsFromCSV(fnamOrig)
            resample_to_csv(feedLocal, barFrequency, fnamResa)

        print 'loading ', fnamResa
        feed.addBarsFromCSV(instrument, fnamResa)
        month += relativedelta(months=1)

    print 'set up strategy and plot'
    myStrategy = MyStrategy(feed, instrument, bBandsPeriod)

    if plot:
        plt = plotter.StrategyPlotter(myStrategy, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "upper",
            myStrategy.getBollingerBands().getUpperBand())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "middle",
            myStrategy.getBollingerBands().getMiddleBand())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "lower",
            myStrategy.getBollingerBands().getLowerBand())

    print 'run the strategy'
    myStrategy.run()
    print "Result: %.2f" % myStrategy.getResult()

    if plot:
        plt.plot()
Example #12
0
def mainPlot():
    instrument = 'BINA--BTC--USDT'
    if mysqlToCsv(label=True, database='vic_5mk', table='5mk', instrument=instrument):
        feed = GenericBarFeed(Frequency.MINUTE * 5, None, None)
        feed.addBarsFromCSV(instrument, instrument + '.csv')

    strat = myStrategy(feed, instrument)
    strat.run()
    plt.plot(strat.ncp5)
    plt.plot(strat.ncp55)
    plt.show()
    print(strat.counter)
Example #13
0
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 image - pythonspot.com'
        feed = GenericBarFeed(Frequency.DAY, None, None)
        feed.addBarsFromCSV("fd", "8-11.csv")

        # 3.实例化策略
        myStrategy = MyStrategy(feed, "fd")
        plot = plotter.StrategyPlotter(myStrategy)
        myStrategy.run()
        plot.plot()
        self.initUI()
Example #14
0
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 image - pythonspot.com'
        feed = GenericBarFeed(Frequency.DAY, None, None)

        path = "C:\\Users\\user\\Desktop\\lastest(8.14)"
        if os.path.exists(path+"\\8-11.csv"):  
            feed.addBarsFromCSV("fd", "8-11.csv")  
  
            # 3.实例化策略  
            myStrategy = MyStrategy(feed, "fd")
            plot = plotter.StrategyPlotter(myStrategy)
            myStrategy.run()
            plot.plot()
            self.initUI()
Example #15
0
def main(plot):
    instrument = ["price_diff", 'SHFE_AU', 'COMEX_AU']
    bBandsPeriod = 20

    # Download the bars.
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV('price_diff', 'price_oneyear_diff.csv')
    feed.addBarsFromCSV('SHFE_AU', 'AU_oneyear_samedate.csv')
    feed.addBarsFromCSV('COMEX_AU', 'GC_oneyear_samedate.csv')

    # 3. broker setting
    broker_commission = broker.backtesting.FixedPerTrade(390)  # 2230

    fill_stra = broker.fillstrategy.DefaultStrategy(volumeLimit=1)
    sli_stra = broker.slippage.VolumeShareSlippage(priceImpact=0.2)
    fill_stra.setSlippageModel(sli_stra)

    brk = broker.backtesting.Broker(10000000, feed, broker_commission)
    brk.setFillStrategy(fill_stra)

    strat = BBands(feed, instrument[0], instrument[1], instrument[2],
                   bBandsPeriod, brk)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    trade_situation = trades.Trades()
    strat.attachAnalyzer(trade_situation)
    draw_down = drawdown.DrawDown()
    strat.attachAnalyzer(draw_down)
    returning = returns.Returns()
    strat.attachAnalyzer(returning)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getInstrumentSubplot(instrument[0]).addDataSeries(
            "upper",
            strat.getBollingerBands().getUpperBand())
        plt.getInstrumentSubplot(instrument[0]).addDataSeries(
            "middle",
            strat.getBollingerBands().getMiddleBand())
        plt.getInstrumentSubplot(instrument[0]).addDataSeries(
            "lower",
            strat.getBollingerBands().getLowerBand())

    strat.run()
    strat.info('最终资产值: ¥ %.2f' % strat.getResult())  #info表示记录每一次的交易
    print '夏普率: ', sharpeRatioAnalyzer.getSharpeRatio(0.05,
                                                      False)  #print表示只打印一次
    print '累计收益率:', (returning.getCumulativeReturns()[-1])
    print '最大回撤:', draw_down.getMaxDrawDown()
    print '总交易次数:', trade_situation.getCount()
    print '每次交易的手续费:', trade_situation.getCommissionsForAllTrades()
    print '赚钱的交易次数:', trade_situation.getProfitableCount()
    print '亏损的交易次数:', trade_situation.getUnprofitableCount()
    print '不赚不亏的交易次数:', trade_situation.getEvenCount()
    print '每次交易的盈亏:', trade_situation.getAll()

    if plot:
        plt.plot()
Example #16
0
def main(plot):
    instrument = "mro"
    fastSMA = 5
    slowSMA = 10
    fastEMA = 12
    slowEMA = 26
    signalEMA = 9
    frequency = bar.Frequency.MINUTE

    if frequency == bar.Frequency.DAY:
        path = MyFiles.dataPath+"mro-2013-yahoofinance.csv"
    elif frequency == bar.Frequency.MINUTE:
        path = MyFiles.dataIntradayPath+"MRO.csv"
    filepath = path

    #############################################don't change ############################33
    from pyalgotrade.barfeed.csvfeed import GenericBarFeed

    feed = GenericBarFeed(frequency)
    feed.setDateTimeFormat('%Y/%m/%d %H:%M')
    feed.addBarsFromCSV(instrument, filepath)

    #feed = yahoofeed.Feed()
    #feed.addBarsFromCSV(instrument,MyFiles.dataPath+"mro-2013-yahoofinance.csv")
    #feed.addBarsFromCSV(instrument,MyFiles.dataIntradayPath+"MRO.csv")


    strat = MyStrategy1(feed, instrument, fastSMA, slowSMA, fastEMA,slowEMA,signalEMA)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getOrCreateSubplot("macd").addDataSeries("MACD Value", strat.getMACD())
        plt.getOrCreateSubplot("macd").addDataSeries("MACD SignalValue", strat.getSignal())
        # plt.getOrCreateSubplot("macd").addDataSeries("MACD Histogram", strat.getHistogram())
        plt.getInstrumentSubplot(instrument).addDataSeries("Fast SMA", strat.getSMAF())
        plt.getInstrumentSubplot(instrument).addDataSeries("Slow SMA", strat.getSMAS())

        #plt.getOrCreateSubplot("rsi").addLine("Overbought", overBoughtThreshold)
        #plt.getOrCreateSubplot("rsi").addLine("Oversold", overSoldThreshold)

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
Example #17
0
def main(plot):
    bBandsPeriod = 60 * 24 * 2

    # download and load the historic trade data from mtgox
    currency = 'USD'
    instrument = 'BTC'
    startdate = datetime.date(2013, 1, 1)
    enddate = datetime.date.today() - relativedelta(days=1)
    barFrequency = pyalgotrade.barfeed.Frequency.MINUTE

    print '(down-)loading bars'
    feed = GenericBarFeed(barFrequency)
    month = startdate
    while month <= enddate:
        fnamOrig = 'trades-mtgox-%s-%d-%d.csv' % (currency, month.year, month.month)
        if barFrequency == pyalgotrade.barfeed.Frequency.MINUTE:
            fnamResa = 'resamp1m-mtgox-%s-%d-%d.csv' % (currency, month.year, month.month)
        else:
            fnamResa = 'resamp1h-mtgox-%s-%d-%d.csv' % (currency, month.year, month.month)
        if not os.path.exists(fnamOrig):
            print 'downloading ', fnamOrig
            tools.download_trades_by_month(currency, month.year, month.month, fnamOrig)
        if not os.path.exists(fnamResa):
            print 'resampling ', fnamResa
            feedLocal = barfeed.CSVTradeFeed()
            feedLocal.addBarsFromCSV(fnamOrig)
            resample_to_csv(feedLocal, barFrequency, fnamResa)

        print 'loading ', fnamResa
        feed.addBarsFromCSV(instrument, fnamResa)
        month += relativedelta(months=1)

    print 'set up strategy and plot'
    myStrategy = MyStrategy(feed, instrument, bBandsPeriod)

    if plot:
        plt = plotter.StrategyPlotter(myStrategy, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("upper", myStrategy.getBollingerBands().getUpperBand())
        plt.getInstrumentSubplot(instrument).addDataSeries("middle", myStrategy.getBollingerBands().getMiddleBand())
        plt.getInstrumentSubplot(instrument).addDataSeries("lower", myStrategy.getBollingerBands().getLowerBand())

    print 'run the strategy'
    myStrategy.run()
    print "Result: %.2f" % myStrategy.getResult()

    if plot:
        plt.plot()
Example #18
0
    def table_sitting(self):
        feed = GenericBarFeed(Frequency.DAY, None, None)
        path = "C:\\Users\\user\\Desktop\\lastest(8.14)"
        if os.path.exists(path+"\\8-11.csv"): 
            feed.addBarsFromCSV("fd", "8-11.csv")  
      
            # 3.实例化策略  
            myStrategy = MyStrategy(feed, "fd")  
            # 4.设置指标和绘图  
            sharpe_ratio = sharpe.SharpeRatio()
            mytrade = trades.Trades() 
            myStrategy.attachAnalyzer(sharpe_ratio)
            myStrategy.attachAnalyzer(mytrade)
            #plt = plotter.StrategyPlotter(myStrategy) 
              
            # 5.运行策略  
            myStrategy.run()
            myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

            self.tableWidget.setHorizontalHeaderLabels(["第一行", "第二行"])
            self.tableWidget.setVerticalHeaderLabels(["淨利", "毛利","毛損","報酬率","總交易次數","勝率","獲利因子","夏普比率"])
            #设置表头

            lb1 = QLabel(str(int(myStrategy.getResult()-1000000)))
            self.tableWidget.setCellWidget(0,0,lb1)
            lb2 = QLabel("test")
            self.tableWidget.setCellWidget(1,0,lb2)
            a=str(((myStrategy.getResult()-1000000)/1000000)*100)
            last_a=a[:6]+"(%)"
            lb3 = QLabel(last_a)
            self.tableWidget.setCellWidget(3,0,lb3)
            if mytrade.getCount()==0:
                last_a=" N/A"
            else:
                last_a=str(mytrade.getCount())
            lb4 = QLabel(last_a)
            self.tableWidget.setCellWidget(4,0,lb4)
            try:
                a=str(mytrade.getProfitableCount()/mytrade.getCount()*100)
                last_a=a[:6]+"(%)"
            except ZeroDivisionError:
                last_a=" N/A"
            lb5 = QLabel(last_a)
            self.tableWidget.setCellWidget(5,0,lb5)
            lb7 = QLabel(str(sharpe_ratio.getSharpeRatio(0)))
            self.tableWidget.setCellWidget(7,0,lb7)
def run_strategy(smaPeriod):
    # Load the yahoo feed from the CSV file
    # feed = yahoofeed.Feed()
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV("zggf", "E:\Stock\Data_Day/000831.SZ.csv")
    global myStrategy
    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, "zggf", smaPeriod)
    plt = plotter.StrategyPlotter(myStrategy)
    sharpe_ratio = sharpe.SharpeRatio()
    trade_situation = trades.Trades()
    myStrategy.attachAnalyzer(sharpe_ratio)
    myStrategy.attachAnalyzer(trade_situation)
    myStrategy.run()
    print("Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity())
    print("sharpe_ratio", sharpe_ratio.getSharpeRatio(0))
    print("total number of trades", trade_situation.getCount())
    print("Profit times number of trades ",
          trade_situation.getProfitableCount())
    print(myStrategy.Sma_price)
    plt.plot()
Example #20
0
def run_strategy():
    # Load the yahoo feed from the CSV file
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV(coin, get_file_path())

    # commission
    broker_commission = broker.backtesting.TradePercentage(0.002)
    broker_brk = floatBroker(10000, feed, broker_commission)
    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, coin, broker_brk)

    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)

    myStrategy.run()
    print(
        "Final portfolio value: $%.2f %.2f %.2f" %
        (myStrategy.getBroker().getEquity(), myStrategy.getBroker().getCash(),
         myStrategy.getBroker().getShares(coin)))

    myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())
Example #21
0
    def table_sitting(self):
        feed = GenericBarFeed(Frequency.DAY, None, None)
        feed.addBarsFromCSV("fd", "8-11.csv")

        # 3.实例化策略
        myStrategy = MyStrategy(feed, "fd")
        # 4.设置指标和绘图
        sharpe_ratio = sharpe.SharpeRatio()
        mytrade = trades.Trades()
        myStrategy.attachAnalyzer(sharpe_ratio)
        myStrategy.attachAnalyzer(mytrade)
        plt = plotter.StrategyPlotter(myStrategy)

        # 5.运行策略
        myStrategy.run()
        myStrategy.info("Final portfolio value: $%.2f" %
                        myStrategy.getResult())

        self.tableWidget.setHorizontalHeaderLabels(["第一行", "第二行"])
        self.tableWidget.setVerticalHeaderLabels(
            ["淨利", "毛利", "毛損", "報酬率", "總交易次數", "勝率", "獲利因子", "夏普比率"])
        #设置表头
        lb1 = QLabel(str(myStrategy.getResult() - 1000000))
        self.tableWidget.setCellWidget(0, 0, lb1)
        lb2 = QLabel("test")
        self.tableWidget.setCellWidget(1, 0, lb2)
        a = str(((myStrategy.getResult() - 1000000) / 1000000) * 100)
        last_a = a[:6] + "(%)"
        lb3 = QLabel(last_a)
        self.tableWidget.setCellWidget(3, 0, lb3)
        lb4 = QLabel(str(mytrade.getCount()))
        self.tableWidget.setCellWidget(4, 0, lb4)
        a = str(mytrade.getProfitableCount() / mytrade.getCount() * 100)
        last_a = a[:6] + "(%)"
        lb5 = QLabel(last_a)
        self.tableWidget.setCellWidget(5, 0, lb5)
        lb7 = QLabel(str(sharpe_ratio.getSharpeRatio(0)))
        self.tableWidget.setCellWidget(7, 0, lb7)
Example #22
0
def backtest(stockcode,date,preclose,prehigh,prelow,p1,p2,p3,p4):
    stockcode=stockcode
    #date=['2016-02-29','2016-03-02','2016-03-11']
    path = "../histdata/tick/bak/"
    strat =rbreaker
    paras=[preclose,prehigh,prelow,p1,p2,p3,p4]
    plot = True
   # barfeed = tickcsvfeed.TickBarFeed(bar.Frequency.SECOND)
    barfeed=GenericBarFeed(pyalgotrade.bar.Frequency.SECOND)
    dstr=''
    for d in date:
        filepath = path +'stock_'+ stockcode + "_"+d+".csv"
        barfeed.addBarsFromCSV(stockcode, filepath)
        dstr=dstr+'_'+d
    barfeed.setDateTimeFormat('%Y-%m-%d %H:%M:%S')
    strat = strat(barfeed, stockcode, *paras)
    strat.run()
    cash=strat.getBroker()._Broker__cash
    #tradeTimes=strat.getTradeTimes()
    ticker=open(path +'stock_'+ stockcode+'_' + dstr+".csv", 'a')
    ticker.write(str(p1))
    ticker.write(',')
    ticker.write(str(p2))
    ticker.write(',')
    ticker.write(str(p3))
    ticker.write(',')
    ticker.write(str(p4))
    ticker.write(',')
    ticker.write(str(cash))
    ticker.write(',')
    #ticker.write(str(tradeTimes))

    ticker.write('\n')
    ticker.close()
    del strat
    #return ( stockcode,date,p1,p2,p3,p4,cash,tradeTimes)
    return ( stockcode,date,p1,p2,p3,p4,cash)
Example #23
0
def main(plot):
    symbol = sql_to_csv(True)

    instrument = symbol
    smaPeriod = 10

    # Download the bars.
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV(symbol, symbol + '.csv')

    strat = SMACrossOver(feed, instrument, smaPeriod)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "sma", strat.getSMA())

    strat.run()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))

    if plot:
        plt.plot()
Example #24
0
def run_strategy(smaPeriod):
    df_new = pd.DataFrame(columns=('shares_ID', 'total number of trades',
                                   'Profit times number of trades',
                                   'Profit Percentage',
                                   'Final portfolio value'))
    for (root, dirs, files) in os.walk("E:/SHZQ"):
        for x in range(len(files)):
            feed = GenericBarFeed(Frequency.WEEK, None, None)
            feed.addBarsFromCSV("fd", "E:/SHZQ/" + files[x])
            myStrategy = MyStrategy(feed, "fd", smaPeriod)
            trade_situation = trades.Trades()
            myStrategy.attachAnalyzer(trade_situation)
            myStrategy.run()
            print(files[x] + "Final portfolio value:$%.2f" %
                  myStrategy.getBroker().getEquity())
            print("total number of trades", trade_situation.getCount())
            print("Profit times number of trades ",
                  trade_situation.getProfitableCount())
            if trade_situation.getCount() > 0:
                Percentage = trade_situation.getProfitableCount(
                ) / trade_situation.getCount()
                print("百分比", Percentage)
            else:
                Percentage = 0
                print("百分比", 0)
            df1 = pd.DataFrame({
                "shares_ID": [files[x]],
                'total number of trades': [trade_situation.getCount()],
                'Profit times number of trades':
                trade_situation.getProfitableCount(),
                'Profit Percentage':
                Percentage,
                'Final portfolio value': [myStrategy.getBroker().getEquity()]
            })
            df_new = pd.concat([df1, df_new], ignore_index=True)
    df_new.to_csv("E:/Stock/html_png_Total//Total.csv", index=False)
Example #25
0
def main(plot):
    """
    """
    # 初始化常量
    instrument = 'BINA--BTC--USDT'
    # 数据
    # 1、从mysql导出csv数据
    # 2、指定数据频率
    # 3、读入csv给feed
    sql_to_csv(False)
    feed = GenericBarFeed(Frequency.MINUTE * 5, None, None)
    feed.addBarsFromCSV(instrument, instrument + '.csv')

    # 评价器
    # 1、初始化一个sharpratio评价器
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    # 注入
    # 1、实例化一个策略
    # 2、注入评价器
    strat = DualThrust(feed, instrument)
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)


#         plt.getInstrumentSubplot(instrument).addDataSeries(
#             "High", strat.get_high())
#         plt.getInstrumentSubplot(instrument).addDataSeries(
#             "Low", strat.get_low())
#         plt.getInstrumentSubplot(instrument).addDataSeries(
#             "BuyPosition", strat.get_buy_position())
#         plt.getInstrumentSubplot(instrument).addDataSeries(
#             "SellPosition", strat.get_sell_position())
    strat.run()
    plt.plot()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))
def main(selected_features, predict_n_days, model_form, testing_datetime,
         testing_end_datetime, n_retrain_times):
    feed = GenericBarFeed(frequency='DAY')
    instruments = {
        'hk_equity_fund': 'dataset/hk_equity_fund_data.csv',
        'growth_fund': 'dataset/growth_fund_data.csv',
        'balanced_fund': 'dataset/balanced_fund_data.csv',
        'conservative_fund': 'dataset/conservative_fund_data.csv',
        'hkdollar_bond_fund': 'dataset/hkdollar_bond_fund_data.csv',
        'stable_fund': 'dataset/stable_fund_data.csv',
        'HSI': 'dataset/HSI_investing_com.csv',
        'IXIC': 'dataset/IXIC_investing_com.csv',
        'us2yrby': 'dataset/us2yrbondyield_investing_com.csv',
        'us10yrby': 'dataset/us10yrbondyield_investing_com.csv'
    }
    for instu, fname in instruments.iteritems():
        print('Importing data %s from file path %s' % (instu, fname))
        feed.addBarsFromCSV(instu, fname)
    capital = 1000000.0
    tree_reg_strategy = WalkForwardBacktester(
        feed=feed,
        instrument=instruments.keys(),
        capital=capital,
        selected_features=selected_features,
        predict_n_days=predict_n_days,
        model_form=model_form,
        testing_datetime=testing_datetime,
        testing_end_datetime=testing_end_datetime,
        n_retrain_times=n_retrain_times)
    retAnalyzer = rets.Returns()
    tree_reg_strategy.attachAnalyzer(retAnalyzer)
    tree_reg_strategy.run()
    equity_curve = list()
    for ret in retAnalyzer.getCumulativeReturns():
        equity_curve.append(capital * (1 + ret))
    return equity_curve
Example #27
0
def run_strategy(sma_period):
    # Load the bar feed from the CSV file
    data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../data/btcusd_1h.csv')
    feed = GenericBarFeed(Frequency.HOUR)
    feed.addBarsFromCSV("BTC", data_path)

    # Evaluate the strategy with the feed's bars.
    strategy = SmaCrossStrategy(feed, "BTC", sma_period=sma_period)

    # Attach a returns analyzers to the strategy.
    returns_analyzer = returns.Returns()
    strategy.attachAnalyzer(returns_analyzer)

    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(strategy)
    # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
    plt.getInstrumentSubplot("BTC").addDataSeries("SMA", strategy.get_sma())
    # Plot the simple returns on each bar.
    plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returns_analyzer.getReturns())

    strategy.run()
    print("Final portfolio value: $%.2f" % strategy.getBroker().getEquity())

    plt.plot()
Example #28
0
def buildFeed(code, filename):
    feed = GenericBarFeed(Frequency.MINUTE)
    feed.setDateTimeFormat("%Y-%m-%d %H:%M")
    feed.addBarsFromCSV(code, filename)
    #feed = csvfeed.Feed("Date Time", "%Y-%m-%d %H:%M")
#    feed.addValuesFromCSV(filename)
    #for item in feed:
#        print(item[0], len(item), item[1])
#        print(item.getDateTime())
    return feed
Example #29
0
 def __getFeedFromGenericCsv(self,instrument):
     '''mid
     使用系统自定义的与数据提供者的数据格式相互独立的csv格式储存的文件
     可以作为用户管理各种数据源的统一格式使用
     '''
     from pyalgotrade.barfeed.csvfeed import GenericBarFeed
     from pyalgotrade import bar
     frequency = bar.Frequency.DAY
     barfeed = GenericBarFeed(frequency)
     barfeed.setDateTimeFormat('%Y-%m-%d %H:%M:%S')
     
     dataRoot = os.path.abspath(os.path.join(os.path.dirname(__file__),'data','generic','csv'))        
     filename = dataRoot+os.sep+'day'+os.sep+('%s.csv'%instrument)          
     barfeed.addBarsFromCSV(instrument, filename) 
     return barfeed
Example #30
0
def main(plot):
    from pyalgotrade import bar
    from pyalgotrade import plotter
    instrument = "002665"
    bBandsPeriod = 40
    strat = BBands
    frequency = bar.Frequency.DAY
    plot = True

    # Download the bars.
    from pyalgotrade.barfeed.csvfeed import GenericBarFeed
    barfeed = GenericBarFeed(frequency)
    barfeed.setDateTimeFormat('%Y-%m-%d %H:%M:%S')
    barfeed.addBarsFromCSV("002665", "F:/shuju/002665-barfeed.csv")
    strat = strat(barfeed, instrument, bBandsPeriod)

    strat = BBands(barfeed, instrument, bBandsPeriod)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:

        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "upper",
            strat.getBollingerBands().getUpperBand())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "middle",
            strat.getBollingerBands().getMiddleBand())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "lower",
            strat.getBollingerBands().getLowerBand())

    strat.run()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))

    if plot:

        plt.plot()
Example #31
0
def main():
    filedir = "testresults"
    iteration = 0
    resultsdict = {}

    for instrument in instrumentListGetter():
        if len(instrument.split()) > 1:
            instrument, instrumentSource = instrument.split()
            print "instrument: %s, source: %s" % (instrument, instrumentSource)
        else:
            instrumentSource = ""

        #feed = yahoofeed.Feed()
        #feed.addBarsFromCSV("hm",  DATAPATH + "/hm_table.csv")

        # Load the feed from the CSV files.

        #for params in parameters_generator():
        faileddataforinstrument = False
        for params in teststrategy.parameters_generator():

            # Do not move to outer loop or severe performance problems arise # take the data we have and use
            yiter = 0
            if "quandl" in instrumentSource:  # https://www.quandl.com/data/
                '''/home/carl/Projects/algotrader/algotrader/lib64/python2.7/site-packages/pyalgotrade/barfeed/csvfeed.py:171 needs try hack '''
                try:
                    feed = GenericBarFeed(frequency=bar.Frequency.DAY)
                    feed.setDateTimeFormat("%Y-%m-%d")
                    feed.setColumnName("datetime", "Date")
                    feed.setColumnName("adj_close", "Adjusted Close")
                    #feed.addBarsFromCSV(instrument, DATAPATH)
                    feed.addBarsFromCSV(instrument,
                                        DATAPATH + "/" + instrument + ".csv")
                except:
                    print sys.exc_info()
                    faileddataforinstrument = True

            else:
                for year in range(YEARSOFDATA, 0, -1):
                    startyear = localtime().tm_year - (YEARSOFDATA - yiter)
                    try:
                        feed = build_feed([instrument],
                                          startyear,
                                          2016,
                                          DATAPATH,
                                          frequency=86400,
                                          timezone=None,
                                          skipErrors=False)
                    except:
                        print "\n\nFailed downloading %s for year %d yiter %d \n\n" % (
                            instrument, startyear, yiter)
                        yiter += 1
                        if year == (YEARSOFDATA - 1):
                            faileddataforinstrument = True

            if faileddataforinstrument:
                break

            strat = teststrategy.TestStrat(feed, instrument, *params)
            iteration += 1

            paramnames = teststrategy.parameters_generator(paramnames=True)
            paramsarray = zip(paramnames, [str(p) for p in params])
            paramsstring = str([
                ":".join(t) for t in zip(paramnames, [str(p) for p in params])
            ])

            print "\n\nIteration %d / %d; Instrument %s ; Params %s" % (
                iteration, iterations, instrument, paramsstring)

            #retAnalyzer = returns.Returns()
            #strat.attachAnalyzer(retAnalyzer)
            sharpeRatioAnalyzer = sharpe.SharpeRatio()
            strat.attachAnalyzer(sharpeRatioAnalyzer)
            #drawDownAnalyzer = drawdown.DrawDown()
            #strat.attachAnalyzer(drawDownAnalyzer)
            tradesAnalyzer = trades.Trades()
            strat.attachAnalyzer(tradesAnalyzer)

            # with instrument
            #csvdict["Params"] = [":".join(t) for t in  zip(("instrument", "entrySMA", "exitDays", "rsiPeriod", "overBoughtThreshold", "overSoldThreshold"), [str(p) for p in params] )]
            # without instrument

            print paramsstring
            strat.run()
            tradetotal = 0

            tradetotal = sum(
                [t * 100.00 for t in tradesAnalyzer.getAllReturns()])
            nr_of_trades = tradesAnalyzer.getCount()
            try:
                profitable_tradeprcnt = "%.2f" % (
                    (float(tradesAnalyzer.getProfitableCount()) /
                     float(tradesAnalyzer.getCount())) * 100)
                trade_avg_result_prcnt = "%.2f" % (
                    tradetotal / float(tradesAnalyzer.getCount()))
            except ZeroDivisionError:
                profitable_tradeprcnt = "0.0"
                trade_avg_result_prcnt = "0.0"

            sharpe_ratio = "%.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0.05))

            #print "Cumulative returns: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)

            print "Trade stats"
            print "Nr of trades:\t\t\t%d" % (nr_of_trades)
            print "Trade avg:\t\t\t%s%%" % (trade_avg_result_prcnt)
            print "Profitable trades:\t\t%s%%" % (profitable_tradeprcnt)
            print "Sharpe ratio:\t\t\t", sharpe_ratio
            print
            returns = tradesAnalyzer.getAllReturns()

            if tradesAnalyzer.getProfitableCount() > 0:
                trade_max = "%.2f" % (returns.max() * 100)
                trade_min = "%.2f" % (returns.min() * 100)
                trade_stddev = "%.2f" % (returns.std() * 100)
            else:
                trade_max = "%.2f" % 0
                trade_min = "%.2f" % 0
                trade_stddev = "%.2f" % 0

            print "Returns std. dev.: %s %%\t\t\t" % trade_stddev
            print "Max. return: %s %%\t\t\t" % trade_max
            print "Min. return: %s %%\t\t\t" % trade_min
            #print "Trade total:	    %.2f" % ( tradetotal )
            #print "Max. drawdown: %.2f %%" % (drawDownAnalyzer.getMaxDrawDown() * 100)

            #if tradesAnalyzer.getProfitableCount() > 0:
            #profits = tradesAnalyzer.getProfits()
            #losses = tradesAnalyzer.getLosses()
            #print "Avg. profit: $%2.f" % (profits.mean())
            #print "Avg. loss: $%2.f" % (losses.mean())

            #returns = tradesAnalyzer.getPositiveReturns()
            #returns = tradesAnalyzer.getAllReturns()
            #print "Avg. return: %2.f %%" % (returns.mean() * 100) # too much rounding
            #print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
            #print "Max. return: %2.f %%" % (returns.max() * 100)
            #print "Min. return: %2.f %%" % (returns.min() * 100)

            #print "Trades std. dev.: $%2.f" % (profits.std())
            #print "Max. profit: $%2.f" % (profits.max())
            #print "Min. profit: $%2.f" % (profits.min())

            if paramsstring in resultsdict.keys():
                try:
                    resultsdict[paramsstring]['nr_of_trades'] = int(
                        resultsdict[paramsstring]['nr_of_trades']) + int(
                            nr_of_trades)
                    resultsdict[paramsstring][
                        'profitable_tradeprcnt'] = "%.2f" % (
                            (float(resultsdict[paramsstring]
                                   ['profitable_tradeprcnt']) +
                             float(profitable_tradeprcnt)) / 2.00)
                    resultsdict[paramsstring][
                        'trade_avg_result_prcnt'] = "%.2f" % (
                            (float(resultsdict[paramsstring]
                                   ['trade_avg_result_prcnt']) +
                             float(trade_avg_result_prcnt)) / 2.00)
                    resultsdict[paramsstring]['sharpe_ratio'] = "%.2f" % (
                        (float(resultsdict[paramsstring]['sharpe_ratio']) +
                         float(sharpe_ratio)) / 2.00)
                    resultsdict[paramsstring]['trade_max'] = "%.2f" % (
                        float(resultsdict[paramsstring]['trade_max']) +
                        float(trade_max) / 2.00)
                    resultsdict[paramsstring]['trade_min'] = "%.2f" % (
                        float(resultsdict[paramsstring]['trade_min']) +
                        float(trade_min) / 2.00)
                    resultsdict[paramsstring]['trade_stddev'] = "%.2f" % (
                        float(resultsdict[paramsstring]['trade_stddev']) +
                        float(trade_stddev) / 2.00)
                except ZeroDivisionError:
                    print "\nError (ZeroDivisionError) trying averaging with: %s\n" % paramsstring
            else:  # First time with params
                resultsdict[paramsstring] = dict(paramsarray)
                resultsdict[paramsstring]['params'] = paramsstring
                resultsdict[paramsstring]['nr_of_trades'] = nr_of_trades
                resultsdict[paramsstring][
                    'profitable_tradeprcnt'] = profitable_tradeprcnt
                resultsdict[paramsstring][
                    'trade_avg_result_prcnt'] = trade_avg_result_prcnt
                resultsdict[paramsstring]['sharpe_ratio'] = sharpe_ratio
                resultsdict[paramsstring]['trade_max'] = trade_max
                resultsdict[paramsstring]['trade_min'] = trade_min
                resultsdict[paramsstring]['trade_stddev'] = trade_stddev

            feed.reset()  # feed must be reset

            del sharpeRatioAnalyzer
            del tradesAnalyzer

    with open(filedir + "/" + strat.STRATNAME + '.csv', 'wb') as csvfile:
        fieldnames = ['params']
        fieldnames.extend(paramnames)
        fieldnames.extend(
            ('nr_of_trades', 'profitable_tradeprcnt', 'trade_avg_result_prcnt',
             'sharpe_ratio', 'trade_max', 'trade_min', 'trade_stddev'))

        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        #csvheader = {'params':'Params: ' + strat.STRATNAME, paramnames, 'nr_of_trades':'Nr of trades',\
        #        'profitable_tradeprcnt':'Profitable trades%', 'trade_avg_result_prcnt':'Trade avg %', 'sharpe_ratio': 'Sharpe Ratio'}
        csvheader = {'params': 'Params: ' + strat.STRATNAME}
        for n in paramnames:
            csvheader[n] = n
        csvheader['nr_of_trades'] = 'Nr of trades'
        csvheader['profitable_tradeprcnt'] = 'Profitable trades%'
        csvheader['trade_avg_result_prcnt'] = 'Trade avg %'
        csvheader['sharpe_ratio'] = 'Sharpe Ratio'
        csvheader['trade_max'] = 'Trade Max'
        csvheader['trade_min'] = 'Trade Min'
        csvheader['trade_stddev'] = 'Trade Stddev'
        writer.writerow(csvheader)
        for result in resultsdict.keys():
            writer.writerow(resultsdict[result])
Example #32
0
    
    #############################################path set ############################33 
    if frequency == bar.Frequency.MINUTE:
        path = "..\\histdata\\min\\"
    elif frequency == bar.Frequency.DAY:
        path = "..\\histdata\\day\\"
    elif frequency == bar.Frequency.SECOND:
        path = "..\\histdata\\tick\\"
    filepath = path +'stock_'+ instrument + "_"+date+".csv"
    
    
    #############################################don't change ############################33  
    from pyalgotrade.barfeed.csvfeed import GenericBarFeed

    
    barfeed = GenericBarFeed(frequency)
    barfeed.setDateTimeFormat('%Y-%m-%d %H:%M:%S')
    barfeed.addBarsFromCSV(instrument, filepath)
    strat = strat(barfeed, instrument, *paras)
    
    if plot:
            plt = plotter.StrategyPlotter(strat, True, True, True)
            mall , mals , masl , mass = strat.getSMA()
#          #  print type(ma1)
            plt.getInstrumentSubplot('indicator').addDataSeries("small", mall)
            plt.getInstrumentSubplot('indicator').addDataSeries("smals", mals)
           # plt.getInstrumentSubplot('indicator').addDataSeries("smasl", masl)
           # plt.getInstrumentSubplot('indicator').addDataSeries("smass", mass)
            
            position = strat.getTest()
            plt.getOrCreateSubplot("position").addDataSeries("position", position)
Example #33
0
# feed = quandlfeed.Feed()
# feed.addBarsFromCSV("orcl", "WIKI-ORCL-2000-quandl.csv")
# Evaluate the strategy with the feed's bars.


#import through quandl
# instrument = "AAPL"
# feed = quandl.build_feed("WIKI", [instrument], 2017, 2018, ".")

#import from google
# feed = googlefeed.Feed()
# instrument = "spy"
# feed.addBarsFromCSV(instrument, "spy_2017.csv")

#import through local csv
feed = GenericBarFeed(Frequency.DAY, None, None)
feed.addBarsFromCSV("output", "output.csv")
instrument = "output"
myStrategy = MyStrategy(feed, instrument)

sharpeRatioAnalyzer = sharpe.SharpeRatio()
returnsAnalyzer = returns.Returns()

myStrategy.attachAnalyzer(returnsAnalyzer)
plot = True
if plot:
    plt = plotter.StrategyPlotter(myStrategy)
    plt.getInstrumentSubplot(instrument).addDataSeries("sma20", myStrategy.getSMA4())
    plt.getInstrumentSubplot(instrument).addDataSeries("sma40", myStrategy.getSMA40())

myStrategy.run()
Example #34
0
def run():
    # Load the yahoo feed from the CSV file
    instruments = {
        #'orcl'
        #,'aapl'
        'XAGUSD': {"name":"XAGUSD", "dollar_per_point":1},
        #'fxcm',
    }
    CAPITAL = 20000000
    feed = GenericBarFeed(5 * Frequency.MINUTE)
    datas = {}
    for i in instruments:
        datas[i] = []
        csv_name = '%s.csv' % (i)
        csv_name_new = "new_" + csv_name
        csv_name = os.path.join("data", csv_name)
        csv_name_new = os.path.join("new", csv_name_new)
        with open(csv_name, "rb") as fr:
            reader = csv.DictReader(fr)
            with open(csv_name_new, "wb")as fw:
                w = csv.DictWriter(fw, ["Date Time", "Open", "High", "Low", "Close", "Volume", "Adj Close"])
                w.writeheader()
                for row in reader:
                    new = {}
                    d = row["Date"]
                    new["Date Time"] = d[:4] + "-" + d[4:6] + "-" + d[6:] + " " + row["Timestamp"]
                    new["Open"] = row["Open"]
                    new["High"] = row["High"]
                    new["Low"] = row["Low"]
                    new["Close"] = row["Close"]
                    new["Volume"] = row["Volume"]
                    #w.writerow(new)
                    new["datetime"] = datetime.strptime(new["Date Time"], "%Y-%m-%d %H:%M:%S")
                    datas[i].append(new)
        feed.addBarsFromCSV(i, csv_name_new)
    # print datas
    indicator = OrderedDict()
    datelist = []
    for i in datas:
        for d in datas[i]:
            key = d["datetime"].strftime("%Y-%m-%d")
            if key not in indicator:
                indicator[key] = {
                    "Date":key,
                    "Open": float(d["Open"]),
                    "High": float(d["High"]),
                    "Low": float(d["Low"]),
                    "Close": float(d["Close"]),
                    "High55":"",
                    "Low55":"",
                    "High20":"",
                    "Low20":"",
                    "ATR20":"",
                    "TR":""
                }
                datelist.append(indicator[key])
            else:
                indicator[key]["High"] = max(indicator[key]["High"], float(d["High"]))
                indicator[key]["Low"] = min(indicator[key]["Low"], float(d["Low"]))
                indicator[key]["Close"] = float(d["Close"])
    for i in range(0, len(datelist)):
        if i > 20:
            datelist[i]["High20"] = max([d["High"] for d in datelist[i-20:i]])
            datelist[i]["Low20"] = min([d["Low"] for d in datelist[i-20:i]])
        if i > 55:
            datelist[i]["High55"] = max([d["High"] for d in datelist[i-55:i]])
            datelist[i]["Low55"] = min([d["Low"] for d in datelist[i-55:i]])
        if i > 1:
            lastday = datelist[i-1]
        #lastlastday = datelist[i-2]
            tr = max([datelist[i]["High"] - datelist[i]["Low"], datelist[i]["High"] - lastday["Close"], lastday["Close"] - datelist[i]["Low"]])
        datelist[i]["TR"] = tr
        if i > 20:
            if lastday["ATR20"] == "":
                datelist[i]["ATR20"] = sum(d["TR"] for d in datelist[i-20:i]) / 20
            else:
                datelist[i]["ATR20"] = (19*lastday["ATR20"] + tr)/20

    from pprint import pprint
    for d in indicator.values():
        pprint( d)
Example #35
0
from pyalgotrade import strategy
from pyalgotrade.bar import Frequency
from pyalgotrade.barfeed.csvfeed import GenericBarFeed


# 1.构建一个策略
class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed)
        self.__instrument = instrument

    def onBars(self, bars):  # 每一个数据都会抵达这里,就像becktest中的next
        bar = bars[self.__instrument]
        self.info(bar.getClose())  # 我们打印输出收盘价


# 2.获得回测数据,官网来源于yahoo,由于墙的关系,我们用本地数据
feed = GenericBarFeed(Frequency.DAY, None, None)
feed.addBarsFromCSV("fd", "fd.csv")

# 3.把策略跑起来
myStrategy = MyStrategy(feed, "fd")
Example #36
0
    instrument = '000001'
    market = 'SZ'
    fromDate = '20140101'
    toDate = '20160101'
    frequency = bar.Frequency.DAY
    paras = [2, 20, 60, 10]
    plot = True

    #############################################path set ############################33
    if frequency == bar.Frequency.MINUTE:
        path = "..\\histdata\\min\\"
    elif frequency == bar.Frequency.DAY:
        path = "..\\histdata\\day\\"
    filepath = path + instrument + market + ".csv"

    #############################################don't change ############################33
    from pyalgotrade.barfeed.csvfeed import GenericBarFeed

    barfeed = GenericBarFeed(frequency)
    barfeed.setDateTimeFormat('%Y-%m-%d %H:%M:%S')
    barfeed.addBarsFromCSV(instrument, filepath)
    strat = strat(barfeed, instrument, *paras)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)

    strat.run()

    if plot:
        plt.plot()
Example #37
0
def main(selected_features, predict_n_days, model_form, testing_datetime,
         testing_end_datetime, n_retrain_times):
    feed = GenericBarFeed(frequency='DAY')
    instruments = {
        'hk_equity_fund': 'dataset/hk_equity_fund_data.csv',
        'growth_fund': 'dataset/growth_fund_data.csv',
        'balanced_fund': 'dataset/balanced_fund_data.csv',
        'conservative_fund': 'dataset/conservative_fund_data.csv',
        'hkdollar_bond_fund': 'dataset/hkdollar_bond_fund_data.csv',
        'stable_fund': 'dataset/stable_fund_data.csv',
        'HSI': 'dataset/HSI_investing_com.csv',
        'IXIC': 'dataset/IXIC_investing_com.csv',
        'us2yrby': 'dataset/us2yrbondyield_investing_com.csv',
        'us10yrby': 'dataset/us10yrbondyield_investing_com.csv'
    }
    for instu, fname in instruments.iteritems():
        print('Importing data %s from file path %s' % (instu, fname))
        feed.addBarsFromCSV(instu, fname)
    # selected_features = [
    #     'hk_equity_fund', 'growth_fund', 'balanced_fund', 'conservative_fund', 'hkdollar_bond_fund', 'stable_fund'
    # ]
    # selected_features = list()
    # indicators = [
    #     'hk_equity_fund_rsi', 'growth_fund_rsi', 'balanced_fund_rsi', 'conservative_fund_rsi',
    #     'hkdollar_bond_fund_rsi', 'stable_fund_rsi'
    # ]
    # selected_features += indicators
    # predict_n_days = 30
    tree_reg_strategy = WalkForwardBacktester(
        feed=feed,
        instrument=instruments.keys(),
        capital=1000000.0,
        selected_features=selected_features,
        predict_n_days=predict_n_days,
        model_form=model_form,
        testing_datetime=testing_datetime,
        testing_end_datetime=testing_end_datetime,
        n_retrain_times=n_retrain_times)
    retAnalyzer = rets.Returns()
    tree_reg_strategy.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    tree_reg_strategy.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    tree_reg_strategy.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    tree_reg_strategy.attachAnalyzer(tradesAnalyzer)
    tree_reg_strategy.run()

    print('************************')
    print('** Backtesting Report **')
    print('************************')

    portfo_val = tree_reg_strategy.getResult()
    print "Final portfolio value: $%.2f" % portfo_val
    cumulative_returns = retAnalyzer.getCumulativeReturns()[-1]
    print "Cumulative returns: %.2f %%" % (cumulative_returns * 100)
    sharpe_ratio = sharpeRatioAnalyzer.getSharpeRatio(0.03)
    print "Sharpe ratio: %.2f" % (sharpe_ratio)
    mdd = drawDownAnalyzer.getMaxDrawDown()
    print "Max. drawdown: %.2f %%" % (mdd * 100)
    print "Longest drawdown duration: %s" % (
        drawDownAnalyzer.getLongestDrawDownDuration())
    if mdd > 0:
        calmar_ratio = retAnalyzer.getCumulativeReturns()[-1] / mdd
        print "Calmar ratio: %.4f" % (calmar_ratio)
    else:
        calmar_ratio = None

    print
    print "Total trades: %d" % (tradesAnalyzer.getCount())
    if tradesAnalyzer.getCount() > 0:
        profits = tradesAnalyzer.getAll()
        print "Avg. profit: $%2.f" % (profits.mean())
        print "Profits std. dev.: $%2.f" % (profits.std())
        print "Max. profit: $%2.f" % (profits.max())
        print "Min. profit: $%2.f" % (profits.min())
        returns = tradesAnalyzer.getAllReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.min() * 100)

    print
    print "Profitable trades: %d" % (tradesAnalyzer.getProfitableCount())
    if tradesAnalyzer.getProfitableCount() > 0:
        profits = tradesAnalyzer.getProfits()
        print "Avg. profit: $%2.f" % (profits.mean())
        print "Profits std. dev.: $%2.f" % (profits.std())
        print "Max. profit: $%2.f" % (profits.max())
        print "Min. profit: $%2.f" % (profits.min())
        returns = tradesAnalyzer.getPositiveReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.min() * 100)

    print
    print "Unprofitable trades: %d" % (tradesAnalyzer.getUnprofitableCount())
    if tradesAnalyzer.getUnprofitableCount() > 0:
        losses = tradesAnalyzer.getLosses()
        print "Avg. loss: $%2.f" % (losses.mean())
        print "Losses std. dev.: $%2.f" % (losses.std())
        print "Max. loss: $%2.f" % (losses.min())
        print "Min. loss: $%2.f" % (losses.max())
        returns = tradesAnalyzer.getNegativeReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.min() * 100)
    return portfo_val, cumulative_returns, sharpe_ratio, mdd, calmar_ratio
Example #38
0
    plot = True
    
    #############################################path set ############################33 
    if frequency == bar.Frequency.MINUTE:
        path = "..\\histdata\\min\\"
    elif frequency == bar.Frequency.DAY:
        path = "..\\histdata\\day\\"
    filepath = path + instrument + market + ".csv"
    
    
    #############################################don't change ############################33  
    from pyalgotrade.bar import Frequency
    from pyalgotrade.barfeed.csvfeed import GenericBarFeed

    
    barfeed = GenericBarFeed(Frequency.DAY)
    barfeed.addBarsFromCSV(instrument, filepath)
    strat = strat(barfeed, instrument, *paras)
    
    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        
    strat.run()
    
    if plot:
        plt.plot()