예제 #1
0
    def test_account_in_init(self):
        """
        Test that accessing account in init doesn't break.
        """
        test_algo = TradingAlgorithm(
            script=access_account_in_init,
            sim_params=self.sim_params,
        )
        set_algo_instance(test_algo)

        self.zipline_test_config['algorithm'] = test_algo
        self.zipline_test_config['trade_count'] = 1

        zipline = simfactory.create_test_zipline(
            **self.zipline_test_config)

        output, _ = drain_zipline(self, zipline)
예제 #2
0
    def test_pipeline_beyond_daily_bars(self):
        """
        Ensure that we can run an algo with pipeline beyond the max date
        of the daily bars.
        """

        # For ensuring we call before_trading_start.
        count = [0]

        current_day = default_nyse_schedule.next_execution_day(
            self.pipeline_loader.raw_price_loader.last_available_dt, )

        def initialize(context):
            pipeline = attach_pipeline(Pipeline(), 'test')

            vwap = VWAP(window_length=10)
            pipeline.add(vwap, 'vwap')

            # Nothing should have prices less than 0.
            pipeline.set_screen(vwap < 0)

        def handle_data(context, data):
            pass

        def before_trading_start(context, data):
            context.results = pipeline_output('test')
            self.assertTrue(context.results.empty)
            count[0] += 1

        algo = TradingAlgorithm(
            initialize=initialize,
            handle_data=handle_data,
            before_trading_start=before_trading_start,
            data_frequency='daily',
            get_pipeline_loader=lambda column: self.pipeline_loader,
            start=self.dates[0],
            end=current_day,
            env=self.env,
        )

        algo.run(
            FakeDataPortal(),
            overwrite_sim_params=False,
        )

        self.assertTrue(count[0] > 0)
예제 #3
0
    def _algo_record_float_magic_should_pass(self, var_type):
        test_algo = TradingAlgorithm(
            script=record_float_magic % var_type,
            sim_params=self.sim_params,
        )
        set_algo_instance(test_algo)

        self.zipline_test_config['algorithm'] = test_algo
        self.zipline_test_config['trade_count'] = 200

        zipline = simfactory.create_test_zipline(**self.zipline_test_config)
        output, _ = drain_zipline(self, zipline)
        self.assertEqual(len(output), 252)
        incr = []
        for o in output[:200]:
            incr.append(o['daily_perf']['recorded_vars']['data'])
        np.testing.assert_array_equal(incr, [np.nan] * 200)
예제 #4
0
    def test_history(self):
        history_algo = """
from zipline.api import history, add_history

def initialize(context):
    add_history(10, '1d', 'price')

def handle_data(context, data):
    df = history(10, '1d', 'price')
"""

        algo = TradingAlgorithm(
            script=history_algo,
            sim_params=self.sim_params,
        )
        output = algo.run(self.source)
        self.assertIsNot(output, None)
예제 #5
0
    def test_order_methods(self):
        """
        Only test that order methods can be called without error.
        Correct filling of orders is tested in zipline.
        """
        test_algo = TradingAlgorithm(
            script=call_all_order_methods,
            sim_params=self.sim_params,
        )
        set_algo_instance(test_algo)

        self.zipline_test_config['algorithm'] = test_algo
        self.zipline_test_config['trade_count'] = 200

        zipline = simfactory.create_test_zipline(**self.zipline_test_config)

        output, _ = drain_zipline(self, zipline)
예제 #6
0
    def test_assets_appear_on_correct_days(self, test_name, chunksize):
        """
        Assert that assets appear at correct times during a backtest, with
        correctly-adjusted close price values.
        """

        if chunksize == 'all_but_one_day':
            chunksize = (
                self.dates.get_loc(self.last_asset_end) -
                self.dates.get_loc(self.first_asset_start)
            ) - 1

        def initialize(context):
            p = attach_pipeline(Pipeline(), 'test', chunksize=chunksize)
            p.add(USEquityPricing.close.latest, 'close')

        def handle_data(context, data):
            results = pipeline_output('test')
            date = get_datetime().normalize()
            for asset in self.assets:
                # Assets should appear iff they exist today and yesterday.
                exists_today = self.exists(date, asset)
                existed_yesterday = self.exists(date - trading_day, asset)
                if exists_today and existed_yesterday:
                    latest = results.loc[asset, 'close']
                    self.assertEqual(latest, self.expected_close(date, asset))
                else:
                    self.assertNotIn(asset, results.index)

        before_trading_start = handle_data

        algo = TradingAlgorithm(
            initialize=initialize,
            handle_data=handle_data,
            before_trading_start=before_trading_start,
            data_frequency='daily',
            get_pipeline_loader=lambda column: self.pipeline_loader,
            start=self.first_asset_start,
            end=self.last_asset_end,
            env=self.env,
        )

        # Run for a week in the middle of our data.
        algo.run(source=self.closes.loc[self.first_asset_start:
                                        self.last_asset_end])
예제 #7
0
    def test_multiple_pipelines(self):
        """
        Test that we can attach multiple pipelines and access the correct
        output based on the pipeline name.
        """
        def initialize(context):
            pipeline_close = attach_pipeline(Pipeline(), 'test_close')
            pipeline_volume = attach_pipeline(Pipeline(), 'test_volume')

            pipeline_close.add(USEquityPricing.close.latest, 'close')
            pipeline_volume.add(USEquityPricing.volume.latest, 'volume')

        def handle_data(context, data):
            closes = pipeline_output('test_close')
            volumes = pipeline_output('test_volume')
            date = get_datetime().normalize()
            for asset in self.assets:
                # Assets should appear iff they exist today and yesterday.
                exists_today = self.exists(date, asset)
                existed_yesterday = self.exists(date - self.trading_day, asset)
                if exists_today and existed_yesterday:
                    self.assertEqual(closes.loc[asset, 'close'],
                                     self.expected_close(date, asset))
                    self.assertEqual(volumes.loc[asset, 'volume'],
                                     self.expected_volume(date, asset))
                else:
                    self.assertNotIn(asset, closes.index)
                    self.assertNotIn(asset, volumes.index)

        column_to_loader = {
            USEquityPricing.close: self.pipeline_close_loader,
            USEquityPricing.volume: self.pipeline_volume_loader,
        }

        algo = TradingAlgorithm(
            initialize=initialize,
            handle_data=handle_data,
            data_frequency='daily',
            get_pipeline_loader=lambda column: column_to_loader[column],
            start=self.first_asset_start,
            end=self.last_asset_end,
            env=self.env,
        )

        algo.run(self.data_portal)
예제 #8
0
    def test_register_post_init(self):
        def initialize(algo):
            algo.initialized = True

        def handle_data(algo, data):

            with self.assertRaises(RegisterTradingControlPostInit):
                algo.set_max_position_size(self.sid, 1, 1)
            with self.assertRaises(RegisterTradingControlPostInit):
                algo.set_max_order_size(self.sid, 1, 1)
            with self.assertRaises(RegisterTradingControlPostInit):
                algo.set_max_order_count(1)
            with self.assertRaises(RegisterTradingControlPostInit):
                algo.set_long_only()

        algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data)
        algo.run(self.source)
        self.source.rewind()
예제 #9
0
    def test_history(self):
        history_algo = """
from zipline.api import history, add_history

def initialize(context):
    add_history(10, '1d', 'price')

def handle_data(context, data):
    df = history(10, '1d', 'price')
"""
        start = pd.Timestamp('1991-01-01', tz='UTC')
        end = pd.Timestamp('1991-01-15', tz='UTC')
        source = RandomWalkSource(start=start, end=end)
        sim_params = factory.create_simulation_parameters(
            data_frequency='minute')
        algo = TradingAlgorithm(script=history_algo, sim_params=sim_params)
        output = algo.run(source)
        self.assertIsNot(output, None)
예제 #10
0
    def test_algo_record_vars(self):
        test_algo = TradingAlgorithm(
            script=record_variables,
            sim_params=self.sim_params,
        )
        set_algo_instance(test_algo)

        self.zipline_test_config['algorithm'] = test_algo
        self.zipline_test_config['trade_count'] = 200

        zipline = simfactory.create_test_zipline(**self.zipline_test_config)
        output, _ = drain_zipline(self, zipline)
        self.assertEqual(len(output), 252)
        incr = []
        for o in output[:200]:
            incr.append(o['daily_perf']['recorded_vars']['incr'])

        np.testing.assert_array_equal(incr, range(1, 201))
예제 #11
0
    def test_zipline_api_resolves_dynamically(self):
        # Make a dummy algo.
        algo = TradingAlgorithm(
            initialize=lambda context: None,
            handle_data=lambda context, data: None,
            sim_params=self.sim_params,
        )

        # Verify that api methods get resolved dynamically by patching them out
        # and then calling them
        for method in algo.all_api_methods():
            name = method.__name__
            sentinel = object()

            def fake_method(*args, **kwargs):
                return sentinel
            setattr(algo, name, fake_method)
            with ZiplineAPI(algo):
                self.assertIs(sentinel, getattr(zipline.api, name)())
예제 #12
0
    def test_duplicate_pipeline_names(self):
        """
        Test that we raise an error when we try to attach a pipeline with a
        name that already exists for another attached pipeline.
        """
        def initialize(context):
            attach_pipeline(Pipeline(), 'test')
            attach_pipeline(Pipeline(), 'test')

        algo = TradingAlgorithm(
            initialize=initialize,
            data_frequency='daily',
            get_pipeline_loader=lambda column: self.pipeline_close_loader,
            start=self.first_asset_start,
            end=self.last_asset_end,
            env=self.env,
        )

        with self.assertRaises(DuplicatePipelineName):
            algo.run(self.data_portal)
예제 #13
0
    def test_get_environment(self):
        expected_env = {
            'arena': 'backtest',
            'data_frequency': 'minute',
            'start': pd.Timestamp('2006-01-03 14:31:00+0000', tz='UTC'),
            'end': pd.Timestamp('2006-01-04 21:00:00+0000', tz='UTC'),
            'capital_base': 100000.0,
            'platform': 'zipline'
        }

        def initialize(algo):
            self.assertEqual('zipline', algo.get_environment())
            self.assertEqual(expected_env, algo.get_environment('*'))

        def handle_data(algo, data):
            pass

        algo = TradingAlgorithm(initialize=initialize,
                                handle_data=handle_data,
                                sim_params=self.sim_params)
        algo.run(self.source)
예제 #14
0
    def test_get_datetime(self, name, tz):

        algo = dedent(
            """
            import pandas as pd
            from zipline.api import get_datetime

            def initialize(context):
                context.tz = {tz} or 'UTC'
                context.first_bar = True

            def handle_data(context, data):
                if context.first_bar:
                    dt = get_datetime({tz})
                    if dt.tz.zone != context.tz:
                        raise ValueError("Mismatched Zone")
                    elif dt.tz_convert("US/Eastern").hour != 9:
                        raise ValueError("Mismatched Hour")
                    elif dt.tz_convert("US/Eastern").minute != 31:
                        raise ValueError("Mismatched Minute")
                context.first_bar = False
            """.format(tz=repr(tz))
        )

        start = to_utc('2014-01-02 9:31')
        end = to_utc('2014-01-03 9:31')
        source = RandomWalkSource(
            start=start,
            end=end,
        )
        sim_params = factory.create_simulation_parameters(
            data_frequency='minute'
        )
        algo = TradingAlgorithm(
            script=algo,
            sim_params=sim_params,
            identifiers=[1]
        )
        algo.run(source)
        self.assertFalse(algo.first_bar)
예제 #15
0
    def test_asset_lookup(self):
        metadata = {0: {'symbol': 'PLAY',
                        'asset_type': 'equity',
                        'start_date': '2002-01-01',
                        'end_date': '2004-01-01'},
                    1: {'symbol': 'PLAY',
                        'asset_type': 'equity',
                        'start_date': '2005-01-01',
                        'end_date': '2006-01-01'}}
        algo = TradingAlgorithm(asset_metadata=metadata)

        # Test before either PLAY existed
        algo.datetime = pd.Timestamp('2001-12-01', tz='UTC')
        with self.assertRaises(SymbolNotFound):
            algo.symbol('PLAY')
        with self.assertRaises(SymbolNotFound):
            algo.symbols('PLAY')

        # Test when first PLAY exists
        algo.datetime = pd.Timestamp('2002-12-01', tz='UTC')
        list_result = algo.symbols('PLAY')
        self.assertEqual(0, list_result[0])

        # Test after first PLAY ends
        algo.datetime = pd.Timestamp('2004-12-01', tz='UTC')
        self.assertEqual(0, algo.symbol('PLAY'))

        # Test after second PLAY begins
        algo.datetime = pd.Timestamp('2005-12-01', tz='UTC')
        self.assertEqual(1, algo.symbol('PLAY'))

        # Test after second PLAY ends
        algo.datetime = pd.Timestamp('2006-12-01', tz='UTC')
        self.assertEqual(1, algo.symbol('PLAY'))
        list_result = algo.symbols('PLAY')
        self.assertEqual(1, list_result[0])

        # Test lookup SID
        self.assertIsInstance(algo.sid(0), Equity)
        self.assertIsInstance(algo.sid(1), Equity)
def agent_train(data_train):
    """Train the agent
       Learn from the environment
    """
    for iter in range(0, Q_training_iters):
        gv.mylogger.logger.info("Agent Iteration :" + str(iter + 1))

        # Create algorithm object passing in initialize,
        # handle_data functions and so on
        algo = TradingAlgorithm(initialize=train.initialize,
                                handle_data=train.handle_data,
                                data_frequency='daily',
                                capital_base=gv.capital_base)

        # Run algorithm
        perf = algo.run(data_train)

        # Train neural network with produced training set
        Q_update()

        # Update epsilon
        gv.epsilon = pow(gv.epsilon, iter + 2)
예제 #17
0
    def test_empty_pipeline(self):

        # For ensuring we call before_trading_start.
        count = [0]

        def initialize(context):
            pipeline = attach_pipeline(Pipeline(), 'test')

            vwap = VWAP(window_length=10)
            pipeline.add(vwap, 'vwap')

            # Nothing should have prices less than 0.
            pipeline.set_screen(vwap < 0)

        def handle_data(context, data):
            pass

        def before_trading_start(context, data):
            context.results = pipeline_output('test')
            self.assertTrue(context.results.empty)
            count[0] += 1

        algo = TradingAlgorithm(
            initialize=initialize,
            handle_data=handle_data,
            before_trading_start=before_trading_start,
            data_frequency='daily',
            get_pipeline_loader=lambda column: self.pipeline_loader,
            start=self.dates[0],
            end=self.dates[-1],
            env=self.env,
        )

        algo.run(
            FakeDataPortal(),
            overwrite_sim_params=False,
        )

        self.assertTrue(count[0] > 0)
예제 #18
0
def worker(args):
    """thread worker function"""
    period, bottom, top, shift, max_long, prob_window, prob = args

    algo_obj = TradingAlgorithm(initialize=initialize,
                                handle_data=handle_data,
                                analyze=analyze,
                                sim_params=sim_params)

    algo_obj.RSI_PERIOD = period
    algo_obj.RSI_BOTTOM, algo_obj.RSI_TOP, algo_obj.RSI_SHIFT = bottom, top, shift
    algo_obj.MAX_LONG, algo_obj.MAX_SHORT = max_long, max_long
    algo_obj.PROB_WINDOW = prob_window
    algo_obj.MIN_PROB = prob

    perf = algo_obj.run(data, overwrite_sim_params=False)
    print(("Returns: {0:.2f}% MaxDrawdown: {1:.2f}% " +
           "Benchmark: {2:.2f}% Args: {3}").format(
               perf.algorithm_period_return[-1] * 100,
               perf.max_drawdown[-1] * 100,
               perf.benchmark_period_return[-1] * 100, args))

    return
예제 #19
0
    def test_schedule_function(self):
        date_rules = DateRuleFactory
        time_rules = TimeRuleFactory

        def incrementer(algo, data):
            algo.func_called += 1
            self.assertEqual(
                algo.get_datetime().time(),
                datetime.time(hour=14, minute=31),
            )

        def initialize(algo):
            algo.func_called = 0
            algo.days = 1
            algo.date = None
            algo.schedule_function(
                func=incrementer,
                date_rule=date_rules.every_day(),
                time_rule=time_rules.market_open(),
            )

        def handle_data(algo, data):
            if not algo.date:
                algo.date = algo.get_datetime().date()

            if algo.date < algo.get_datetime().date():
                algo.days += 1
                algo.date = algo.get_datetime().date()

        algo = TradingAlgorithm(
            initialize=initialize,
            handle_data=handle_data,
            sim_params=self.sim_params,
        )
        algo.run(self.source)

        self.assertEqual(algo.func_called, algo.days)
예제 #20
0
파일: olmar.py 프로젝트: otmaneJai/Zipline
# Note: this function can be removed if running
# this algorithm on quantopian.com
def analyze(context=None, results=None):
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(111)
    results.portfolio_value.plot(ax=ax)
    ax.set_ylabel('Portfolio value (USD)')
    plt.show()


# Note: this if-block should be removed if running
# this algorithm on quantopian.com
if __name__ == '__main__':
    # Set the simulation start and end dates.
    start = datetime(2004, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc)

    # Load price data from yahoo.
    data = load_from_yahoo(stocks=STOCKS, indexes={}, start=start, end=end)
    data = data.dropna()

    # Create and run the algorithm.
    olmar = TradingAlgorithm(handle_data=handle_data,
                             initialize=initialize,
                             identifiers=STOCKS)
    results = olmar.run(data)

    # Plot the portfolio data.
    analyze(results=results)
예제 #21
0
    def test_volshare_slippage(self):
        # verify order -> transaction -> portfolio position.
        # --------------
        test_algo = TradingAlgorithm(
            script="""
from zipline.api import *

def initialize(context):
    model = slippage.VolumeShareSlippage(
                            volume_limit=.3,
                            price_impact=0.05
                       )
    set_slippage(model)
    set_commission(commission.PerShare(0.02))
    context.count = 2
    context.incr = 0

def handle_data(context, data):
    if context.incr < context.count:
        # order small lots to be sure the
        # order will fill in a single transaction
        order(0, 5000)
    record(price=data[0].price)
    record(volume=data[0].volume)
    record(incr=context.incr)
    context.incr += 1
    """,
            sim_params=self.sim_params,
        )
        set_algo_instance(test_algo)

        self.zipline_test_config['algorithm'] = test_algo
        self.zipline_test_config['trade_count'] = 100

        # 67 will be used inside assert_single_position
        # to confirm we have as many transactions as expected.
        # The algo places 2 trades of 5000 shares each. The trade
        # events have volume ranging from 100 to 950. The volume cap
        # of 0.3 limits the trade volume to a range of 30 - 316 shares.
        # The spreadsheet linked below calculates the total position
        # size over each bar, and predicts 67 txns will be required
        # to fill the two orders. The number of bars and transactions
        # differ because some bars result in multiple txns. See
        # spreadsheet for details:
# https://www.dropbox.com/s/ulrk2qt0nrtrigb/Volume%20Share%20Worksheet.xlsx
        self.zipline_test_config['expected_transactions'] = 67

        # self.zipline_test_config['transforms'] = \
        #     test_algo.transform_visitor.transforms.values()

        zipline = simfactory.create_test_zipline(
            **self.zipline_test_config)
        output, _ = assert_single_position(self, zipline)

        # confirm the slippage and commission on a sample
        # transaction
        per_share_commish = 0.02
        perf = output[1]
        transaction = perf['daily_perf']['transactions'][0]
        commish = transaction['amount'] * per_share_commish
        self.assertEqual(commish, transaction['commission'])
        self.assertEqual(2.029, transaction['price'])
예제 #22
0
 def test_api_symbol(self):
     algo = TradingAlgorithm(script=api_symbol_algo)
     algo.run(self.df)
예제 #23
0
 def test_api_calls_string(self):
     algo = TradingAlgorithm(script=api_algo)
     algo.run(self.df)
예제 #24
0
 def test_api_calls(self):
     algo = TradingAlgorithm(initialize=initialize_api,
                             handle_data=handle_data_api)
     algo.run(self.df)
예제 #25
0
 def test_noop_string(self):
     algo = TradingAlgorithm(script=noop_algo)
     algo.run(self.df)
예제 #26
0
 def test_noop(self):
     algo = TradingAlgorithm(initialize=initialize_noop,
                             handle_data=handle_data_noop)
     algo.run(self.df)
예제 #27
0
파일: views.py 프로젝트: ajmal017/FindMore
    def form_valid(self, form):
        # SMA data prepare
        sma = form.save(commit=False)

        name = form.cleaned_data['name']
        code = form.cleaned_data['code']
        market = form.cleaned_data['market']
        short_ma = form.cleaned_data['short_ma']
        long_ma = form.cleaned_data['long_ma']
        buy_quantity = form.cleaned_data['buy_quantity']
        sell_quantity = form.cleaned_data['sell_quantity']
        capital_base = form.cleaned_data['capital_base']
        start_date = form.cleaned_data['start_date']
        end_date = form.cleaned_data['end_date']

        # Backtesting
        def initialize(context):
            context.i = 0
            context.symbol = symbol(name)
            context.hold = False

        def handle_data(context, data):
            context.i += 1
            if context.i < long_ma:
                return

            buy = False
            sell = False
            short_mavg = data.history(context.symbol, 'price', short_ma,
                                      '1d').mean()
            long_mavg = data.history(context.symbol, 'price', long_ma,
                                     '1d').mean()

            if short_mavg > long_mavg and context.hold == False:
                order(context.symbol, buy_quantity)
                context.hold = True
                buy = True
            elif short_mavg < long_mavg and context.hold == True:
                order(context.symbol, -sell_quantity)
                context.hold = False
                sell = True

            record(Price=data.current(context.symbol,'price'),short_mavg=short_mavg, \
                        long_mavg=long_mavg,buy=buy,sell=sell)

        # Data preparing
        df = fdr.DataReader(code, start_date, end_date)
        data = df[['Close']]
        data.columns = [name]
        xkrx = get_calendar('XKRX')

        # Call backtesting
        if market == 'KOSPI' or market == 'KOSDAQ':
            algo = TradingAlgorithm(sim_params=create_simulation_parameters(capital_base=capital_base,\
                    trading_calendar=xkrx),initialize=initialize,handle_data=handle_data,trading_calendar=xkrx)
            result = algo.run(data)
        elif market == 'NASDAQ':
            algo = TradingAlgorithm(sim_params=create_simulation_parameters(capital_base=capital_base),\
                    initialize=initialize,handle_data=handle_data)
            result = algo.run(data)

        # Quantile plot and save
        now = timezone.now()
        file_home = '/home/seungyong/FindMore/static/'
        bt_file_name = name + '_' + str(now) + '_SMA-BT.png'
        bt_file_path = file_home + bt_file_name
        bt_static_path = '/static/' + bt_file_name

        pv_file_name = name + '_' + str(now) + '_SMA-PV.png'
        pv_file_path = file_home + pv_file_name
        pv_static_path = '/static/' + pv_file_name

        plt.plot(result.index, result.Price)
        plt.plot(result.index, result.short_mavg)
        plt.plot(result.index, result.long_mavg)
        plt.legend(loc='best')
        if sell_quantity > 0:
            plt.plot(result.loc[result.buy == True].index,
                     result.short_mavg[result.buy == True],
                     '^',
                     color='r',
                     markersize=5)
            plt.plot(result.loc[result.sell == True].index,
                     result.short_mavg[result.sell == True],
                     'v',
                     color='g',
                     markersize=5)
        elif sell_quantity == 0:
            plt.plot(result.loc[result.buy == True].index,
                     result.short_mavg[result.buy == True],
                     '^',
                     color='r',
                     markersize=5)
        plt.savefig(bt_file_path, dpi=150)
        plt.clf()

        plt.plot(result.index, result.portfolio_value)
        plt.savefig(pv_file_path, dpi=150)
        plt.clf()

        # SMA result insert
        sma.name = name
        sma.code = code
        sma.market = market
        sma.start_date = start_date
        sma.end_date = end_date
        sma.short_ma = short_ma
        sma.long_ma = long_ma
        sma.buy_quantity = buy_quantity
        sma.sell_quantity = sell_quantity
        sma.capital_base = capital_base
        sma.last_pv = result.portfolio_value[-1]
        sma.last_value = result.ending_value[-1]
        sma.last_cash = result.ending_cash[-1]
        sma.capital_used = sum(result.capital_used)
        if result.positions.values[-1] == []:
            sma.shares = 0
            sma.expected_return = (
                (result.ending_cash[-1] / capital_base) - 1) * 100
        elif result.positions.values[-1] != []:
            sma.shares = result.positions.values[-1][0]['amount']
            sma.expected_return = (
                (result.portfolio_value[-1] / capital_base) - 1) * 100
        sma.bt_path = bt_static_path
        sma.pv_path = pv_static_path

        form.save()

        return super(SMACreateView, self).form_valid(form)
예제 #28
0
            year += 1
        data[each] = result

    columns = ['date'].extend(column)
    return DataFrame(data, index=date, columns=None)


# Define algorithm
def initialize(context):
    pass


def handle_data(context, data):
    order('Close', 10)
    record(Close=data['Close'])


data = generate_data('sh600000', '2010-01-01', '2015-01-01',
                     ['open', 'high', 'low', 'close'])
print data

# Create algorithm object passing in initialize and
# handle_data functions
algo_obj = TradingAlgorithm(initialize=initialize, handle_data=handle_data)

# Run algorithm
perf_manual = algo_obj.run(data)

# Print
perf_manual.to_csv('output.csv')
예제 #29
0
def before_trading_start(context, data):
    context.pipeline_data = pipeline_output('my_pipeline')
    #print("pipeline_data",type(context.pipeline_data))
    #print(context.portfolio)
    pass


#################################################################################################################################################
for i in range(0, len(g_models)):
    #for i in range(0,4):
    g_idx = i
    algor_obj = TradingAlgorithm(
        initialize=initialize,
        handle_data=handle_data,
        before_trading_start=before_trading_start,
        sim_params=sim_params,
        env=trading_environment,
        data_frequency='daily',
        get_pipeline_loader=choose_loader,
    )

    result = algor_obj.run(data)
    #result.to_csv("result.csv", encoding="utf-8")
    #print(result)

    # for index,values in  result.iterrows():
    #     print index
    #     for t in values['transactions']:
    #         print t
    #     print "++++++++++++++++++++++++++++++++++++++++++++"
예제 #30
0
def _run(handle_data, initialize, before_trading_start, analyze, algofile,
         algotext, defines, data_frequency, capital_base, data, bundle,
         bundle_timestamp, start, end, algo_params, bm_symbol, output,
         print_algo, local_namespace, environ):
    """Run a backtest for the given algorithm.

    This is shared between the cli and :func:`zipline.run_algo`.
    """
    if algotext is not None:
        if local_namespace:
            ip = get_ipython()  # noqa
            namespace = ip.user_ns
        else:
            namespace = {}

        for assign in defines:
            try:
                name, value = assign.split('=', 2)
            except ValueError:
                raise ValueError(
                    'invalid define %r, should be of the form name=value' %
                    assign, )
            try:
                # evaluate in the same namespace so names may refer to
                # eachother
                namespace[name] = eval(value, namespace)
            except Exception as e:
                raise ValueError(
                    'failed to execute definition for name %r: %s' %
                    (name, e), )
    elif defines:
        raise _RunAlgoError(
            'cannot pass define without `algotext`',
            "cannot pass '-D' / '--define' without '-t' / '--algotext'",
        )
    else:
        namespace = {}
        if algofile is not None:
            algotext = algofile.read()

    if print_algo:
        if PYGMENTS:
            highlight(
                algotext,
                PythonLexer(),
                TerminalFormatter(),
                outfile=sys.stdout,
            )
        else:
            click.echo(algotext)

    if bundle is not None:
        bundle_data = load(
            bundle,
            environ,
            bundle_timestamp,
        )

        prefix, connstr = re.split(
            r'sqlite:///',
            str(bundle_data.asset_finder.engine.url),
            maxsplit=1,
        )
        if prefix:
            raise ValueError(
                "invalid url %r, must begin with 'sqlite:///'" %
                str(bundle_data.asset_finder.engine.url), )
        env = TradingEnvironment(bm_symbol=bm_symbol, asset_db_path=connstr)
        #env = TradingEnvironment(bm_symbol='000001',
        #                         exchange_tz='Asia/Shanghai',
        #                         trading_calendar=get_calendar('SHSZ'),
        #                         asset_db_path=connstr)
        first_trading_day =\
            bundle_data.equity_minute_bar_reader.first_trading_day
        data = DataPortal(
            env.asset_finder,
            get_calendar("SHSZ"),
            first_trading_day=first_trading_day,
            equity_minute_reader=bundle_data.equity_minute_bar_reader,
            equity_daily_reader=bundle_data.equity_daily_bar_reader,
            adjustment_reader=bundle_data.adjustment_reader,
        )

        pipeline_loader = USEquityPricingLoader(
            bundle_data.equity_daily_bar_reader,
            bundle_data.adjustment_reader,
        )

        def choose_loader(column):
            if column in USEquityPricing.columns:
                return pipeline_loader
            raise ValueError("No PipelineLoader registered for column %s." %
                             column)
    else:
        env = TradingEnvironment(environ=environ)
        choose_loader = None

    perf = TradingAlgorithm(
        namespace=namespace,
        #capital_base=capital_base,
        algo_params=algo_params,
        env=env,
        get_pipeline_loader=choose_loader,
        sim_params=create_simulation_parameters(
            start=start,
            end=end,
            capital_base=capital_base,
            data_frequency=data_frequency,
            trading_calendar=get_calendar("SHSZ"),
        ),
        **{
            'initialize': initialize,
            'handle_data': handle_data,
            'before_trading_start': before_trading_start,
            'analyze': analyze,
        } if algotext is None else {
            'algo_filename': getattr(algofile, 'name', '<algorithm>'),
            'script': algotext,
        }).run(
            data,
            overwrite_sim_params=False,
        )

    if output == '-':
        click.echo(str(perf))
    elif output != os.devnull:  # make the zipline magic not write any data
        perf.to_pickle(output)

    return perf