text
stringlengths
81
112k
Download human activity recognition dataset from UCI ML Repository and store it at /tsfresh/notebooks/data. Examples ======== >>> from tsfresh.examples import har_dataset >>> har_dataset.download_har_dataset() def download_har_dataset(): """ Download human activity recognition dataset fro...
Add the features calculated using the timeseries_container and add them to the corresponding rows in the input pandas.DataFrame X. To save some computing time, you should only include those time serieses in the container, that you need. You can set the timeseries container with the method :func...
Use the given timeseries from :func:`~set_timeseries_container` and calculate features from it and add them to the data sample X (which can contain other manually-designed features). Then determine which of the features of X are relevant for the given target y. Store those relevant features int...
After the fit step, it is known which features are relevant, Only extract those from the time series handed in with the function :func:`~set_timeseries_container`. If filter_only_tsfresh_features is False, also delete the irrelevant, already present features in the data frame. :param X: the da...
given a DataFrame where records are stored row-wise, rearrange it such that records are stored column-wise. def _preprocess(df): """ given a DataFrame where records are stored row-wise, rearrange it such that records are stored column-wise. """ df = df.stack() df.index.rename(["id", "time...
Calculate the relevance table for the features contained in feature matrix `X` with respect to target vector `y`. The relevance table is calculated for the intended machine learning task `ml_task`. To accomplish this for each feature from the input pandas.DataFrame an univariate feature significance test i...
Infer the machine learning task to select for. The result will be either `'regression'` or `'classification'`. If the target vector only consists of integer typed values or objects, we assume the task is `'classification'`. Else `'regression'`. :param y: The target vector y. :type y: pandas.Series ...
Create a combined relevance table out of a list of relevance tables, aggregating the p-values and the relevances. :param relevance_tables: A list of relevance tables :type relevance_tables: List[pd.DataFrame] :return: The combined relevance table :rtype: pandas.DataFrame def combine_relevance_tabl...
For a given feature, determine if it is real, binary or constant. Here binary means that only two unique values occur in the feature. :param feature_column: The feature column :type feature_column: pandas.Series :return: 'constant', 'binary' or 'real' def get_feature_type(feature_column): """ ...
Extract features from * a :class:`pandas.DataFrame` containing the different time series or * a dictionary of :class:`pandas.DataFrame` each containing one type of time series In both cases a :class:`pandas.DataFrame` with the calculated features will be returned. For a list of all the calculat...
Converts the dataframe df in into a list of individual time seriess. E.g. the DataFrame ==== ====== ========= id kind val ==== ====== ========= 1 a -0.21761 1 a -0.613667 1 a -2.07339 2 b -0.576254 ...
Wrapper around the _do_extraction_on_chunk, which calls it on all chunks in the data frame. A chunk is a subset of the data, with a given kind and id - so a single time series. The data is separated out into those single time series and the _do_extraction_on_chunk is called on each of them. The results are...
Main function of this module: use the feature calculators defined in the default_fc_parameters or kind_to_fc_parameters parameters and extract all features on the chunk. The chunk consists of the chunk id, the chunk kind and the data (as a Series), which is then converted to a numpy array - so a single...
Helper function to extract the configuration of a certain function from the column name. The column name parts (split by "__") should be passed to this function. It will skip the kind name and the function name and only use the parameter parts. These parts will be split up on "_" into the parameter name and...
Helper function to convert parameters to a valid string, that can be used in a column name. Does the opposite which is used in the from_columns function. The parameters are sorted by their name and written out in the form <param name>_<param value>__<param name>_<param value>__ ... If a <param_val...
Helper function to stop the profiling process and write out the profiled data into the given filename. Before this, sort the stats by the passed sorting. :param profiler: An already started profiler (probably by start_profiling). :type profiler: cProfile.Profile :param filename: The name of the output ...
Compute the min, max and median for all columns in the DataFrame. For more information, please see the :func:`~tsfresh.utilities.dataframe_functions.get_range_values_per_column` function. :param X: DataFrame to calculate min, max and median values on :type X: pandas.DataFrame ...
Column-wise replace all ``NaNs``, ``-inf`` and ``+inf`` in the DataFrame `X` with average/extreme values from the provided dictionaries. :param X: DataFrame to impute :type X: pandas.DataFrame :return: imputed DataFrame :rtype: pandas.DataFrame :...
Download the Robot Execution Failures LP1 Data Set[#1] from the UCI Machine Learning Repository [#2] and store it locally. :return: Examples ======== >>> from tsfresh.examples import download_robot_execution_failures >>> download_robot_execution_failures() def download_robot_execution_failur...
Load the Robot Execution Failures LP1 Data Set[1]. The Time series are passed as a flat DataFrame. Examples ======== >>> from tsfresh.examples import load_robot_execution_failures >>> df, y = load_robot_execution_failures() >>> print(df.shape) (1320, 8) :param multiclass: If True, ret...
High level convenience function to extract time series features from `timeseries_container`. Then return feature matrix `X` possibly augmented with relevant features with respect to target vector `y`. For more details see the documentation of :func:`~tsfresh.feature_extraction.extraction.extract_features` and ...
Return list of control parameters :param n: number of samples :type n: int :param kappa_3: inverse bifurcation point :type kappa_3: float :param ratio: ratio (default 0.5) of samples before and beyond drift-bifurcation :type ratio: float :param rel_increase: relative increase from bifu...
Simulates n time-series with l time steps each for the m-dimensional velocity of a dissipative soliton classification=True: target 0 means tau<=1/0.3, Dissipative Soliton with Brownian motion (purely noise driven) target 1 means tau> 1/0.3, Dissipative Soliton with Active Brownian motion (intrinsiv velocit...
Helper function to check for ``NaN`` in the data frame and raise a ``ValueError`` if there is one. :param df: the pandas DataFrame to test for NaNs :type df: pandas.DataFrame :param columns: a list of columns to test for NaNs. If left empty, all columns of the DataFrame will be tested. :type columns: l...
Columnwise replaces all ``NaNs`` and ``infs`` from the DataFrame `df_impute` with average/extreme values from the same columns. This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` is replaced by * ``-inf`` -> ``min`` * ``+inf`` -> ``max`` * ``NaN`` -> ``median`` I...
Replaces all ``NaNs``, ``-infs`` and ``+infs`` from the DataFrame `df_impute` with 0s. The `df_impute` will be modified in place. All its columns will be into converted into dtype ``np.float64``. :param df_impute: DataFrame to impute :type df_impute: pandas.DataFrame :return df_impute: imputed DataFra...
Columnwise replaces all ``NaNs``, ``-inf`` and ``+inf`` from the DataFrame `df_impute` with average/extreme values from the provided dictionaries. This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` is replaced by * ``-inf`` -> by value in col_to_min * ``+inf`` -> by valu...
Retrieves the finite max, min and mean values per column in the DataFrame `df` and stores them in three dictionaries. Those dictionaries `col_to_max`, `col_to_min`, `col_to_median` map the columnname to the maximal, minimal or median value of that column. If a column does not contain any finite values at a...
Restrict df_or_dict to those ids contained in index. :param df_or_dict: a pandas DataFrame or a dictionary. :type df_or_dict: pandas.DataFrame or dict :param column_id: it must be present in the pandas DataFrame or in all DataFrames in the dictionary. It is not allowed to have NaN values in this co...
Aggregates all ids in column_id from the time series container ` :param df_or_dict: a pandas DataFrame or a dictionary. :type df_or_dict: pandas.DataFrame or dict :param column_id: it must be present in the pandas DataFrame or in all DataFrames in the dictionary. It is not allowed to have NaN value...
Try to transform any given input to the internal representation of time series, which is a flat DataFrame (the first format from see :ref:`data-formats-label`). This function can transform pandas DataFrames in different formats or dictionaries into the internal format that we use. It should not be called b...
This method creates sub windows of the time series. It rolls the (sorted) data frames for each kind and each id separately in the "time" domain (which is represented by the sort order of the sort column given by `column_sort`). For each rolling step, a new id is created by the scheme "id={id}, shift={shift}", ...
Takes a singular time series x and constructs a DataFrame df and target vector y that can be used for a time series forecasting task. The returned df will contain, for every time stamp in x, the last max_timeshift data points as a new time series, such can be used to fit a time series forecasting model. ...
Check the significance of all features (columns) of feature matrix X and return a possibly reduced feature matrix only containing relevant features. The feature matrix must be a pandas.DataFrame in the format: +-------+-----------+-----------+-----+-----------+ | index | feature_1 | feature_2 ...
Connect to a running TWS or IB gateway application. After the connection is made the client is fully synchronized and ready to serve requests. This method is blocking. Args: host: Host name or IP address. port: Port number. clientId: ID number to use...
Disconnect from a TWS or IB gateway application. This will clear all session state. def disconnect(self): """ Disconnect from a TWS or IB gateway application. This will clear all session state. """ if not self.client.isConnected(): return stats = self...
Wait on any new update to arrive from the network. Args: timeout: Maximum time in seconds to wait. If 0 then no timeout is used. .. note:: A loop with ``waitOnUpdate`` should not be used to harvest tick data from tickers, since some ticks can go miss...
Iterate until condition is met, with optional timeout in seconds. The yielded value is that of the condition or False when timed out. Args: condition: Predicate function that is tested after every network update. timeout: Maximum time in seconds to wait. ...
List of account values for the given account, or of all accounts if account is left blank. Args: account: If specified, filter for this account name. def accountValues(self, account: str = '') -> List[AccountValue]: """ List of account values for the given account, ...
List of account values for the given account, or of all accounts if account is left blank. This method is blocking on first run, non-blocking after that. Args: account: If specified, filter for this account name. def accountSummary(self, account: str = '') -> List[AccountValue]: ...
List of portfolio items of the default account. def portfolio(self) -> List[PortfolioItem]: """ List of portfolio items of the default account. """ account = self.wrapper.accounts[0] return [v for v in self.wrapper.portfolio[account].values()]
List of positions for the given account, or of all accounts if account is left blank. Args: account: If specified, filter for this account name. def positions(self, account: str = '') -> List[Position]: """ List of positions for the given account, or of all accounts...
List of subscribed :class:`.PnL` objects (profit and loss), optionally filtered by account and/or modelCode. The :class:`.PnL` objects are kept live updated. Args: account: If specified, filter for this account name. modelCode: If specified, filter for this account mode...
List of subscribed :class:`.PnLSingle` objects (profit and loss for single positions). The :class:`.PnLSingle` objects are kept live updated. Args: account: If specified, filter for this account name. modelCode: If specified, filter for this account model. c...
List of all open order trades. def openTrades(self) -> List[Trade]: """ List of all open order trades. """ return [v for v in self.wrapper.trades.values() if v.orderStatus.status not in OrderStatus.DoneStates]
List of all orders from this session. def orders(self) -> List[Order]: """ List of all orders from this session. """ return list( trade.order for trade in self.wrapper.trades.values())
List of all open orders. def openOrders(self) -> List[Order]: """ List of all open orders. """ return [trade.order for trade in self.wrapper.trades.values() if trade.orderStatus.status not in OrderStatus.DoneStates]
List of all executions from this session. def executions(self) -> List[Execution]: """ List of all executions from this session. """ return list(fill.execution for fill in self.wrapper.fills.values())
Get ticker of the given contract. It must have been requested before with reqMktData with the same contract object. The ticker may not be ready yet if called directly after :meth:`.reqMktData`. Args: contract: Contract to get ticker for. def ticker(self, contract: Contract) -> Tick...
Request and return a list of snapshot tickers. The list is returned when all tickers are ready. This method is blocking. Args: contracts: Contracts to get tickers for. regulatorySnapshot: Request NBBO snapshots (may incur a fee). def reqTickers( self, *cont...
Fully qualify the given contracts in-place. This will fill in the missing fields in the contract, especially the conId. Returns a list of contracts that have been successfully qualified. This method is blocking. Args: contracts: Contracts to qualify. def qualifyContracts(...
Create a limit order that is bracketed by a take-profit order and a stop-loss order. Submit the bracket like: .. code-block:: python for o in bracket: ib.placeOrder(contract, o) https://interactivebrokers.github.io/tws-api/bracket_order.html Args: ...
Place the trades in the same One Cancels All (OCA) group. https://interactivebrokers.github.io/tws-api/oca.html Args: orders: The orders that are to be placed together. def oneCancelsAll( orders: List[Order], ocaGroup: str, ocaType: int) -> List[Order]: """ Pla...
Retrieve commission and margin impact without actually placing the order. The given order will not be modified in any way. This method is blocking. Args: contract: Contract to test. order: Order to test. def whatIfOrder(self, contract: Contract, order: Order) -> OrderS...
Place a new order or modify an existing order. Returns a Trade that is kept live updated with status changes, fills, etc. Args: contract: Contract to use for order. order: The order to be placed. def placeOrder(self, contract: Contract, order: Order) -> Trade: "...
Cancel the order and return the Trade it belongs to. Args: order: The order to be canceled. def cancelOrder(self, order: Order) -> Trade: """ Cancel the order and return the Trade it belongs to. Args: order: The order to be canceled. """ self.cl...
It is recommended to use :meth:`.accountValues` instead. Request account values of multiple accounts and keep updated. This method is blocking. Args: account: If specified, filter for this account name. modelCode: If specified, filter for this account model. def reqAc...
It is recommended to use :meth:`.fills` or :meth:`.executions` instead. Request and return a list a list of fills. This method is blocking. Args: execFilter: If specified, return executions that match the filter. def reqExecutions( self, execFilter: Execution...
Start a subscription for profit and loss events. Returns a :class:`.PnL` object that is kept live updated. The result can also be queried from :meth:`.pnl`. https://interactivebrokers.github.io/tws-api/pnl.html Args: account: Subscribe to this account. modelCod...
Cancel PnL subscription. Args: account: Cancel for this account. modelCode: If specified, cancel for this account model. def cancelPnL(self, account, modelCode: str = ''): """ Cancel PnL subscription. Args: account: Cancel for this account. ...
Start a subscription for profit and loss events for single positions. Returns a :class:`.PnLSingle` object that is kept live updated. The result can also be queried from :meth:`.pnlSingle`. https://interactivebrokers.github.io/tws-api/pnl.html Args: account: Subscribe to t...
Cancel PnLSingle subscription for the given account, modelCode and conId. Args: account: Cancel for this account name. modelCode: Cancel for this account model. conId: Cancel for this contract ID. def cancelPnLSingle( self, account: str, modelCode: str, ...
Get a list of contract details that match the given contract. If the returned list is empty then the contract is not known; If the list has multiple values then the contract is ambiguous. The fully qualified contract is available in the the ContractDetails.contract attribute. T...
Request contract descriptions of contracts that match a pattern. This method is blocking. https://interactivebrokers.github.io/tws-api/matching_symbols.html Args: pattern: The first few letters of the ticker symbol, or for longer strings a character sequence matchi...
Request price increments rule. https://interactivebrokers.github.io/tws-api/minimum_increment.html Args: marketRuleId: ID of market rule. The market rule IDs for a contract can be obtained via :meth:`.reqContractDetails` from :class:`.Contrac...
Request realtime 5 second bars. https://interactivebrokers.github.io/tws-api/realtime_bars.html Args: contract: Contract of interest. barSize: Must be 5. whatToShow: Specifies the source for constructing bars. Can be 'TRADES', 'MIDPOINT', 'BID' or 'A...
Cancel the realtime bars subscription. Args: bars: The bar list that was obtained from ``reqRealTimeBars``. def cancelRealTimeBars(self, bars: RealTimeBarList): """ Cancel the realtime bars subscription. Args: bars: The bar list that was obtained from ``reqReal...
Request historical bar data. This method is blocking. https://interactivebrokers.github.io/tws-api/historical_bars.html Args: contract: Contract of interest. endDateTime: Can be set to '' to indicate the current time, or it can be given as a datetime.da...
Cancel the update subscription for the historical bars. Args: bars: The bar list that was obtained from ``reqHistoricalData`` with a keepUpToDate subscription. def cancelHistoricalData(self, bars: BarDataList): """ Cancel the update subscription for the historical b...
Request historical ticks. The time resolution of the ticks is one second. This method is blocking. https://interactivebrokers.github.io/tws-api/historical_time_and_sales.html Args: contract: Contract to query. startDateTime: Can be given as a datetime.date or ...
Get the datetime of earliest available historical data for the contract. Args: contract: Contract of interest. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. formatDate: If set to 2 then the result ...
Subscribe to tick data or request a snapshot. Returns the Ticker that holds the market data. The ticker will initially be empty and gradually (after a couple of seconds) be filled. https://interactivebrokers.github.io/tws-api/md_request.html Args: contract: Contract...
Unsubscribe from realtime streaming tick data. Args: contract: The exact contract object that was used to subscribe with. def cancelMktData(self, contract: Contract): """ Unsubscribe from realtime streaming tick data. Args: contract: The exact c...
Subscribe to tick-by-tick data and return the Ticker that holds the ticks in ticker.tickByTicks. https://interactivebrokers.github.io/tws-api/tick_data.html Args: contract: Contract of interest. tickType: One of 'Last', 'AllLast', 'BidAsk' or 'MidPoint'. nu...
Unsubscribe from tick-by-tick data Args: contract: The exact contract object that was used to subscribe with. def cancelTickByTickData(self, contract: Contract, tickType: str): """ Unsubscribe from tick-by-tick data Args: contract: The exact con...
Subscribe to market depth data (a.k.a. DOM, L2 or order book). https://interactivebrokers.github.io/tws-api/market_depth.html Args: contract: Contract of interest. numRows: Number of depth level on each side of the order book (5 max). isSmartDepth: C...
Unsubscribe from market depth data. Args: contract: The exact contract object that was used to subscribe with. def cancelMktDepth(self, contract: Contract, isSmartDepth=False): """ Unsubscribe from market depth data. Args: contract: The exact co...
Request histogram data. This method is blocking. https://interactivebrokers.github.io/tws-api/histograms.html Args: contract: Contract to query. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. ...
Get fundamental data of a contract in XML format. This method is blocking. https://interactivebrokers.github.io/tws-api/fundamentals.html Args: contract: Contract to query. reportType: * 'ReportsFinSummary': Financial summary * 'Reports...
Do a blocking market scan by starting a subscription and canceling it after the initial list of results are in. This method is blocking. https://interactivebrokers.github.io/tws-api/market_scanners.html Args: subscription: Basic filters. scannerSubscriptionOpti...
Subscribe to market scan data. https://interactivebrokers.github.io/tws-api/market_scanners.html Args: subscription: What to scan for. scannerSubscriptionOptions: Unknown. scannerSubscriptionFilterOptions: Unknown. def reqScannerSubscription( self, subs...
Cancel market data subscription. https://interactivebrokers.github.io/tws-api/market_scanners.html Args: dataList: The scan data list that was obtained from :meth:`.reqScannerSubscription`. def cancelScannerSubscription(self, dataList: ScanDataList): """ Ca...
Calculate the volatility given the option price. This method is blocking. https://interactivebrokers.github.io/tws-api/option_computations.html Args: contract: Option contract. optionPrice: Option price to use in calculation. underPrice: Price of the underl...
Calculate the option price given the volatility. This method is blocking. https://interactivebrokers.github.io/tws-api/option_computations.html Args: contract: Option contract. volatility: Option volatility to use in calculation. underPrice: Price of the un...
Get the option chain. This method is blocking. https://interactivebrokers.github.io/tws-api/options.html Args: underlyingSymbol: Symbol of underlier contract. futFopExchange: Exchange (only for ``FuturesOption``, otherwise leave blank). unde...
Exercise an options contract. https://interactivebrokers.github.io/tws-api/options.html Args: contract: The option contract to be exercised. exerciseAction: * 1 = exercise the option * 2 = let the option lapse exerciseQuantity: Number...
Get the body of a news article. This method is blocking. https://interactivebrokers.github.io/tws-api/news.html Args: providerCode: Code indicating news provider, like 'BZ' or 'FLY'. articleId: ID of the specific article. newsArticleOptions: Unknown. def r...
Get historical news headline. https://interactivebrokers.github.io/tws-api/news.html This method is blocking. Args: conId: Search news articles for contract with this conId. providerCodes: A '+'-separated list of provider codes, like 'BZ+FLY'. ...
Replaces Financial Advisor's settings. Args: faDataType: See :meth:`.requestFA`. xml: The XML-formatted configuration string. def replaceFA(self, faDataType: int, xml: str): """ Replaces Financial Advisor's settings. Args: faDataType: See :meth:`.re...
Create pandas DataFrame from the sequence of same-type objects. When a list of labels is given then only retain those labels and drop the rest. def df(objs, labels=None): """ Create pandas DataFrame from the sequence of same-type objects. When a list of labels is given then only retain those labels...
Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON. def tree(obj): """ Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON. """ from .objects import Object if isinstance(obj, (bool, int, float, str, b...
Create candlestick plot for the given bars. The bars can be given as a DataFrame or as a list of bar objects. def barplot(bars, title='', upColor='blue', downColor='red'): """ Create candlestick plot for the given bars. The bars can be given as a DataFrame or as a list of bar objects. """ impor...
Create a log handler that logs to the given file. def logToFile(path, level=logging.INFO): """ Create a log handler that logs to the given file. """ logger = logging.getLogger() logger.setLevel(level) formatter = logging.Formatter( '%(asctime)s %(name)s %(levelname)s %(message)s') h...
Create a log handler that logs to the console. def logToConsole(level=logging.INFO): """ Create a log handler that logs to the console. """ logger = logging.getLogger() logger.setLevel(level) formatter = logging.Formatter( '%(asctime)s %(name)s %(levelname)s %(message)s') handler = ...
Format the integer or float n to 3 significant digits + SI prefix. def formatSI(n) -> str: """ Format the integer or float n to 3 significant digits + SI prefix. """ s = '' if n < 0: n = -n s += '-' if type(n) is int and n < 1000: s = str(n) + ' ' elif n < 1e-22: ...
By default run the event loop forever. When awaitables (like Tasks, Futures or coroutines) are given then run the event loop until each has completed and return their results. An optional timeout (in seconds) can be given that will raise asyncio.TimeoutError if the awaitables are not ready within the ...
Schedule the callback to be run at the given time with the given arguments. Args: time: Time to run callback. If given as :py:class:`datetime.time` then use today as date. callback: Callable scheduled to run. args: Arguments for to call callback with. def schedule( ...
Iterator that waits periodically until certain time points are reached while yielding those time points. Args: start: Start time, can be specified as datetime.datetime, or as datetime.time in which case today is used as the date end: End time, can be specified as datetime.datetime, ...
Async version of :meth:`timeRange`. async def timeRangeAsync( start: datetime.time, end: datetime.time, step: float) -> AsyncIterator[datetime.datetime]: """ Async version of :meth:`timeRange`. """ assert step > 0 start = _fillDate(start) end = _fillDate(end) delta = datetim...
Async version of :meth:`waitUntil`. async def waitUntilAsync(t: datetime.time) -> bool: """ Async version of :meth:`waitUntil`. """ t = _fillDate(t) now = datetime.datetime.now(t.tzinfo) secs = (t - now).total_seconds() await asyncio.sleep(secs) return True