示例#1
0
def temp():
    # data

    start = dt(2017, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = dt(2017, 9, 29, 0, 0, 0, 0, pytz.utc)

    data = web.DataReader("종가", "yahoo", start, end)

    data = data[['Adj Close']]
    data.columns = ['종가']
    # data = data.tz_localize('UTC')

    # algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data)
    # result = algo.run(data)
    result = run_algorithm(start,
                           end,
                           initialize,
                           100000000.0,
                           handle_data,
                           data_frequency='daily',
                           data=data)

    # plt.plot(result.index, result.portfolio_value)
    # plt.show()

    plt.plot(result.index, result.ma5)
    plt.plot(result.index, result.ma20)
    plt.legend(loc='best')

    # plt.plot(result.ix[result.buy == True].index, result.ma5[result.buy == True], '^')
    # plt.plot(result.ix[result.sell == True].index, result.ma5[result.sell == True], 'v')

    plt.show()
示例#2
0
    def test_algo_init(self):
        '''
        test init symbol checking
        '''
        def initialize(context):
            symbols = ['AAPL', 'GE', 'JNJ', 'THEBADONE']
            return init(context, 'test', symbols=symbols)

        def handle_data(context, data, s=self):
            s.context = context

        end = get_calendar('NYSE').previous_close(Timestamp.utcnow())
        start = get_calendar('NYSE').previous_close(end - DateOffset(days=1))

        res = run_algorithm(
            start=start,
            end=end,
            initialize=initialize,
            handle_data=handle_data,
            capital_base=float('1.0e5'),
        )

        self.assertListEqual(
            ['AAPL', 'GE', 'JNJ'],
            [s.symbol for s in self.context.sbot['symbols']],
        )
        self.assertEqual(
            self.context.sbot['capital_ppt'],
            1.0 / len(self.context.sbot['symbols']),
        )
示例#3
0
def backtest():
    df = utils.get_dataframe_with_code("005440")
    # df = utils.add_이동평균선_to_dataframe(df, [5, 20])

    # df은 오름차순으로 되어 있다.

    # serialdatetime = [pd.to_datetime(bb, utc="UTC", format="%Y%m%d") for bb in df.index]
    serialdatetime = [dt.strptime(str(bb), "%Y%m%d") for bb in df.index]

    # dtstart = serialdatetime[0].astimezone(pytz.utc)
    # dtend = serialdatetime[-1].astimezone(pytz.utc)

    # dtstart = serialdatetime[0]
    # dtend = serialdatetime[-1]

    # dtstart = dt(2001, 1, 2, 0, 0, 0, 0, pytz.utc)
    # dtend = dt(2017, 9, 29, 0, 0, 0, 0, pytz.utc)

    start = str(df.index[0]) + "%s"
    dtstart = dt.strptime(start % ("000000"),
                          "%Y%m%d%H%M%S").astimezone(pytz.utc)

    end = str(df.index[-1]) + "%s"
    dtend = dt.strptime(end % ("000000"), "%Y%m%d%H%M%S").astimezone(pytz.utc)

    # dtstart = dt(2001, 1, 2)
    # dtend = dt(2017, 9, 29 )
    #
    # indexnew = pd.date_range('2001/1/2', periods=4119)
    # indexnew = indexnew.tz_localize(None)

    df = df.set_index(pd.DatetimeIndex(serialdatetime))
    data = df[["현재가"]]
    data.columns = ['종가']
    # data = data.tz_localize(pytz.utc)

    print("data length :%s" % (len(data)))

    dfresult = run_algorithm(dtstart,
                             dtend,
                             initialize,
                             100000000.0,
                             handle_data,
                             data_frequency='daily',
                             data=data)
    #
    # algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data)
    # dfresult = algo.run(data)

    plt.plot(dfresult.index, dfresult.portfolio_value)
    plt.show()
示例#4
0
    def test_adx_sar_so(self):
        '''
        ensure adx_sar_so trading system runs without exceptions
        '''

        end = get_calendar('NYSE').previous_close(Timestamp.utcnow())
        start = get_calendar('NYSE').previous_close(end - DateOffset(months=2))

        res = run_algorithm(
            start=start,
            end=end,
            initialize=adx_sar_so.initialize,
            handle_data=adx_sar_so.handle_data,
            capital_base=float('1.0e5'),
        )
        self.assertNotEqual(res['alpha'][-1], 0.0)
示例#5
0
    def test_zipline(self):
        '''
        a do-nothing algo to test zipline through latest close
        '''
        def initialize(context):
            pass

        end = get_calendar('NYSE').previous_close(Timestamp.utcnow())
        start = get_calendar('NYSE').previous_close(end - DateOffset(years=1))

        res = run_algorithm(
            start=start,
            end=end,
            initialize=initialize,
            capital_base=float('1.0e5'),
        )

        self.assertTrue(start in res.index and end in res.index)
示例#6
0
def temp2():
    df = pd.read_hdf("test100.hdf", "day")
    datelen = len(df)

    # start = dt.strptime("20170101%s"%("000000"), "%Y%m%d%H%M%S").astimezone(pytz.utc)
    # end = dt.strptime("20170410%s"%("000000"), "%Y%m%d%H%M%S").astimezone(pytz.utc)

    start = dt(2017, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = dt(2017, 4, 10, 0, 0, 0, 0, pytz.utc)

    # start = datetime.datetime(2017, 1, 1)
    # end = datetime.datetime(2017, 4, 10)

    # data = web.DataReader("종가", "yahoo", start, end)

    # rawdata = [ aa for aa in range(datelen)]
    rawdata = df["현재가"].tolist()
    # daterange = pd.date_range('2017/1/1', periods=datelen)
    daterange = pd.date_range(start, end)
    data = pd.DataFrame(rawdata, daterange, ['종가'])
    # data = data.tz_localize('UTC')

    result = run_algorithm(start,
                           end,
                           initialize,
                           100000000.0,
                           handle_data,
                           data_frequency='daily',
                           data=data)

    # algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data)
    # result = algo.run(data)

    plt.plot(result.index, result.ma5)
    plt.plot(result.index, result.ma20)
    plt.legend(loc='best')

    plt.show()
示例#7
0
def main():
    args = parse_arguments()
    # Set tz to avoid TypeError: Cannot compare tz-naive and tz-aware timestamps pandas issue
    # This shold be fixed in 0.23
    start = (pd.to_datetime('2017-08-01') + BDay(1)).tz_localize('UTC')
    end = (pd.to_datetime('2018-08-28') + BDay(1)).tz_localize('UTC')

    # TODO: Add start/end date setup
    # start = pd.Timestamp(args.from_date, tz='utc') if args.from_date else None
    # end = pd.Timestamp(args.to_date, tz='utc') if args.to_date else None

    backtest = run_algorithm(start,
                             end,
                             initialize,
                             args.capital_base,
                             before_trading_start=before_trading_start,
                             analyze=analyze,
                             bundle='iex-csvdir-bundle')
    returns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(
        backtest)
    # TODO: The backtest benchmark graphs/data are not looking good, check why is this happening.
    benchmark_rets = None  # backtest.benchmark_period_return
    plotting.create_simple_tear_sheet(returns,
                                      positions=positions,
                                      transactions=transactions,
                                      benchmark_rets=benchmark_rets,
                                      file_name=os.path.join(
                                          working_dir,
                                          export_file_format.format('simple')))

    plotting.create_returns_tear_sheet(
        returns,
        positions=positions,
        transactions=transactions,
        benchmark_rets=benchmark_rets,
        file_name=os.path.join(working_dir,
                               export_file_format.format('returns')))
示例#8
0
            order(symbol('002450'), 300, limit_price=buy_price)
            buy_status = True


if __name__ == '__main__':
    from zipline.utils.cli import Date
    from zipline.utils.run_algo import run_algorithm
    from zipline.gens.brokers.tdx_shipane_broker import TdxShipaneBroker
    from zipline.gens.shipane_client import ShipaneClient
    import pandas as pd
    import os
    import datetime

    if platform.architecture()[0] == '32bit':
        client_uri = 'config.json'
    else:
        client_uri = "tcp://127.0.0.1:4242"

    shipane_client = ShipaneClient(client_key="1")
    broker = TdxShipaneBroker(client_uri, shipane_client)
    if not os.path.exists('tmp'):
        os.mkdir('tmp')
    realtime_bar_target = 'tmp/real-bar-{}'.format(str(pd.to_datetime('today').date()))
    state_filename = 'tmp/live-state'

    start = Date(tz='utc', as_timestamp=True).parser('2017-10-01')

    end = Date(tz='utc', as_timestamp=True).parser(datetime.datetime.now().strftime("%Y-%m-%d"))
    run_algorithm(start, end, initialize, 10e6, handle_data=handle_data, bundle='tdx',
                  trading_calendar='SHSZ', data_frequency="minute", output='out.pickle',
                  broker=broker, state_filename=state_filename, realtime_bar_target=realtime_bar_target)