def _get_test_case_set_up():
    timer = SettableTimer()
    tickers = [QuandlTicker("MSFT", "WIKI"), QuandlTicker("AAPL", "WIKI")]
    price_data_provider_mock = _create_price_provider_mock(tickers)
    data_handler = DailyDataHandler(price_data_provider_mock, timer)

    return timer, tickers, data_handler
Example #2
0
def main():
    initial_risk = 0.03

    start_date = str_to_date('2016-01-01')
    end_date = str_to_date('2017-12-31')

    # ----- build trading session ----- #
    session_builder = container.resolve(BacktestTradingSessionBuilder)  # type: BacktestTradingSessionBuilder
    session_builder.set_backtest_name('Moving Average Alpha Model Backtest')
    session_builder.set_position_sizer(InitialRiskPositionSizer, initial_risk=initial_risk)
    session_builder.set_contract_ticker_mapper(DummyQuandlContractTickerMapper())
    session_builder.set_commission_model(IBCommissionModel)
    session_builder.set_frequency(Frequency.DAILY)
    ts = session_builder.build(start_date, end_date)

    # ----- build models ----- #
    model = MovingAverageAlphaModel(fast_time_period=5, slow_time_period=20, risk_estimation_factor=1.25,
                                    data_handler=ts.data_handler)
    model_tickers = [QuandlTicker('AAPL', 'WIKI'), QuandlTicker('AMZN', 'WIKI')]
    model_tickers_dict = {model: model_tickers}

    # ----- preload price data ----- #
    ts.use_data_preloading(model_tickers)

    # ----- start trading ----- #
    AlphaModelStrategy(ts, model_tickers_dict, use_stop_losses=True)
    ts.start_trading()

    # ----- use results ----- #
    backtest_tms = ts.portfolio.portfolio_eod_series().to_log_returns()
    print("mean daily log return: {}".format(backtest_tms.mean()))
    print("std of daily log returns: {}".format(backtest_tms.std()))
Example #3
0
    def setUp(self):
        trade_columns = pd.Index([TradeField.Ticker, TradeField.StartDate, TradeField.EndDate, TradeField.Return])
        apple_ticker = QuandlTicker("AAPL", "WIKI")
        ibm_ticker = QuandlTicker("IBM", "WIKI")

        self.trades = QFDataFrame(columns=trade_columns, data=[
            [apple_ticker, str_to_date("2015-01-03"), str_to_date("2015-01-10"), 0.1],
            [apple_ticker, str_to_date("2015-02-01"), str_to_date("2015-02-10"), -0.05],
            [apple_ticker, str_to_date("2015-03-01"), str_to_date("2015-03-30"), -0.05],
            [apple_ticker, str_to_date("2015-04-01"), str_to_date("2015-04-30"), 0.1],
            [ibm_ticker, str_to_date("2015-05-01"), str_to_date("2015-05-08"), -0.05],
            [ibm_ticker, str_to_date("2015-06-01"), str_to_date("2015-06-23"), 0.1],
            [ibm_ticker, str_to_date("2015-07-01"), str_to_date("2015-07-30"), -0.05]
        ])
def get_data():
    data_provider = container.resolve(QuandlDataProvider)  # type: QuandlDataProvider
    start_date = str_to_date('2017-01-01')
    end_date = str_to_date('2017-12-31')
    live_date = str_to_date('2016-01-01')

    dummy_strategy_tms = data_provider.get_price(
        tickers=QuandlTicker('AAPL', 'WIKI'), fields=PriceField.Close, start_date=start_date, end_date=end_date)
    dummy_benchmark_tms = data_provider.get_price(
        tickers=QuandlTicker('IBM', 'WIKI'), fields=PriceField.Close, start_date=start_date, end_date=end_date)

    dummy_strategy_tms.name = "Live Trading"
    dummy_benchmark_tms.name = "In-Sample Results"
    return dummy_strategy_tms, dummy_benchmark_tms, live_date
Example #5
0
def main():
    data_provider = container.resolve(GeneralPriceProvider)
    benchmark_tms = data_provider.get_price(QuandlTicker('AAPL', 'WIKI'),
                                            PriceField.Close, start_date,
                                            end_date)
    strategy_tms = data_provider.get_price(QuandlTicker('MSFT', 'WIKI'),
                                           PriceField.Close, start_date,
                                           end_date)

    regression_chart = RegressionChart(benchmark_tms=benchmark_tms,
                                       strategy_tms=strategy_tms)
    regression_chart.plot()

    plt.show(block=True)
Example #6
0
def main():
    data_provider = container.resolve(GeneralPriceProvider)
    series = data_provider.get_price(QuandlTicker('AAPL', 'WIKI'),
                                     PriceField.Close,
                                     start_date=start_date,
                                     end_date=end_date)
    series = series.to_prices(1)

    vol_manager = VolatilityManager(series)
    managed_series, weights_series = vol_manager.get_managed_series(
        vol_level=0.2,
        window_size=20,
        lag=1,
        min_leverage=min_lev,
        max_leverage=max_lev)
    managed_series = managed_series.to_prices(1)

    line_chart = LineChart()
    series_element = DataElementDecorator(series)
    managed_element = DataElementDecorator(managed_series)

    line_chart.add_decorator(series_element)
    line_chart.add_decorator(managed_element)

    legend = LegendDecorator(legend_placement=Location.BEST, key='legend')
    legend.add_entry(series_element, 'Original')
    legend.add_entry(managed_element, 'Vol_managed')
    line_chart.add_decorator(legend)
    line_chart.plot()
    plt.show(block=True)
Example #7
0
def main():
    plt.style.use(['seaborn-poster', 'macrostyle'])

    data = container.resolve(GeneralPriceProvider)

    start_date = str_to_date('2016-01-01')
    end_date = str_to_date('2016-11-20')

    spx_tms = data.get_price(QuandlTicker('AAPL', 'WIKI'), PriceField.Close,
                             start_date, end_date)
    spx_tms = spx_tms.pct_change()

    recession = rand_recession(spx_tms)
    names = [
        "Quarter on quarter annualised,  (SA, Chained 2009, %)",
        "Year on year  (SA, Chained 2009, %)", None
    ]

    chart = create_bar_chart([spx_tms],
                             names,
                             "US Real Gross Domestic Product Growth (%)",
                             [spx_tms],
                             recession,
                             quarterly=False,
                             start_x=datetime.datetime.strptime("2015", "%Y"))
    chart.plot()
    plt.show(block=True)
Example #8
0
    def _get_history_from_table(
            self, tickers_of_single_db: Sequence[QuandlTicker],
            fields: Sequence[str], start_date: datetime,
            end_date: datetime) -> Dict[QuandlTicker, pd.DataFrame]:
        # Possibly this method is not generic enough, but I couldn't find another table db to test it.
        field_options = {}
        if fields is not None:
            columns = ['ticker', 'date'] + list(fields)
            field_options['qopts'] = {'columns': columns}

        db_name = tickers_of_single_db[0].database_name
        result_dict = {}

        tickers_str = [t.as_string() for t in tickers_of_single_db]
        df = quandl.get_table(db_name,
                              ticker=tickers_str,
                              paginate=True,
                              **field_options)
        # at this point we have a large DataFrame with rows corresponding to different tickers
        # we group it by ticker
        ticker_grouping = df.groupby('ticker')
        for ticker_str, ticker_df in ticker_grouping:
            ticker = QuandlTicker(ticker=ticker_str,
                                  database_name=db_name,
                                  database_type=QuandlDBType.Table)
            dates_fields_values_df = self._format_single_ticker_table(
                ticker_df, start_date, end_date)
            result_dict[ticker] = dates_fields_values_df

        return result_dict
Example #9
0
def main():
    data_provider = container.resolve(QuandlDataProvider)  # type: QuandlDataProvider
    start_date = str_to_date('2016-01-01')
    end_date = str_to_date('2017-11-02')

    print('Single ticker:')
    ticker = QuandlTicker('IBM', 'WIKI')
    data = data_provider.get_history(tickers=ticker, start_date=start_date, end_date=end_date)
    print(data)

    print('Single ticker: lower case')
    ticker = QuandlTicker('ibm', 'wiki')
    data = data_provider.get_history(tickers=ticker, start_date=start_date, end_date=end_date)
    print(data)

    print('Single ticker:')
    ticker = QuandlTicker('IBM', 'WIKI/PRICES', QuandlDBType.Table)
    data = data_provider.get_history(tickers=ticker, start_date=start_date, end_date=end_date)
    print(data)

    print('Single ticker, Price')
    ticker = QuandlTicker('IBM', 'WIKI/PRICES', QuandlDBType.Table)
    data = data_provider.get_price(tickers=ticker, fields=PriceField.Close, start_date=start_date, end_date=end_date)
    print(data)

    print('Continues Futures - CHRIS')
    ticker = QuandlTicker('ASX_TN2', 'CHRIS')
    data = data_provider.get_history(tickers=ticker, start_date=start_date, end_date=end_date)
    print(data)

    print('Futures - ICE')
    ticker = QuandlTicker('OZ2019', 'ICE')
    data = data_provider.get_history(tickers=ticker, start_date=start_date, end_date=end_date)
    print(data)

    print('Futures - CME')
    ticker = QuandlTicker('EMF2018', 'CME')
    data = data_provider.get_history(tickers=ticker, start_date=start_date, end_date=end_date)
    print(data)

    print('Futures - EUREX')
    ticker = QuandlTicker('FCXEZ2018', 'EUREX')
    data = data_provider.get_history(tickers=ticker, start_date=start_date, end_date=end_date)
    print(data)

    print('Continues Futures - CHRIS')
    ticker = QuandlTicker('ASX_TN2', 'CHRIS')
    data = data_provider.get_price(tickers=ticker, fields=PriceField.Close, start_date=start_date, end_date=end_date)
    print(data)
Example #10
0
def main():
    data_provider = container.resolve(GeneralPriceProvider)
    prices_tms = data_provider.get_price(QuandlTicker('AAPL', 'WIKI'),
                                         PriceField.Close, start_date,
                                         end_date)

    underwater_chart = UnderwaterChart(prices_tms)
    underwater_chart.plot()

    plt.show(block=True)
Example #11
0
def main():
    data_provider = container.resolve(GeneralPriceProvider)
    spy_tms = data_provider.get_price(QuandlTicker('AAPL', 'WIKI'),
                                      PriceField.Close, start_date, end_date)

    cone_chart = ConeChart(data=spy_tms,
                           nr_of_data_points=200,
                           is_end_date=live_start_date)
    cone_chart.plot()

    plt.show(block=True)
Example #12
0
def get_data():
    data_provider = container.resolve(
        QuandlDataProvider)  # type: QuandlDataProvider
    start_date = str_to_date('2010-01-01')
    end_date = str_to_date('2017-12-31')
    live_date = str_to_date('2015-01-01')

    strategy = data_provider.get_price(tickers=QuandlTicker('AAPL', 'WIKI'),
                                       fields=PriceField.Close,
                                       start_date=start_date,
                                       end_date=end_date)
    benchmark = data_provider.get_price(tickers=QuandlTicker('IBM', 'WIKI'),
                                        fields=PriceField.Close,
                                        start_date=start_date,
                                        end_date=end_date)

    strategy.name = "Strategy"
    benchmark.name = "Benchmark"

    return strategy, benchmark, live_date
def main():
    model_type = MovingAverageAlphaModel

    initial_risk = 0.03
    commission_model = IBCommissionModel()

    start_date = str_to_date('2016-01-01')
    end_date = str_to_date('2017-12-31')

    # ----- build trading session ----- #
    session_builder = container.resolve(
        BacktestTradingSessionBuilder)  # type: BacktestTradingSessionBuilder
    session_builder.set_backtest_name('Moving Average Alpha Model Backtest')
    session_builder.set_position_sizer(InitialRiskPositionSizer, initial_risk)
    session_builder.set_contract_ticker_mapper(
        DummyQuandlContractTickerMapper())
    session_builder.set_commission_model(commission_model)
    session_builder.set_monitor_type(BacktestMonitor)
    ts = session_builder.build(start_date, end_date)

    # ----- build models ----- #
    model_factory = AlphaModelFactory(ts.data_handler)
    model = model_factory.make_parametrized_model(model_type)
    model_tickers = [
        QuandlTicker('AAPL', 'WIKI'),
        QuandlTicker('AMZN', 'WIKI')
    ]
    model_tickers_dict = {model: model_tickers}

    # ----- preload price data ----- #
    all_tickers_used = get_all_tickers_used(model_tickers_dict)
    ts.use_data_preloading(all_tickers_used)

    # ----- start trading ----- #
    AlphaModelStrategy(ts, model_tickers_dict, use_stop_losses=True)
    ts.start_trading()

    # ----- use results ----- #
    backtest_tms = ts.portfolio.get_portfolio_timeseries().to_log_returns()
    print("mean daily log return: {}".format(backtest_tms.mean()))
    print("std of daily log returns: {}".format(backtest_tms.std()))
Example #14
0
def main():
    data_provider = container.resolve(GeneralPriceProvider)
    prices_tms = data_provider.get_price(QuandlTicker('AAPL', 'WIKI'), PriceField.Close, start_date)

    event_dates_list = [datetime(2000, 1, 1), datetime(2003, 1, 1), datetime(2006, 1, 1), datetime(2009, 1, 1)]

    event_chart = create_event_comparison_chart(
        prices_tms, event_dates_list, 'Beginning of the year',
        samples_before=100, samples_after=200, rebase_method=RebaseMethod.divide)
    event_chart.plot()

    plt.show(block=True)
Example #15
0
def main():
    tms = data_provider.get_price(QuandlTicker('AAPL', 'WIKI'), PriceField.Close, start_date, end_date)
    tms2 = data_provider.get_price(QuandlTicker('MSFT', 'WIKI'), PriceField.Close, start_date, end_date)

    line_chart = LineChart()
    data_element = DataElementDecorator(tms)
    line_chart.add_decorator(data_element)

    data_element2 = DataElementDecorator(tms2, use_secondary_axes=True)
    line_chart.add_decorator(data_element2)

    axes_decorator = AxesLabelDecorator(x_label='dates', y_label='primary', secondary_y_label='secondary')
    line_chart.add_decorator(axes_decorator)

    legend = LegendDecorator(legend_placement=Location.BEST)
    legend.add_entry(data_element, 'AAPL')
    legend.add_entry(data_element2, 'MSFT')
    line_chart.add_decorator(legend)

    line_chart.plot()
    plt.show(block=True)
def _calculate_single_values(data_provider):
    ticker = QuandlTicker('AAPL', 'WIKI')
    fields = [
        PriceField.Open, PriceField.High, PriceField.Low, PriceField.Close
    ]
    prices_df = data_provider.get_price(ticker, fields, start_date, end_date)

    di_vol = DriftIndependentVolatility.get_volatility(prices_df,
                                                       Frequency.DAILY)
    print("drift_independent_vol = {}".format(di_vol))

    close_price_tms = prices_df[PriceField.Close]
    simple_vol = get_volatility(close_price_tms, Frequency.DAILY)
    print("simple_vol = {}".format(simple_vol))
    def setUp(self):
        self.timer = SettableTimer()
        self.tickers = [
            QuandlTicker("MSFT", "WIKI"),
            QuandlTicker("AAPL", "WIKI")
        ]
        price_data_provider_mock = self._create_price_provider_mock(
            self.tickers)
        self.data_handler = DailyDataHandler(price_data_provider_mock,
                                             self.timer)

        MarketOpenEvent.set_trigger_time({
            "hour": 13,
            "minute": 30,
            "second": 0,
            "microsecond": 0
        })
        MarketCloseEvent.set_trigger_time({
            "hour": 20,
            "minute": 0,
            "second": 0,
            "microsecond": 0
        })
Example #18
0
def main():
    data_provider = container.resolve(GeneralPriceProvider)
    prices_tms = data_provider.get_price(QuandlTicker('AAPL', 'WIKI'),
                                         PriceField.Close, start_date,
                                         end_date)

    chart = create_return_quantiles(prices_tms, live_start_date)
    chart.plot()

    chart = create_return_quantiles(prices_tms)
    chart.plot()

    chart = create_return_quantiles(prices_tms, end_date)
    chart.plot()

    plt.show(block=True)
def main():
    data_provider = container.resolve(GeneralPriceProvider)
    spy_tms = data_provider.get_price(QuandlTicker('AAPL', 'WIKI'),
                                      PriceField.Close, start_date, end_date)

    first_part = spy_tms.loc[spy_tms.index < live_start_date]
    first_part.name = 'first part of series'

    last_part = spy_tms.loc[spy_tms.index > live_start_date]
    last_part.name = 'last part of series'

    returns_similarity_chart = create_returns_similarity(
        first_part,
        last_part,
        mean_normalization=False,
        std_normalization=False,
    )
    returns_similarity_chart.plot()
    plt.show(block=True)
Example #20
0
def main():
    data_provider = container.resolve(GeneralPriceProvider)
    prices_tms = data_provider.get_price(QuandlTicker('AAPL', 'WIKI'),
                                         PriceField.Close, start_date,
                                         end_date)

    line_chart = LineChart()
    data_element = DataElementDecorator(prices_tms)
    line_chart.add_decorator(data_element)
    legend = LegendDecorator(legend_placement=Location.BEST, key='legend')
    legend.add_entry(data_element, 'SPY')
    line_chart.add_decorator(legend)

    cone_decorator = ConeDecorator(live_start_date=live_start_date,
                                   series=prices_tms,
                                   key='cone')
    line_chart.add_decorator(cone_decorator)
    line_chart.plot()

    plt.show(block=True)
Example #21
0
def main():
    data_provider = container.resolve(GeneralPriceProvider)
    prices_tms = data_provider.get_price(QuandlTicker('AAPL', 'WIKI'),
                                         PriceField.Close, start_date,
                                         end_date)

    line_chart = LineChart()
    data_element = DataElementDecorator(prices_tms)
    line_chart.add_decorator(data_element)

    sample_date = str_to_date('2008-06-01')

    # if you want to test FigureCoordinates, you may want to pass additional argument: clip_on=False
    text_decorator = TextDecorator("Sample text",
                                   x=DataCoordinate(sample_date),
                                   y=AxesCoordinate(0.9))
    line_chart.add_decorator(text_decorator)

    line_chart.plot()
    plt.show(block=True)
def _calculate_timeseries(data_provider):
    print('\n\n\t--- Drift Independent Volatility Test in progress ---')

    def simple_vol(close_tms):
        return get_volatility(close_tms, Frequency.DAILY)

    def di_vol(ohlc_df):
        return DriftIndependentVolatility.get_volatility(
            ohlc_df, Frequency.DAILY)

    ticker = QuandlTicker('MSFT', 'WIKI')
    fields = [
        PriceField.Open, PriceField.High, PriceField.Low, PriceField.Close
    ]
    prices_df = data_provider.get_price(ticker, fields, start_date,
                                        end_date)  # type: PricesDataFrame

    window_len = 128

    close_price_tms = prices_df[PriceField.Close]  # type: PricesSeries
    simple_vols = close_price_tms.rolling_window(window_len, simple_vol)
    print('Simple Volatility - start value:', simple_vols[0])

    drift_independent_vols = prices_df.rolling_time_window(
        window_len, 1, di_vol)
    print('Drift Independent Volatility - start value:',
          drift_independent_vols[0])

    line_chart = LineChart()
    sv_data = DataElementDecorator(simple_vols)
    line_chart.add_decorator(sv_data)
    div_data = DataElementDecorator(drift_independent_vols)
    line_chart.add_decorator(div_data)
    line_chart.plot()
    print('\nPlot generated successfully.')
    plt.show(block=True)
Example #23
0
class TestQuandlTable(unittest.TestCase):
    START_DATE = str_to_date('2014-01-01')
    END_DATE = str_to_date('2015-02-02')
    SINGLE_FIELD = 'adj_close'
    MANY_FIELDS = ['adj_low', 'adj_volume', 'adj_close']
    db_name = 'WIKI/PRICES'
    type = QuandlDBType.Table

    INVALID_TICKER = QuandlTicker('INV1', db_name, type)

    SINGLE_TICKER = QuandlTicker('IBM', db_name, type)
    MANY_TICKERS = [
        QuandlTicker('IBM', db_name, type),
        QuandlTicker('MSFT', db_name, type),
        QuandlTicker('AAPL', db_name, type)
    ]
    NUM_OF_DATES = 273

    SINGLE_PRICE_FIELD = PriceField.Close
    MANY_PRICE_FIELDS = [PriceField.Close, PriceField.Open, PriceField.High]

    def setUp(self):
        self.quandl_provider = QuandlDataProvider(settings)

    # =========================== Test invalid ticker ==========================================================

    def test_price_single_invalid_ticker_single_field(self):
        # single ticker, single field; end_date by default now, frequency by default DAILY, currency by default None
        data = self.quandl_provider.get_price(tickers=self.INVALID_TICKER,
                                              fields=self.SINGLE_PRICE_FIELD,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE,
                                              frequency=Frequency.DAILY)

        self.assertIsInstance(data, PricesSeries)
        self.assertEqual(len(data), 0)
        self.assertEqual(data.name, self.INVALID_TICKER.as_string())

    def test_price_single_invalid_ticker_many_fields(self):
        # single ticker, single field; end_date by default now, frequency by default DAILY, currency by default None
        data = self.quandl_provider.get_price(tickers=self.INVALID_TICKER,
                                              fields=self.MANY_PRICE_FIELDS,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE,
                                              frequency=Frequency.DAILY)

        self.assertIsInstance(data, PricesDataFrame)
        self.assertEqual(data.shape, (0, len(self.MANY_PRICE_FIELDS)))
        self.assertEqual(list(data.columns), self.MANY_PRICE_FIELDS)

    # =========================== Test get_price method ==========================================================

    def test_price_single_ticker_single_field(self):
        # single ticker, single field; end_date by default now, frequency by default DAILY, currency by default None
        data = self.quandl_provider.get_price(tickers=self.SINGLE_TICKER,
                                              fields=self.SINGLE_PRICE_FIELD,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE,
                                              frequency=Frequency.DAILY)

        self.assertIsInstance(data, PricesSeries)
        self.assertEqual(len(data), self.NUM_OF_DATES)
        self.assertEqual(data.name, self.SINGLE_TICKER.as_string())

    def test_price_single_ticker_multiple_fields(self):
        # single ticker, many fields; can be the same as for single field???
        data = self.quandl_provider.get_price(tickers=self.SINGLE_TICKER,
                                              fields=self.MANY_PRICE_FIELDS,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE,
                                              frequency=Frequency.DAILY)

        self.assertEqual(type(data), PricesDataFrame)
        self.assertEqual(data.shape,
                         (self.NUM_OF_DATES, len(self.MANY_PRICE_FIELDS)))
        self.assertEqual(list(data.columns), self.MANY_PRICE_FIELDS)

    def test_price_single_ticker_all_available_fields(self):
        # single ticker, many fields; can be the same as for single field???
        data = self.quandl_provider.get_history(tickers=self.SINGLE_TICKER,
                                                fields=None,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertEqual(type(data), QFDataFrame)
        self.assertEqual(data.shape[0], self.NUM_OF_DATES)

        # assumption: when we request all available fields, there should be at least 4 of them: Open, High, Low, Close.
        # can be more (e.g. Volume)
        self.assertTrue(len(data.columns) >= 4)

    def test_price_multiple_tickers_single_field(self):
        data = self.quandl_provider.get_price(tickers=self.MANY_TICKERS,
                                              fields=self.SINGLE_PRICE_FIELD,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE,
                                              frequency=Frequency.DAILY)
        self.assertEqual(type(data), PricesDataFrame)
        self.assertEqual(data.shape,
                         (self.NUM_OF_DATES, len(self.MANY_TICKERS)))
        self.assertEqual(list(data.columns), self.MANY_TICKERS)

    def test_price_multiple_tickers_multiple_fields(self):
        # testing for single date (start_date and end_date are the same)
        data = self.quandl_provider.get_price(tickers=self.MANY_TICKERS,
                                              fields=self.MANY_PRICE_FIELDS,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE,
                                              frequency=Frequency.DAILY)

        self.assertEqual(type(data), QFDataArray)
        self.assertEqual(data.shape, (self.NUM_OF_DATES, len(
            self.MANY_TICKERS), len(self.MANY_PRICE_FIELDS)))
        self.assertIsInstance(data.dates.to_index(), pd.DatetimeIndex)
        self.assertEqual(list(data.tickers), self.MANY_TICKERS)
        self.assertEqual(list(data.fields), self.MANY_PRICE_FIELDS)

    # =========================== Test get_history method ==========================================================

    def test_historical_single_ticker_single_field(self):
        # single ticker, single field; end_date by default now, frequency by default DAILY, currency by default None
        data = self.quandl_provider.get_history(tickers=self.SINGLE_TICKER,
                                                fields=self.SINGLE_FIELD,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertIsInstance(data, QFSeries)
        self.assertEqual(len(data), self.NUM_OF_DATES)
        self.assertEqual(data.name, self.SINGLE_TICKER.as_string())

    def test_historical_single_ticker_multiple_fields(self):
        # single ticker, many fields; can be the same as for single field???
        data = self.quandl_provider.get_history(tickers=self.SINGLE_TICKER,
                                                fields=self.MANY_FIELDS,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertEqual(type(data), QFDataFrame)
        self.assertEqual(data.shape,
                         (self.NUM_OF_DATES, len(self.MANY_FIELDS)))
        self.assertEqual(list(data.columns), self.MANY_FIELDS)

    def test_historical_multiple_tickers_single_field(self):
        data = self.quandl_provider.get_history(tickers=self.MANY_TICKERS,
                                                fields=self.SINGLE_FIELD,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertEqual(type(data), QFDataFrame)
        self.assertEqual(data.shape,
                         (self.NUM_OF_DATES, len(self.MANY_TICKERS)))
        self.assertEqual(list(data.columns), self.MANY_TICKERS)

    def test_historical_multiple_tickers_multiple_fields_one_date(self):
        # testing for single date (start_date and end_date are the same)
        data = self.quandl_provider.get_history(tickers=self.MANY_TICKERS,
                                                fields=self.MANY_FIELDS,
                                                start_date=self.END_DATE,
                                                end_date=self.END_DATE)
        self.assertEqual(type(data), QFDataFrame)
        self.assertEqual(data.shape,
                         (len(self.MANY_TICKERS), len(self.MANY_FIELDS)))
        self.assertEqual(list(data.index), self.MANY_TICKERS)
        self.assertEqual(list(data.columns), self.MANY_FIELDS)

    def test_historical_multiple_tickers_multiple_fields_many_dates(self):
        # testing for single date (start_date and end_date are the same)
        data = self.quandl_provider.get_history(tickers=self.MANY_TICKERS,
                                                fields=self.MANY_FIELDS,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)
        self.assertEqual(type(data), QFDataArray)
        self.assertEqual(
            data.shape,
            (self.NUM_OF_DATES, len(self.MANY_TICKERS), len(self.MANY_FIELDS)))
        self.assertIsInstance(data.dates.to_index(), pd.DatetimeIndex)
        self.assertEqual(list(data.tickers), self.MANY_TICKERS)
        self.assertEqual(list(data.fields), self.MANY_FIELDS)

    def test_historical_single_ticker_all_fields_all_dates(self):
        # single ticker, many fields; can be the same as for single field???
        data = self.quandl_provider.get_history(tickers=self.SINGLE_TICKER)

        self.assertEqual(type(data), QFDataFrame)
        self.assertTrue(data.shape[0] > self.NUM_OF_DATES)
        self.assertTrue(data.shape[1] > len(self.MANY_FIELDS))
Example #24
0
class TestQuandlTimeseries(unittest.TestCase):
    START_DATE = str_to_date('2014-01-01')
    END_DATE = str_to_date('2015-02-02')

    SINGLE_TICKER = QuandlTicker('PKOBP', 'WSE')
    SINGLE_FIELD = 'Close'
    MANY_FIELDS = ['Close', 'High', 'Low']
    WSE_NUM_OF_DATES = 270
    WSE_OUTPUT_FIELDS = [
        'Open', 'High', 'Low', 'Close', '%Change', 'Volume', '# of Trades',
        'Turnover (1000)'
    ]

    INVALID_TICKER = QuandlTicker('Inv1', 'WIKI')
    INVALID_TICKERS = [
        QuandlTicker('Inv1', 'WSE'),
        QuandlTicker('PKOBP', 'WSE'),
        QuandlTicker('MSFT', 'WSE')
    ]

    MANY_TICKERS = [
        QuandlTicker('MSFT', 'WIKI'),
        QuandlTicker('AAPL', 'WIKI'),
        QuandlTicker('EA', 'WIKI'),
        QuandlTicker('IBM', 'WIKI')
    ]

    MIXED_DB_TICKERS = MANY_TICKERS + [
        QuandlTicker('IBM', 'WIKI/PRICES', QuandlDBType.Table),
        QuandlTicker('PKOBP', 'WSE')
    ]

    WIKI_NUM_OF_DATES = 273
    WIKI_OUTPUT_FIELDS = [
        'Open', 'High', 'Low', 'Close', 'Volume', 'Ex-Dividend', 'Split Ratio',
        'Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume'
    ]
    MANY_TICKERS_STR = [t.as_string() for t in MANY_TICKERS]

    SINGLE_PRICE_FIELD = PriceField.Close
    MANY_PRICE_FIELDS = [PriceField.Close, PriceField.Open, PriceField.High]

    def setUp(self):
        self.quandl_provider = QuandlDataProvider(settings)

    # =========================== Test invalid ticker ==========================================================

    def test_price_single_invalid_ticker_single_field(self):
        # single ticker, single field; end_date by default now, frequency by default DAILY, currency by default None
        data = self.quandl_provider.get_price(tickers=self.INVALID_TICKER,
                                              fields=self.SINGLE_PRICE_FIELD,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE)

        self.assertIsInstance(data, PricesSeries)
        self.assertEqual(len(data), 0)
        self.assertEqual(data.name, self.INVALID_TICKER.as_string())

    def test_historical_single_invalid_ticker_no_field(self):
        # single ticker, single field; end_date by default now, frequency by default DAILY, currency by default None
        data = self.quandl_provider.get_history(tickers=self.INVALID_TICKER,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertIsInstance(data, QFDataFrame)
        self.assertEqual(len(data), 0)

    def test_price_single_invalid_ticker_many_fields(self):
        # single ticker, single field; end_date by default now, frequency by default DAILY, currency by default None
        data = self.quandl_provider.get_price(tickers=self.INVALID_TICKER,
                                              fields=self.MANY_PRICE_FIELDS,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE)

        self.assertIsInstance(data, PricesDataFrame)
        self.assertEqual(data.shape, (0, len(self.MANY_PRICE_FIELDS)))
        self.assertEqual(list(data.columns), self.MANY_PRICE_FIELDS)

    def test_price_single_invalid_ticker_all_fields(self):
        # single ticker, single field; end_date by default now, frequency by default DAILY, currency by default None
        data = self.quandl_provider.get_history(tickers=self.INVALID_TICKER,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertIsInstance(data, QFDataFrame)
        self.assertEqual(data.shape, (0, 1))

    def test_price_many_invalid_tickers_many_fields(self):
        # single ticker, single field; end_date by default now, frequency by default DAILY, currency by default None
        data = self.quandl_provider.get_price(tickers=self.INVALID_TICKERS,
                                              fields=self.MANY_PRICE_FIELDS,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE)

        self.assertEqual(type(data), QFDataArray)
        self.assertEqual(data.shape,
                         (self.WSE_NUM_OF_DATES, len(self.INVALID_TICKERS),
                          len(self.MANY_PRICE_FIELDS)))
        self.assertIsInstance(data.dates.to_index(), pd.DatetimeIndex)
        self.assertEqual(list(data.tickers), self.INVALID_TICKERS)
        self.assertEqual(list(data.fields), self.MANY_PRICE_FIELDS)

    # =========================== Test get_price method ==========================================================

    def test_price_single_ticker_single_field(self):
        data = self.quandl_provider.get_price(tickers=self.SINGLE_TICKER,
                                              fields=self.SINGLE_PRICE_FIELD,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE)

        self.assertEqual(type(data), PricesSeries)
        self.assertEqual(len(data), self.WSE_NUM_OF_DATES)
        self.assertEqual(data.name, self.SINGLE_TICKER.as_string())

    def test_price_single_ticker_multiple_fields(self):
        data = self.quandl_provider.get_price(tickers=self.SINGLE_TICKER,
                                              fields=self.MANY_PRICE_FIELDS,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE)

        self.assertEqual(type(data), PricesDataFrame)
        self.assertEqual(data.shape,
                         (self.WSE_NUM_OF_DATES, len(self.MANY_PRICE_FIELDS)))
        self.assertEqual(list(data.columns), self.MANY_PRICE_FIELDS)

    def test_price_multiple_tickers_single_field(self):
        data = self.quandl_provider.get_price(tickers=self.MANY_TICKERS,
                                              fields=self.SINGLE_PRICE_FIELD,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE)

        self.assertEqual(PricesDataFrame, type(data))
        self.assertEqual((self.WIKI_NUM_OF_DATES, len(self.MANY_TICKERS)),
                         data.shape)
        self.assertEqual(self.MANY_TICKERS, list(data.columns))

    def test_price_multiple_tickers_multiple_fields(self):
        # testing for single date (start_date and end_date are the same)
        data = self.quandl_provider.get_price(tickers=self.MANY_TICKERS,
                                              fields=self.MANY_PRICE_FIELDS,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE)

        self.assertEqual(type(data), QFDataArray)
        self.assertEqual(data.shape,
                         (self.WIKI_NUM_OF_DATES, len(
                             self.MANY_TICKERS), len(self.MANY_PRICE_FIELDS)))
        self.assertIsInstance(data.dates.to_index(), pd.DatetimeIndex)
        self.assertEqual(list(data.tickers), self.MANY_TICKERS)
        self.assertEqual(list(data.fields), self.MANY_PRICE_FIELDS)

    def test_price_mixed_databases(self):
        data = self.quandl_provider.get_price(tickers=self.MIXED_DB_TICKERS,
                                              fields=self.MANY_PRICE_FIELDS,
                                              start_date=self.START_DATE,
                                              end_date=self.END_DATE)
        self.assertEqual(type(data), QFDataArray)
        exected_number_of_dates = 280
        self.assertEqual(data.shape,
                         (exected_number_of_dates, len(self.MIXED_DB_TICKERS),
                          len(self.MANY_PRICE_FIELDS)))
        self.assertIsInstance(data.dates.to_index(), pd.DatetimeIndex)
        self.assertEqual(list(data.tickers), self.MIXED_DB_TICKERS)
        self.assertEqual(list(data.fields), self.MANY_PRICE_FIELDS)

    # =========================== Test get_history method ==========================================================

    # ======================== Test Single Ticker
    def test_historical_single_ticker_no_field(self):
        # get all fields
        data = self.quandl_provider.get_history(tickers=self.SINGLE_TICKER,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertIsInstance(data, QFDataFrame)
        self.assertEqual(data.shape,
                         (self.WSE_NUM_OF_DATES, len(self.WSE_OUTPUT_FIELDS)))
        self.assertEqual(set(data.columns), set(self.WSE_OUTPUT_FIELDS))

    def test_historical_single_ticker_single_field(self):
        # single ticker, single field; end_date by default now, frequency by default DAILY, currency by default None
        data = self.quandl_provider.get_history(tickers=self.SINGLE_TICKER,
                                                fields=self.SINGLE_FIELD,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertIsInstance(data, QFSeries)
        self.assertEqual(len(data), self.WSE_NUM_OF_DATES)
        self.assertEqual(data.name, self.SINGLE_TICKER.as_string())

    def test_historical_single_ticker_multiple_fields(self):
        data = self.quandl_provider.get_history(tickers=self.SINGLE_TICKER,
                                                fields=self.MANY_FIELDS,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertEqual(type(data), QFDataFrame)
        self.assertEqual(data.shape,
                         (self.WSE_NUM_OF_DATES, len(self.MANY_FIELDS)))
        self.assertEqual(list(data.columns), self.MANY_FIELDS)

    def test_historical_single_ticker_no_end_date(self):
        # get all fields
        data = self.quandl_provider.get_history(tickers=self.SINGLE_TICKER,
                                                start_date=self.START_DATE)

        self.assertIsInstance(data, QFDataFrame)
        self.assertTrue(data.shape[0] > self.WSE_NUM_OF_DATES)
        self.assertEqual(data.shape[1], len(self.WSE_OUTPUT_FIELDS))
        self.assertEqual(set(data.columns), set(self.WSE_OUTPUT_FIELDS))

    def test_historical_single_ticker_no_dates(self):
        # get all fields
        data = self.quandl_provider.get_history(tickers=self.SINGLE_TICKER)

        self.assertIsInstance(data, QFDataFrame)
        self.assertTrue(data.shape[0] > self.WSE_NUM_OF_DATES)
        self.assertEqual(data.shape[1], len(self.WSE_OUTPUT_FIELDS))
        self.assertEqual(set(data.columns), set(self.WSE_OUTPUT_FIELDS))

    # ======================== Test Multiple Tickers

    def test_historical_multiple_tickers_no_field(self):
        data = self.quandl_provider.get_history(tickers=self.MANY_TICKERS,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertEqual(type(data), QFDataArray)
        self.assertEqual(data.shape,
                         (self.WIKI_NUM_OF_DATES, len(
                             self.MANY_TICKERS), len(self.WIKI_OUTPUT_FIELDS)))
        self.assertEqual(list(data.tickers), self.MANY_TICKERS)
        self.assertEqual(set(data.fields.values), set(self.WIKI_OUTPUT_FIELDS))

    def test_historical_multiple_tickers_single_field(self):
        data = self.quandl_provider.get_history(tickers=self.MANY_TICKERS,
                                                fields=self.SINGLE_FIELD,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertEqual(type(data), QFDataFrame)
        self.assertEqual(data.shape,
                         (self.WIKI_NUM_OF_DATES, len(self.MANY_TICKERS)))
        self.assertEqual(list(data.columns), self.MANY_TICKERS)

    def test_historical_multiple_tickers_multiple_fields(self):
        data = self.quandl_provider.get_history(tickers=self.MANY_TICKERS,
                                                fields=self.MANY_FIELDS,
                                                start_date=self.START_DATE,
                                                end_date=self.END_DATE)

        self.assertEqual(type(data), QFDataArray)
        self.assertEqual(data.shape,
                         (self.WIKI_NUM_OF_DATES, len(
                             self.MANY_TICKERS), len(self.MANY_FIELDS)))
        self.assertEqual(list(data.tickers), self.MANY_TICKERS)
        self.assertEqual(list(data.fields), self.MANY_FIELDS)
Example #25
0
 def contract_to_ticker(self, contract: Contract) -> Ticker:
     return QuandlTicker(ticker=contract.symbol, database_name='WIKI')
Example #26
0
 def contract_to_ticker(self, contract: Contract, strictly_to_specific_ticker=True) -> QuandlTicker:
     return QuandlTicker(ticker=contract.symbol, database_name='WIKI')
Example #27
0
class TestFastAlphaModelsTester(TestCase):
    apple_ticker = QuandlTicker("AAPL", "WIKI")
    ibm_ticker = QuandlTicker("IBM", "WIKI")
    tickers = [apple_ticker, ibm_ticker]

    test_start_date = str_to_date("2015-01-01")
    test_end_date = str_to_date("2015-01-31")

    data_start_date = str_to_date("2014-12-25")
    data_end_date = test_end_date

    frequency = Frequency.DAILY

    MarketOpenEvent.set_trigger_time({
        "hour": 13,
        "minute": 30,
        "second": 0,
        "microsecond": 0
    })
    MarketCloseEvent.set_trigger_time({
        "hour": 20,
        "minute": 0,
        "second": 0,
        "microsecond": 0
    })

    def setUp(self):
        all_fields = PriceField.ohlcv()

        self._mocked_prices_arr = self._make_mock_data_array(
            self.tickers, all_fields)
        self._price_provider_mock = PresetDataProvider(self._mocked_prices_arr,
                                                       self.data_start_date,
                                                       self.data_end_date,
                                                       self.frequency)
        self.timer = SettableTimer()
        self.contract_ticker_mapper = DummyQuandlContractTickerMapper()

        self.alpha_model_type = DummyAlphaModel

    @classmethod
    def _make_mock_data_array(cls, tickers, fields):
        all_dates_index = pd.bdate_range(start=cls.data_start_date,
                                         end=cls.test_end_date)

        num_of_dates = len(all_dates_index)
        num_of_tickers = len(tickers)
        num_of_fields = len(fields)

        start_value = 100.0
        values = np.arange(
            start_value,
            num_of_dates * num_of_tickers * num_of_fields + start_value)
        reshaped_values = np.reshape(
            values, (num_of_dates, num_of_tickers, num_of_fields))

        mocked_result = QFDataArray.create(all_dates_index,
                                           tickers,
                                           fields,
                                           data=reshaped_values)
        mocked_result.loc[:, :, PriceField.Low] -= 50.0
        mocked_result.loc[:, :, PriceField.High] += 50.0

        return mocked_result

    def test_alpha_models_tester(self):
        first_param_set = (10, Exposure.LONG)
        second_param_set = (5, Exposure.SHORT)
        data_handler = FastDataHandler(self._price_provider_mock, self.timer)

        params = [
            FastAlphaModelTesterConfig(
                self.alpha_model_type, {
                    "period_length": 10,
                    "first_suggested_exposure": Exposure.LONG,
                    "risk_estimation_factor": None
                }, ("period_length", "first_suggested_exposure")),
            FastAlphaModelTesterConfig(
                self.alpha_model_type, {
                    "period_length": 5,
                    "first_suggested_exposure": Exposure.SHORT,
                    "risk_estimation_factor": None
                }, ("period_length", "first_suggested_exposure"))
        ]

        tester = FastAlphaModelTester(params, self.tickers,
                                      self.contract_ticker_mapper,
                                      self.test_start_date, self.test_end_date,
                                      data_handler, self.timer)

        backtest_summary = tester.test_alpha_models()
        self.assertEqual(self.tickers, backtest_summary.tickers)
        self.assertEqual(DummyAlphaModel, backtest_summary.alpha_model_type)

        backtest_summary_elements = backtest_summary.elements_list
        self.assertEqual(2 * (len(self.tickers) + 1),
                         len(backtest_summary_elements))

        # check first backtest summary element - trades
        first_elem = backtest_summary_elements[2]
        self.assertEqual(first_param_set, first_elem.model_parameters)

        expected_trades_data = [[
            self.apple_ticker,
            str_to_date("2015-01-02"),
            str_to_date("2015-01-16"), (260.0 / 160.0 - 1), 1.0
        ],
                                [
                                    self.ibm_ticker,
                                    str_to_date("2015-01-02"),
                                    str_to_date("2015-01-16"),
                                    (265.0 / 165.0 - 1), 1.0
                                ]]

        generated_trades_data = [[
            self.contract_ticker_mapper.contract_to_ticker(t.contract),
            t.start_time, t.end_time, t.pnl, t.direction
        ] for t in first_elem.trades]

        self.assertCountEqual(generated_trades_data, expected_trades_data)

        # check first backtest summary element - returns
        all_dates_index = pd.bdate_range(start=self.test_start_date + BDay(2),
                                         end=self.test_end_date)
        expected_returns = SimpleReturnsSeries(
            index=all_dates_index,
            data=[
                0.0615530, 0.0579832, 0.0548048, 0.0519568, 0.0493902,
                0.0470653, 0.0449495, 0.0430157, 0.0412415, 0.0396078,
                0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000,
                0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000
            ])
        assert_series_equal(expected_returns, first_elem.returns_tms)

        # check second backtest summary element
        second_elem = backtest_summary_elements[5]
        self.assertEqual(second_param_set, second_elem.model_parameters)

        expected_trades_data = [[
            self.apple_ticker,
            str_to_date("2015-01-02"),
            str_to_date("2015-01-09"), (1 - 210.0 / 160.0), -1.0
        ],
                                [
                                    self.apple_ticker,
                                    str_to_date("2015-01-16"),
                                    str_to_date("2015-01-23"),
                                    (310.0 / 260.0 - 1), 1.0
                                ],
                                [
                                    self.apple_ticker,
                                    str_to_date("2015-01-23"),
                                    str_to_date("2015-01-30"),
                                    (1 - 360.0 / 310.0), -1.0
                                ],
                                [
                                    self.ibm_ticker,
                                    str_to_date("2015-01-02"),
                                    str_to_date("2015-01-09"),
                                    (1 - 215.0 / 165.0), -1.0
                                ],
                                [
                                    self.ibm_ticker,
                                    str_to_date("2015-01-16"),
                                    str_to_date("2015-01-23"),
                                    (315.0 / 265.0 - 1), 1.0
                                ],
                                [
                                    self.ibm_ticker,
                                    str_to_date("2015-01-23"),
                                    str_to_date("2015-01-30"),
                                    (1 - 365.0 / 315.0), -1.0
                                ]]
        generated_trades_data = [[
            self.contract_ticker_mapper.contract_to_ticker(t.contract),
            t.start_time, t.end_time, t.pnl, t.direction
        ] for t in second_elem.trades]
        self.assertCountEqual(expected_trades_data, generated_trades_data)

        # check second backtest summary element - returns
        all_dates_index = pd.bdate_range(start=self.test_start_date + BDay(2),
                                         end=self.test_end_date)
        expected_returns = SimpleReturnsSeries(
            index=all_dates_index,
            data=[
                -0.0615530, -0.0579832, -0.0548048, -0.0519568, -0.0493902,
                0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000,
                0.0380987, 0.0367003, 0.0354010, 0.0341905, 0.0330601,
                -0.0320020, -0.0310096, -0.0300769, -0.0291986, -0.0283702
            ])
        assert_series_equal(expected_returns, second_elem.returns_tms)
Example #28
0
class TestFastAlphaModelsTester(TestCase):
    apple_ticker = QuandlTicker("AAPL", "WIKI")
    ibm_ticker = QuandlTicker("IBM", "WIKI")
    tickers = [apple_ticker, ibm_ticker]

    test_start_date = str_to_date("2015-01-01")
    test_end_date = str_to_date("2015-01-31")

    data_start_date = str_to_date("2014-12-25")
    data_end_date = test_end_date

    def setUp(self):
        all_fields = PriceField.ohlcv()

        self._mocked_prices_arr = self._make_mock_data_array(self.tickers, all_fields)
        self._price_provider_mock = PresetDataProvider(self._mocked_prices_arr,
                                                       self.data_start_date, self.data_end_date)
        self.timer = SettableTimer()
        self._alpha_model_factory = DummyAlphaModelFactory(self.timer)  # type: AlphaModelFactory

        self.alpha_model_type = DummyAlphaModel

    @classmethod
    def _make_mock_data_array(cls, tickers, fields):
        all_dates_index = pd.bdate_range(start=cls.data_start_date, end=cls.test_end_date)

        num_of_dates = len(all_dates_index)
        num_of_tickers = len(tickers)
        num_of_fields = len(fields)

        start_value = 100.0
        values = np.arange(start_value, num_of_dates * num_of_tickers * num_of_fields + start_value)
        reshaped_values = np.reshape(values, (num_of_dates, num_of_tickers, num_of_fields))

        mocked_result = QFDataArray.create(all_dates_index, tickers, fields, data=reshaped_values)
        mocked_result.loc[:, :, PriceField.Low] -= 50.0
        mocked_result.loc[:, :, PriceField.High] += 50.0

        return mocked_result

    def test_alpha_models_tester(self):
        first_param_set = (10, Exposure.LONG)
        second_param_set = (5, Exposure.SHORT)
        parameter_lists = (first_param_set, second_param_set)

        tester = FastAlphaModelTester(self.alpha_model_type, parameter_lists, self.tickers,
                                      self.test_start_date, self.test_end_date, self._price_provider_mock,
                                      self.timer, self._alpha_model_factory)

        backtest_summary = tester.test_alpha_models()
        self.assertEqual(self.tickers, backtest_summary.tickers)
        self.assertEqual(DummyAlphaModel, backtest_summary.alpha_model_type)

        backtest_summary_elements = backtest_summary.elements_list
        self.assertEqual(2, len(backtest_summary_elements))

        # check first backtest summary element - trades
        first_elem = backtest_summary_elements[0]
        self.assertEqual(first_param_set, first_elem.model_parameters)

        trade_columns = pd.Index([TradeField.Ticker, TradeField.StartDate, TradeField.EndDate, TradeField.Open,
                                  TradeField.MaxGain, TradeField.MaxLoss, TradeField.Close, TradeField.Return,
                                  TradeField.Exposure])

        expected_trades = pd.DataFrame(columns=trade_columns, data=[
            [
                self.apple_ticker, str_to_date("2015-01-02"), str_to_date("2015-01-16"),
                160.0, 141.0, -48.0, 260.0, 260.0 / 160.0 - 1, 1.0
            ],
            [
                self.ibm_ticker, str_to_date("2015-01-02"), str_to_date("2015-01-16"),
                165.0, 141.0, -48.0, 265.0, 265.0 / 165.0 - 1, 1.0
            ]
        ])
        assert_frame_equal(expected_trades, first_elem.trades_df)

        # check first backtest summary element - returns
        all_dates_index = pd.bdate_range(start=self.test_start_date + BDay(2), end=self.test_end_date, name='dates')
        expected_returns = SimpleReturnsSeries(index=all_dates_index, data=[
            0.0615530, 0.0579832, 0.0548048, 0.0519568, 0.0493902,
            0.0470653, 0.0449495, 0.0430157, 0.0412415, 0.0396078,
            0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000,
            0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000
        ])
        assert_series_equal(expected_returns, first_elem.returns_tms)

        # check second backtest summary element
        second_elem = backtest_summary_elements[1]
        self.assertEqual(second_param_set, second_elem.model_parameters)

        trade_columns = pd.Index([TradeField.Ticker, TradeField.StartDate, TradeField.EndDate, TradeField.Open,
                                  TradeField.MaxGain, TradeField.MaxLoss, TradeField.Close, TradeField.Return,
                                  TradeField.Exposure])

        expected_trades = pd.DataFrame(columns=trade_columns, data=[
            [
                self.apple_ticker, str_to_date("2015-01-02"), str_to_date("2015-01-09"),
                160.0, 48.0, -91.0, 210.0, 1 - 210.0 / 160.0, -1.0
            ],
            [
                self.apple_ticker, str_to_date("2015-01-16"), str_to_date("2015-01-23"),
                260.0, 91.0, -48.0, 310.0, 310.0 / 260.0 - 1, 1.0
            ],
            [
                self.apple_ticker, str_to_date("2015-01-23"), str_to_date("2015-01-30"),
                310.0, 48.0, -91.0, 360.0, 1 - 360.0 / 310.0, -1.0
            ],
            [
                self.ibm_ticker, str_to_date("2015-01-02"), str_to_date("2015-01-09"),
                165.0, 48.0, -91.0, 215.0, 1 - 215.0 / 165.0, -1.0
            ],
            [
                self.ibm_ticker, str_to_date("2015-01-16"), str_to_date("2015-01-23"),
                265.0, 91.0, -48.0, 315.0, 315.0 / 265.0 - 1, 1.0
            ],
            [
                self.ibm_ticker, str_to_date("2015-01-23"), str_to_date("2015-01-30"),
                315.0, 48.0, -91.0, 365.0, 1 - 365.0 / 315.0, -1.0
            ]
        ])
        assert_frame_equal(expected_trades, second_elem.trades_df)

        # check second backtest summary element - returns
        all_dates_index = pd.bdate_range(start=self.test_start_date + BDay(2), end=self.test_end_date, name='dates')
        expected_returns = SimpleReturnsSeries(index=all_dates_index, data=[
            -0.0615530, - 0.0579832, - 0.0548048, - 0.0519568, - 0.0493902,
            0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000,
            0.0380987, 0.0367003, 0.0354010, 0.0341905, 0.0330601,
            - 0.0320020, - 0.0310096, - 0.0300769, - 0.0291986, - 0.0283702
        ])
        assert_series_equal(expected_returns, second_elem.returns_tms)
Example #29
0
 def extract_ticker_name(column_name):
     ticker_str, _ = column_name.split(' - ')
     ticker = QuandlTicker.from_string(ticker_str)
     return ticker
Example #30
0
#     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#     See the License for the specific language governing permissions and
#     limitations under the License.

from datetime import datetime

import matplotlib.pyplot as plt

from demo_scripts.demo_configuration.demo_ioc import container
from qf_lib.common.enums.price_field import PriceField
from qf_lib.common.tickers.tickers import QuandlTicker
from qf_lib.common.utils.dateutils.string_to_date import str_to_date
from qf_lib.data_providers.general_price_provider import GeneralPriceProvider
from qf_lib.plotting.helpers.create_skewness_chart import create_skewness_chart

ticker = QuandlTicker('AAPL', 'WIKI')
# ticker = BloombergTicker('SPX Index')

start_date = str_to_date('2010-01-01')
end_date = datetime.now()


def main():
    data_provider = container.resolve(GeneralPriceProvider)
    prices_tms = data_provider.get_price(ticker, PriceField.Close, start_date,
                                         end_date)

    chart = create_skewness_chart(prices_tms)
    chart.plot()
    plt.show(block=True)