Esempio n. 1
0
 def _set_bar_for_today(self, open_price, high_price, low_price,
                        close_price, volume):
     self.data_handler.get_current_bar.side_effect = lambda tickers: pd.DataFrame(
         index=pd.Index(tickers),
         columns=PriceField.ohlcv(),
         data=[[open_price, high_price, low_price, close_price, volume]])
def future_ticker_example(path_to_data_files: str):
    """
    In order to run the example you need to provide the path to the top directory, containing your data files. The
    example below will:

    1. initialize the Silver FutureTicker
    2. return the list of tickers belonging to the futures chain
    3. return the current specific ticker
    4. check for some tickers, if they belong to the Silver futures family
    5. return Open, High, Low, Close and Volume pricing data for the current specific ticker

    Parameters
    -----------
    path_to_data_files: str
        path to the top directory, which contains all your Portara data files
    """

    start_date = str_to_date('2020-12-02')
    end_date = str_to_date('2021-02-01')
    fields = PriceField.ohlcv()
    # Use the front contract (N = 1)
    # Roll the tickers 1 day before the expiration (days_before_exp_date = 1)
    # Set the point value to 50 (value for each of the contracts can be checked in Portara)
    future_ticker = PortaraFutureTicker('Silver',
                                        'SIA{}',
                                        1,
                                        1,
                                        50,
                                        designated_contracts="HKNUZ")
    daily_freq = Frequency.DAILY

    if path_to_data_files is None:
        raise ValueError(
            "Please provide a correct path to the Portara data and assign it to the "
            "path_to_data_files variable.")

    dp = PortaraDataProvider(path_to_data_files, future_ticker, fields,
                             start_date, end_date, daily_freq)

    # Initialize the future ticker with the data provider and timer. Timer is used to identify the current front ticker.
    timer = SettableTimer()
    future_ticker.initialize_data_provider(timer, dp)

    print(
        '\nCurrent individual contract (front contract) as of 10th December 2020:'
    )
    timer.set_current_time(str_to_date('2020-12-10'))
    current_ticker = future_ticker.get_current_specific_ticker()
    print(f'> {current_ticker}')

    print(
        '\nCurrent individual contract (front contract) as of 10th January 2021:'
    )
    timer.set_current_time(str_to_date('2021-01-10'))
    current_ticker = future_ticker.get_current_specific_ticker()
    print(f'> {current_ticker}')

    print(
        '\nCheck if the following tickers belong to the Silver futures chain:')
    ticker = PortaraTicker('SIA2017H', SecurityType.FUTURE, 50)
    print(f'- {ticker}: {future_ticker.belongs_to_family(ticker)}')
    ticker = PortaraTicker('OH2017H', SecurityType.FUTURE, 50)
    print(f'- {ticker}: {future_ticker.belongs_to_family(ticker)}')
    ticker = PortaraTicker('SIA2017', SecurityType.FUTURE, 50)
    print(f'- {ticker}: {future_ticker.belongs_to_family(ticker)}')
    ticker = PortaraTicker('SIA1999Z', SecurityType.FUTURE, 50)
    print(f'- {ticker}: {future_ticker.belongs_to_family(ticker)}')

    print(
        '\nOpen, High, Low, Close and Volume pricing data for the current specific ticker (as of 10th January 2021)'
    )
    prices = dp.get_price(current_ticker, PriceField.ohlcv(), start_date,
                          end_date, daily_freq)
    print(prices)
Esempio n. 3
0
    def get_current_bar(self, tickers: Union[Ticker, Sequence[Ticker]], frequency: Frequency = None) \
            -> Union[QFSeries, QFDataFrame]:
        """
        Gets the current bar(s) for given Ticker(s). If the bar is not available yet (e.g. before the market close),
        None is returned.

        If the request for single Ticker was made, then the result is a QFSeries indexed with PriceFields (OHLCV).
        If the request for multiple Tickers was made, then the result has Tickers as an index and PriceFields
        as columns.

        Normally on working days the method will return non-empty bars in the time between (inclusive)
        MarketCloseEvent and midnight (exclusive).

        On non-working days or on working days in the time between midnight (inclusive) and MarketClose (exclusive),
        e.g. 12:00, the returned bars will contain Nones as values.

        Parameters
        -----------
        tickers: Ticker, Sequence[Ticker]
            tickers of the securities which prices should be downloaded
        frequency: Frequency
            frequency of the data

        Returns
        -------
        QFSeries, QFDataFrame
            current bar
        """
        if not tickers:
            return QFSeries()

        frequency = frequency or self.fixed_data_provider_frequency or Frequency.DAILY

        tickers, was_single_ticker_provided = convert_to_list(tickers, Ticker)

        current_datetime = self.timer.now()

        if self.time_helper.datetime_of_latest_market_event(
                MarketCloseEvent) < current_datetime:
            last_available_bars = QFDataFrame(index=tickers,
                                              columns=PriceField.ohlcv())
        else:
            current_date = self._zero_out_time_component(current_datetime)
            start_date = current_date - RelativeDelta(days=7)

            prices_data_array = self.get_price(
                tickers=tickers,
                fields=PriceField.ohlcv(),
                start_date=start_date,
                end_date=current_date,
                frequency=frequency)  # type: QFDataArray
            try:
                last_available_bars = cast_data_array_to_proper_type(
                    prices_data_array.loc[current_date])
            except KeyError:
                return QFDataFrame(index=tickers, columns=PriceField.ohlcv())

        if was_single_ticker_provided:
            last_available_bars = last_available_bars.iloc[0, :]

        return last_available_bars