当前位置: 首页>>代码示例>>Python>>正文


Python TradingAlgorithm.run方法代码示例

本文整理汇总了Python中zipline.TradingAlgorithm.run方法的典型用法代码示例。如果您正苦于以下问题:Python TradingAlgorithm.run方法的具体用法?Python TradingAlgorithm.run怎么用?Python TradingAlgorithm.run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在zipline.TradingAlgorithm的用法示例。


在下文中一共展示了TradingAlgorithm.run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_history_container_constructed_at_runtime

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_history_container_constructed_at_runtime(self):
        algo_text = dedent(
            """\
            from zipline.api import history
            def handle_data(context, data):
                context.prices = history(2, '1d', 'price')
            """
        )
        start = pd.Timestamp('2007-04-05', tz='UTC')
        end = pd.Timestamp('2007-04-10', tz='UTC')

        sim_params = SimulationParameters(
            period_start=start,
            period_end=end,
            capital_base=float("1.0e5"),
            data_frequency='minute',
            emission_rate='daily'
        )

        test_algo = TradingAlgorithm(
            script=algo_text,
            data_frequency='minute',
            sim_params=sim_params
        )

        source = RandomWalkSource(start=start, end=end)

        self.assertIsNone(test_algo.history_container)
        test_algo.run(source)
        self.assertIsNotNone(
            test_algo.history_container,
            msg='HistoryContainer was not constructed at runtime',
        )

        container = test_algo.history_container
        self.assertEqual(
            container.buffer_panel.window_length,
            Frequency.MAX_MINUTES['d'],
            msg='HistoryContainer.buffer_panel was not large enough to service'
            ' the given HistorySpec',
        )

        self.assertEqual(
            len(container.digest_panels),
            1,
            msg='The HistoryContainer created too many digest panels',
        )

        freq, digest = list(container.digest_panels.items())[0]
        self.assertEqual(
            freq.unit_str,
            'd',
        )

        self.assertEqual(
            digest.window_length,
            1,
            msg='The digest panel is not large enough to service the given'
            ' HistorySpec',
        )
开发者ID:CallingWisdom,项目名称:zipline,代码行数:62,代码来源:test_history.py

示例2: test_history_daily_data_1m_window

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_history_daily_data_1m_window(self):
        algo_text = """
from zipline.api import history, add_history

def initialize(context):
    add_history(bar_count=1, frequency='1m', field='price')

def handle_data(context, data):
    prices = history(bar_count=3, frequency='1d', field='price')
""".strip()

        start = pd.Timestamp('2006-03-20', tz='UTC')
        end = pd.Timestamp('2006-03-30', tz='UTC')

        sim_params = factory.create_simulation_parameters(
            start=start, end=end)

        with self.assertRaises(IncompatibleHistoryFrequency):
            algo = TradingAlgorithm(
                script=algo_text,
                data_frequency='daily',
                sim_params=sim_params
            )
            source = RandomWalkSource(start=start, end=end)
            algo.run(source)
开发者ID:Joshua2014,项目名称:zipline,代码行数:27,代码来源:test_history.py

示例3: test_history_passed_to_talib

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_history_passed_to_talib(self):
        """
        Had an issue where MagicMock was causing errors during validation
        with talib.

        We don't officially support a talib integration, yet.
        But using talib directly should work.
        """
        algo_text = """
import talib
import numpy as np

from zipline.api import history, add_history, record

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

def handle_data(context, data):
    prices = history(2, '1d', 'price')

    ma_result = talib.MA(np.asarray(prices[0]), timeperiod=2)
    record(ma=ma_result[-1])
""".strip()

        #      April 2007
        # Su Mo Tu We Th Fr Sa
        #  1  2  3  4  5  6  7
        #  8  9 10 11 12 13 14
        # 15 16 17 18 19 20 21
        # 22 23 24 25 26 27 28
        # 29 30

        # Eddie: this was set to 04-10 but I don't see how that makes
        # sense as it does not generate enough data to get at -2 index
        # below.
        start = pd.Timestamp("2007-04-05", tz="UTC")
        end = pd.Timestamp("2007-04-10", tz="UTC")

        sim_params = SimulationParameters(
            period_start=start,
            period_end=end,
            capital_base=float("1.0e5"),
            data_frequency="minute",
            emission_rate="daily",
        )

        test_algo = TradingAlgorithm(
            script=algo_text, data_frequency="minute", sim_params=sim_params, env=TestHistoryAlgo.env
        )

        source = RandomWalkSource(start=start, end=end)
        output = test_algo.run(source)
        # At this point, just ensure that there is no crash.
        self.assertIsNotNone(output)

        recorded_ma = output.ix[-2, "ma"]

        self.assertFalse(pd.isnull(recorded_ma))
        # Depends on seed
        np.testing.assert_almost_equal(recorded_ma, 159.76304468946876)
开发者ID:rongyuhuang,项目名称:zipline,代码行数:62,代码来源:test_history.py

示例4: test_history_grow_length_intra_bar

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_history_grow_length_intra_bar(self, incr):
        """
        Tests growing the length of a digest panel with different date_buf
        deltas in a single bar.
        """
        algo_text = dedent(
            """\
            from zipline.api import history


            def initialize(context):
                context.bar_count = 1


            def handle_data(context, data):
                prices = history(context.bar_count, '1d', 'price')
                context.test_case.assertEqual(len(prices), context.bar_count)
                context.bar_count += {incr}
                prices = history(context.bar_count, '1d', 'price')
                context.test_case.assertEqual(len(prices), context.bar_count)
            """
        ).format(incr=incr)
        start = pd.Timestamp('2007-04-05', tz='UTC')
        end = pd.Timestamp('2007-04-10', tz='UTC')

        sim_params = SimulationParameters(
            period_start=start,
            period_end=end,
            capital_base=float("1.0e5"),
            data_frequency='minute',
            emission_rate='daily',
            env=self.env,
        )

        test_algo = TradingAlgorithm(
            script=algo_text,
            data_frequency='minute',
            sim_params=sim_params,
            env=self.env,
        )
        test_algo.test_case = self

        source = RandomWalkSource(start=start, end=end)

        self.assertIsNone(test_algo.history_container)
        test_algo.run(source)
开发者ID:AlexanderAA,项目名称:zipline,代码行数:48,代码来源:test_history.py

示例5: get_results

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def get_results(self, algo_code):
        algo = TradingAlgorithm(
            script=algo_code,
            env=self.env,
            sim_params=self.sim_params
        )

        return algo.run(self.data_portal)
开发者ID:ABDieng,项目名称:zipline,代码行数:10,代码来源:test_commissions.py

示例6: run_algo

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def run_algo(self, code, sim_params=None, data_frequency="daily"):
        if sim_params is None:
            sim_params = self.sim_params

        test_algo = TradingAlgorithm(script=code, sim_params=sim_params, env=self.env, data_frequency=data_frequency)

        results = test_algo.run(FetcherDataPortal(self.env))

        return results
开发者ID:rsr2425,项目名称:zipline,代码行数:11,代码来源:test_fetcher.py

示例7: test_basic_history_positional_args

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_basic_history_positional_args(self):
        """
        Ensure that positional args work.
        """
        algo_text = """
import copy
from zipline.api import history, add_history

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

def handle_data(context, data):

    prices = history(2, '1d', 'price')
    context.last_prices = copy.deepcopy(prices)
""".strip()

        #      March 2006
        # Su Mo Tu We Th Fr Sa
        #          1  2  3  4
        #  5  6  7  8  9 10 11
        # 12 13 14 15 16 17 18
        # 19 20 21 22 23 24 25
        # 26 27 28 29 30 31

        start = pd.Timestamp('2006-03-20', tz='UTC')
        end = pd.Timestamp('2006-03-21', tz='UTC')

        sim_params = factory.create_simulation_parameters(
            start=start, end=end)

        test_algo = TradingAlgorithm(
            script=algo_text,
            data_frequency='minute',
            sim_params=sim_params
        )

        source = RandomWalkSource(start=start,
                                  end=end)
        output = test_algo.run(source)
        self.assertIsNotNone(output)

        last_prices = test_algo.last_prices[0]
        oldest_dt = pd.Timestamp(
            '2006-03-20 4:00 PM', tz='US/Eastern').tz_convert('UTC')
        newest_dt = pd.Timestamp(
            '2006-03-21 4:00 PM', tz='US/Eastern').tz_convert('UTC')

        self.assertEquals(oldest_dt, last_prices.index[0])
        self.assertEquals(newest_dt, last_prices.index[-1])

        self.assertEquals(139.36946942498648, last_prices[oldest_dt])
        self.assertEquals(180.15661995395106, last_prices[newest_dt])
开发者ID:akitty,项目名称:zipline,代码行数:55,代码来源:test_history.py

示例8: test_basic_history_one_day

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_basic_history_one_day(self):
        algo_text = """
from zipline.api import history, add_history

def initialize(context):
    add_history(bar_count=1, frequency='1d', field='price')

def handle_data(context, data):
    prices = history(bar_count=1, frequency='1d', field='price')
    context.last_prices = prices
""".strip()

        #      March 2006
        # Su Mo Tu We Th Fr Sa
        #          1  2  3  4
        #  5  6  7  8  9 10 11
        # 12 13 14 15 16 17 18
        # 19 20 21 22 23 24 25
        # 26 27 28 29 30 31

        start = pd.Timestamp('2006-03-20', tz='UTC')
        end = pd.Timestamp('2006-03-21', tz='UTC')

        sim_params = factory.create_simulation_parameters(
            start=start, end=end)

        test_algo = TradingAlgorithm(
            script=algo_text,
            data_frequency='minute',
            sim_params=sim_params,
            env=TestHistoryAlgo.env,
        )

        source = RandomWalkSource(start=start,
                                  end=end)
        output = test_algo.run(source)

        self.assertIsNotNone(output)

        last_prices = test_algo.last_prices[0]
        # oldest and newest should be the same if there is only 1 bar
        oldest_dt = pd.Timestamp(
            '2006-03-21 4:00 PM', tz='US/Eastern').tz_convert('UTC')
        newest_dt = pd.Timestamp(
            '2006-03-21 4:00 PM', tz='US/Eastern').tz_convert('UTC')

        self.assertEquals(oldest_dt, last_prices.index[0])
        self.assertEquals(newest_dt, last_prices.index[-1])

        # Random, depends on seed
        self.assertEquals(180.15661995395106, last_prices[oldest_dt])
        self.assertEquals(180.15661995395106, last_prices[newest_dt])
开发者ID:AlexanderAA,项目名称:zipline,代码行数:54,代码来源:test_history.py

示例9: test_current_contract_in_algo

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_current_contract_in_algo(self):
        code = dedent("""
from zipline.api import (
    record,
    continuous_future,
    schedule_function,
    get_datetime,
)

def initialize(algo):
    algo.primary_cl = continuous_future('FO', 0, 'calendar')
    algo.secondary_cl = continuous_future('FO', 1, 'calendar')
    schedule_function(record_current_contract)

def record_current_contract(algo, data):
    record(datetime=get_datetime())
    record(primary=data.current(algo.primary_cl, 'contract'))
    record(secondary=data.current(algo.secondary_cl, 'contract'))
""")
        algo = TradingAlgorithm(script=code,
                                sim_params=self.sim_params,
                                trading_calendar=self.trading_calendar,
                                env=self.env)
        results = algo.run(self.data_portal)
        result = results.iloc[0]

        self.assertEqual(result.primary.symbol,
                         'FOF16',
                         'Primary should be FOF16 on first session.')
        self.assertEqual(result.secondary.symbol,
                         'FOG16',
                         'Secondary should be FOG16 on first session.')

        result = results.iloc[1]
        # Second day, primary should switch to FOG
        self.assertEqual(result.primary.symbol,
                         'FOG16',
                         'Primary should be FOG16 on second session, auto '
                         'close is at beginning of the session.')
        self.assertEqual(result.secondary.symbol,
                         'FOH16',
                         'Secondary should be FOH16 on second session, auto '
                         'close is at beginning of the session.')

        result = results.iloc[2]
        # Second day, primary should switch to FOG
        self.assertEqual(result.primary.symbol,
                         'FOG16',
                         'Primary should remain as FOG16 on third session.')
        self.assertEqual(result.secondary.symbol,
                         'FOH16',
                         'Secondary should remain as FOH16 on third session.')
开发者ID:kongscn,项目名称:zipline,代码行数:54,代码来源:test_continuous_futures.py

示例10: test_history_container_constructed_at_runtime

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_history_container_constructed_at_runtime(self, data_freq):
        algo_text = dedent(
            """\
            from zipline.api import history
            def handle_data(context, data):
                context.prices = history(2, '1d', 'price')
            """
        )
        start = pd.Timestamp("2007-04-05", tz="UTC")
        end = pd.Timestamp("2007-04-10", tz="UTC")

        sim_params = SimulationParameters(
            period_start=start,
            period_end=end,
            capital_base=float("1.0e5"),
            data_frequency=data_freq,
            emission_rate=data_freq,
        )

        test_algo = TradingAlgorithm(
            script=algo_text, data_frequency=data_freq, sim_params=sim_params, env=TestHistoryAlgo.env
        )

        source = RandomWalkSource(start=start, end=end, freq=data_freq)

        self.assertIsNone(test_algo.history_container)
        test_algo.run(source)
        self.assertIsNotNone(test_algo.history_container, msg="HistoryContainer was not constructed at runtime")

        container = test_algo.history_container
        self.assertEqual(len(container.digest_panels), 1, msg="The HistoryContainer created too many digest panels")

        freq, digest = list(container.digest_panels.items())[0]
        self.assertEqual(freq.unit_str, "d")

        self.assertEqual(
            digest.window_length, 1, msg="The digest panel is not large enough to service the given" " HistorySpec"
        )
开发者ID:rongyuhuang,项目名称:zipline,代码行数:40,代码来源:test_history.py

示例11: test_history_passed_to_func

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_history_passed_to_func(self):
        """
        Had an issue where MagicMock was causing errors during validation
        with rolling mean.
        """
        algo_text = """
from zipline.api import history, add_history
import pandas as pd

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

def handle_data(context, data):
    prices = history(2, '1d', 'price')

    pd.rolling_mean(prices, 2)
""".strip()

        #      April 2007
        # Su Mo Tu We Th Fr Sa
        #  1  2  3  4  5  6  7
        #  8  9 10 11 12 13 14
        # 15 16 17 18 19 20 21
        # 22 23 24 25 26 27 28
        # 29 30

        start = pd.Timestamp('2007-04-10', tz='UTC')
        end = pd.Timestamp('2007-04-10', tz='UTC')

        sim_params = SimulationParameters(
            period_start=start,
            period_end=end,
            capital_base=float("1.0e5"),
            data_frequency='minute',
            emission_rate='minute'
        )

        test_algo = TradingAlgorithm(
            script=algo_text,
            data_frequency='minute',
            sim_params=sim_params,
            env=TestHistoryAlgo.env,
        )

        source = RandomWalkSource(start=start,
                                  end=end)
        output = test_algo.run(source)

        # At this point, just ensure that there is no crash.
        self.assertIsNotNone(output)
开发者ID:AlexanderAA,项目名称:zipline,代码行数:52,代码来源:test_history.py

示例12: test_history_daily

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_history_daily(self):
        bar_count = 3
        algo_text = """
from zipline.api import history, add_history

def initialize(context):
    add_history(bar_count={bar_count}, frequency='1d', field='price')
    context.history_trace = []

def handle_data(context, data):
    prices = history(bar_count={bar_count}, frequency='1d', field='price')
    context.history_trace.append(prices)
""".format(bar_count=bar_count).strip()

        #      March 2006
        # Su Mo Tu We Th Fr Sa
        #          1  2  3  4
        #  5  6  7  8  9 10 11
        # 12 13 14 15 16 17 18
        # 19 20 21 22 23 24 25
        # 26 27 28 29 30 31

        start = pd.Timestamp('2006-03-20', tz='UTC')
        end = pd.Timestamp('2006-03-30', tz='UTC')

        sim_params = factory.create_simulation_parameters(
            start=start, end=end, data_frequency='daily', env=self.env,
        )

        _, df = factory.create_test_df_source(sim_params, self.env)
        df = df.astype(np.float64)
        source = DataFrameSource(df)

        test_algo = TradingAlgorithm(
            script=algo_text,
            data_frequency='daily',
            sim_params=sim_params,
            env=TestHistoryAlgo.env,
        )

        output = test_algo.run(source)
        self.assertIsNotNone(output)

        df.columns = self.env.asset_finder.retrieve_all(df.columns)

        for i, received in enumerate(test_algo.history_trace[bar_count - 1:]):
            expected = df.iloc[i:i + bar_count]
            assert_frame_equal(expected, received)
开发者ID:AlexanderAA,项目名称:zipline,代码行数:50,代码来源:test_history.py

示例13: test_history_with_open

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_history_with_open(self):
        algo_text = """
from zipline.api import history, add_history, record

def initialize(context):
    add_history(3, '1d', 'open_price')

def handle_data(context, data):
    opens = history(3, '1d', 'open_price')

    record(current_open=opens[0].ix[-1])
""".strip()

        #      April 2007
        # Su Mo Tu We Th Fr Sa
        #  1  2  3  4  5  6  7
        #  8  9 10 11 12 13 14
        # 15 16 17 18 19 20 21
        # 22 23 24 25 26 27 28
        # 29 30

        start = pd.Timestamp('2007-04-10', tz='UTC')
        end = pd.Timestamp('2007-04-10', tz='UTC')

        sim_params = SimulationParameters(
            period_start=start,
            period_end=end,
            capital_base=float("1.0e5"),
            data_frequency='minute',
            emission_rate='minute'
        )

        test_algo = TradingAlgorithm(
            script=algo_text,
            data_frequency='minute',
            sim_params=sim_params,
            env=TestHistoryAlgo.env,
        )

        source = RandomWalkSource(start=start,
                                  end=end)
        output = test_algo.run(source)

        np.testing.assert_equal(output.ix[0, 'current_open'],
                                99.991436939669939)
开发者ID:AlexanderAA,项目名称:zipline,代码行数:47,代码来源:test_history.py

示例14: test_basic_history

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
    def test_basic_history(self):
        algo_text = """
from zipline.api import history, add_history

def initialize(context):
    add_history(bar_count=2, frequency='1d', field='price')

def handle_data(context, data):
    prices = history(bar_count=2, frequency='1d', field='price')
    prices['prices_times_two'] = prices[1] * 2
    context.last_prices = prices
""".strip()

        #      March 2006
        # Su Mo Tu We Th Fr Sa
        #          1  2  3  4
        #  5  6  7  8  9 10 11
        # 12 13 14 15 16 17 18
        # 19 20 21 22 23 24 25
        # 26 27 28 29 30 31
        start = pd.Timestamp("2006-03-20", tz="UTC")
        end = pd.Timestamp("2006-03-21", tz="UTC")

        sim_params = factory.create_simulation_parameters(start=start, end=end)

        test_algo = TradingAlgorithm(
            script=algo_text, data_frequency="minute", sim_params=sim_params, env=TestHistoryAlgo.env
        )

        source = RandomWalkSource(start=start, end=end)
        output = test_algo.run(source)
        self.assertIsNotNone(output)

        last_prices = test_algo.last_prices[0]
        oldest_dt = pd.Timestamp("2006-03-20 4:00 PM", tz="US/Eastern").tz_convert("UTC")
        newest_dt = pd.Timestamp("2006-03-21 4:00 PM", tz="US/Eastern").tz_convert("UTC")

        self.assertEquals(oldest_dt, last_prices.index[0])
        self.assertEquals(newest_dt, last_prices.index[-1])

        # Random, depends on seed
        self.assertEquals(139.36946942498648, last_prices[oldest_dt])
        self.assertEquals(180.15661995395106, last_prices[newest_dt])
开发者ID:rongyuhuang,项目名称:zipline,代码行数:45,代码来源:test_history.py

示例15: markowitz

# 需要导入模块: from zipline import TradingAlgorithm [as 别名]
# 或者: from zipline.TradingAlgorithm import run [as 别名]
def markowitz(stocks, cash):
    warnings.filterwarnings("once")
    
    solvers.options['show_progress'] = False

    end = pd.Timestamp.utcnow()
    start = end - 50 * pd.tseries.offsets.BDay()
    data = load_bars_from_yahoo(stocks=stocks,
                            start=start, end=end)

    # Instantinate algorithm        
    algo = TradingAlgorithm(initialize=initialize, 
                       handle_data=handle_data, cash=cash)
    # Run algorithm
    results = algo.run(data)
    
    # portfolio value plot
    raw_plot = results.portfolio_value.plot()
    raw_fig = raw_plot.get_figure()
    returns_plot = mpld3.fig_to_html(raw_fig)
    raw_fig.clf()
    
    #stock price plot
    raw_price_data = data.loc[:, :, 'price'].pct_change(1).fillna(0).applymap(lambda x: x + 1).cumprod().applymap(lambda x: x * 100)
    raw_price_plot = raw_price_data.plot(figsize=(8,5))
    raw_price_fig = raw_price_plot.get_figure()
    price_plot = mpld3.fig_to_html(raw_price_fig)
    raw_price_fig.clf()
    
    #final returns
    equalweight_returns = sum(map(list, raw_price_data.tail(1).values)[0]) / 4 - 100
    equalweight_returns = '{0:.2f}%'.format(float(equalweight_returns))
    optimal_returns = (results.portfolio_value.tail(1).iloc[0] - 100000) / 1000
    optimal_returns = '{0:.2f}%'.format(float(optimal_returns))
    
    #efficient frontier plot
    frontier_plot_data = open("plot.png", "rb").read()
    # serialize to HTTP response
    frontier_plot = HttpResponse(frontier_plot_data, content_type="image/png")
    
    return(results, returns_plot, price_plot, frontier_plot, equalweight_returns, optimal_returns)
开发者ID:jerryzhang222,项目名称:MarkowitzOptimizer,代码行数:43,代码来源:markowitz.py


注:本文中的zipline.TradingAlgorithm.run方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。