text
stringlengths
81
112k
Use nested asyncio event loop for Jupyter notebooks. def startLoop(): """ Use nested asyncio event loop for Jupyter notebooks. """ def _ipython_loop_asyncio(kernel): ''' Use asyncio event loop for the given IPython kernel. ''' loop = asyncio.get_event_loop() def...
Run combined Qt5/asyncio event loop. Args: qtLib: Name of Qt library to use, can be 'PyQt5' or 'PySide2'. period: Period in seconds to poll Qt. def useQt(qtLib: str = 'PyQt5', period: float = 0.01): """ Run combined Qt5/asyncio event loop. Args: qtLib: Name of Qt library to us...
Format date or datetime to string that IB uses. def formatIBDatetime(dt) -> str: """ Format date or datetime to string that IB uses. """ if not dt: s = '' elif isinstance(dt, datetime.datetime): if dt.tzinfo: # convert to local system timezone dt = dt.astimez...
Parse string in IB date or datetime format to datetime. def parseIBDatetime(s): """ Parse string in IB date or datetime format to datetime. """ if len(s) == 8: # YYYYmmdd y = int(s[0:4]) m = int(s[4:6]) d = int(s[6:8]) dt = datetime.date(y, m, d) elif s.isdig...
Return values as a tuple. def tuple(self): """ Return values as a tuple. """ return tuple(getattr(self, k) for k in self.__class__.defaults)
Return key-value pairs as a dictionary. def dict(self): """ Return key-value pairs as a dictionary. """ return {k: getattr(self, k) for k in self.__class__.defaults}
Return differences between self and other as dictionary of 2-tuples. def diff(self, other): """ Return differences between self and other as dictionary of 2-tuples. """ diff = {} for k in self.__class__.defaults: left = getattr(self, k) right = getattr(ot...
Get a dictionary of all attributes that differ from the default. def nonDefaults(self): """ Get a dictionary of all attributes that differ from the default. """ nonDefaults = {} for k, d in self.__class__.defaults.items(): v = getattr(self, k) if v != d a...
Start a new request and return the future that is associated with with the key and container. The container is a list by default. def startReq(self, key, contract=None, container=None): """ Start a new request and return the future that is associated with with the key and container. The...
Finish the future of corresponding key with the given result. If no result is given then it will be popped of the general results. def _endReq(self, key, result=None, success=True): """ Finish the future of corresponding key with the given result. If no result is given then it will be p...
Start a tick request that has the reqId associated with the contract. Return the ticker. def startTicker(self, reqId, contract, tickType): """ Start a tick request that has the reqId associated with the contract. Return the ticker. """ ticker = self.tickers.get(id(contra...
Register a live subscription. def startSubscription(self, reqId, subscriber, contract=None): """ Register a live subscription. """ self._reqId2Contract[reqId] = contract self.reqId2Subscriber[reqId] = subscriber
Unregister a live subscription. def endSubscription(self, subscriber): """ Unregister a live subscription. """ self._reqId2Contract.pop(subscriber.reqId, None) self.reqId2Subscriber.pop(subscriber.reqId, None)
This wrapper is called to: * feed in open orders at startup; * feed in open orders or order updates from other clients and TWS if clientId=master id; * feed in manual orders and order updates from TWS if clientId=0; * handle openOrders and allOpenOrders responses. def openOrd...
This wrapper handles both live fills and responses to reqExecutions. def execDetails(self, reqId, contract, execution): """ This wrapper handles both live fills and responses to reqExecutions. """ if execution.orderId == UNSET_INTEGER: # bug in TWS: executions of manual orde...
Get statistics about the connection. def connectionStats(self) -> ConnectionStats: """ Get statistics about the connection. """ if not self.isReady(): raise ConnectionError('Not connected') return ConnectionStats( self._startTime, time.time() ...
Get new request ID. def getReqId(self) -> int: """ Get new request ID. """ if not self.isReady(): raise ConnectionError('Not connected') newId = self._reqIdSeq self._reqIdSeq += 1 return newId
Disconnect from IB connection. def disconnect(self): """ Disconnect from IB connection. """ self.connState = Client.DISCONNECTED if self.conn is not None: self._logger.info('Disconnecting') self.conn.disconnect() self.wrapper.connectionClosed(...
Serialize and send the given fields using the IB socket protocol. def send(self, *fields): """ Serialize and send the given fields using the IB socket protocol. """ if not self.isConnected(): raise ConnectionError('Not connected') msg = io.StringIO() for fie...
Create a message handler that invokes a wrapper method with the in-order message fields as parameters, skipping over the first ``skip`` fields, and parsed according to the ``types`` list. def wrap(self, methodName, types, skip=2): """ Create a message handler that invokes a wrapper meth...
Decode fields and invoke corresponding wrapper method. def interpret(self, fields): """ Decode fields and invoke corresponding wrapper method. """ try: msgId = int(fields[0]) handler = self.handlers[msgId] handler(fields) except Exception: ...
Parse the object's properties according to its default types. def parse(self, obj): """ Parse the object's properties according to its default types. """ for k, default in obj.__class__.defaults.items(): typ = type(default) if typ is str: continue...
Get the set of topics that can be extracted from this report. def topics(self): """ Get the set of topics that can be extracted from this report. """ return set(node.tag for node in self.root.iter() if node.attrib)
Extract items of given topic and return as list of objects. The topic is a string like TradeConfirm, ChangeInDividendAccrual, Order, etc. def extract(self, topic: str, parseNumbers=True) -> list: """ Extract items of given topic and return as list of objects. The topic is a st...
Same as extract but return the result as a pandas DataFrame. def df(self, topic: str, parseNumbers=True): """ Same as extract but return the result as a pandas DataFrame. """ return util.df(self.extract(topic, parseNumbers))
Download report for the given ``token`` and ``queryId``. def download(self, token, queryId): """ Download report for the given ``token`` and ``queryId``. """ url = ( 'https://gdcdyn.interactivebrokers.com' f'/Universal/servlet/FlexStatementService.SendReq...
Load report from XML file. def load(self, path): """ Load report from XML file. """ with open(path, 'rb') as f: self.data = f.read() self.root = et.fromstring(self.data)
Save report to XML file. def save(self, path): """ Save report to XML file. """ with open(path, 'wb') as f: f.write(self.data)
Create and a return a specialized contract based on the given secType, or a general Contract if secType is not given. def create(**kwargs): """ Create and a return a specialized contract based on the given secType, or a general Contract if secType is not given. """ secTy...
See if this ticker has a valid bid and ask. def hasBidAsk(self) -> bool: """ See if this ticker has a valid bid and ask. """ return ( self.bid != -1 and not isNan(self.bid) and self.bidSize > 0 and self.ask != -1 and not isNan(self.ask) and self.askSize > 0)
Return average of bid and ask, or NaN if no valid bid and ask are available. def midpoint(self) -> float: """ Return average of bid and ask, or NaN if no valid bid and ask are available. """ return (self.bid + self.ask) / 2 if self.hasBidAsk() else nan
Return the first available one of * last price if within current bid/ask; * average of bid and ask (midpoint); * close price. def marketPrice(self) -> float: """ Return the first available one of * last price if within current bid/ask; * average of bid and ask ...
To add keywords from a file Args: keyword_file : path to keywords file encoding : specify the encoding of the file Examples: keywords file format can be like: >>> # Option 1: keywords.txt content >>> # java_2e=>java >>> # java pr...
To add keywords from a dictionary Args: keyword_dict (dict): A dictionary with `str` key and (list `str`) as value Examples: >>> keyword_dict = { "java": ["java_2e", "java programing"], "product management": ["PM", "product manager"] ...
To remove keywords from a dictionary Args: keyword_dict (dict): A dictionary with `str` key and (list `str`) as value Examples: >>> keyword_dict = { "java": ["java_2e", "java programing"], "product management": ["PM", "product manager"] ...
To add keywords from a list Args: keyword_list (list(str)): List of keywords to add Examples: >>> keyword_processor.add_keywords_from_list(["java", "python"]}) Raises: AttributeError: If `keyword_list` is not a list. def add_keywords_from_list(self, keyword...
To remove keywords present in list Args: keyword_list (list(str)): List of keywords to remove Examples: >>> keyword_processor.remove_keywords_from_list(["java", "python"]}) Raises: AttributeError: If `keyword_list` is not a list. def remove_keywords_from_li...
Recursively builds a dictionary of keywords present in the dictionary And the clean name mapped to those keywords. Args: term_so_far : string term built so far by adding all previous characters current_dict : dict current recursive position in dic...
Searches in the string for all keywords present in corpus. Keywords present are added to a list `keywords_extracted` and returned. Args: sentence (str): Line of text where we will search for keywords Returns: keywords_extracted (list(str)): List of terms/keywords found ...
Searches in the string for all keywords present in corpus. Keywords present are replaced by the clean name and a new string is returned. Args: sentence (str): Line of text where we will replace keywords Returns: new_sentence (str): Line of text with replaced keywords ...
Computes the Spearman Rank Correlation based Information Coefficient (IC) between factor values and N period forward returns for each period in the factor index. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1...
Get the mean information coefficient of specified groups. Answers questions like: What is the mean IC for each month? What is the mean IC for each group for our whole timerange? What is the mean IC for for each group, each week? Parameters ---------- factor_data : pd.DataFrame - MultiIndex ...
Computes asset weights by factor values and dividing by the sum of their absolute value (achieving gross leverage of 1). Positive factor values will results in positive weights and negative values in negative weights. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiInde...
Computes period wise returns for portfolio weighted by factor values. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each per...
Compute the alpha (excess returns), alpha t-stat (alpha significance), and beta (market exposure) of a factor. A regression is run with the period wise factor universe mean return as the independent variable and mean period wise return from a portfolio weighted by factor values as the dependent variable...
Builds cumulative returns from 'period' returns. This function simulates the cumulative effect that a series of gains or losses (the 'returns') have on an original amount of capital over a period of time. if F is the frequency at which returns are computed (e.g. 1 day if 'returns' contains daily values...
Builds net position values time series, the portfolio percentage invested in each position. Parameters ---------- weights: pd.Series pd.Series containing factor weights, the index contains timestamps at which the trades are computed and the values correspond to assets weights ...
Computes mean returns for factor quantiles across provided forward returns columns. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for ...
Computes the difference between the mean returns of two quantiles. Optionally, computes the standard error of this difference. Parameters ---------- mean_returns : pd.DataFrame DataFrame of mean period wise returns by quantile. MultiIndex containing date and quantile. See me...
Computes the proportion of names in a factor quantile that were not in that quantile in the previous period. Parameters ---------- quantile_factor : pd.Series DataFrame with date, asset and factor quantile. quantile : int Quantile on which to perform turnover analysis. period: s...
Computes autocorrelation of mean factor ranks in specified time spans. We must compare period to period factor ranks rather than factor values to account for systematic shifts in the factor values of all names or names within a group. This metric is useful for measuring the turnover of a factor. If the ...
A date and equity pair is extracted from each index row in the factor dataframe and for each of these pairs a return series is built starting from 'before' the date and ending 'after' the date specified in the pair. All those returns series are then aligned to a common index (-before to after) and retur...
Plots average cumulative returns by factor quantiles in the period range defined by -periods_before to periods_after Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alp...
Simulate a portfolio using the factor in input and returns the cumulative returns of the simulated portfolio Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha facto...
Simulate a portfolio using the factor in input and returns the assets positions as percentage of the total portfolio. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single al...
Simulate a portfolio using the input factor and returns the portfolio performance data properly formatted for Pyfolio analysis. For more details on how this portfolio is built see: - performance.cumulative_returns (how the portfolio returns are computed) - performance.factor_weights (how assets weights...
Creates a small summary tear sheet with returns, information, and turnover analysis. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for ...
Creates a tear sheet for returns analysis of a factor. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor qua...
Creates a tear sheet for information analysis of a factor. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor...
Creates a tear sheet for analyzing the turnover properties of a factor. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each perio...
Creates a full tear sheet for analysis and evaluating single return predicting (alpha) factor. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward ret...
Creates a tear sheet to view the average cumulative returns for a factor within a window (pre and post event). Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex Series indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor...
Creates an event study tear sheet for analysis of a specific event. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single event, forward returns for each period, the fact...
Re-raise the last exception that was active in the current scope without losing the stacktrace but adding an additional message. This is hacky because it has to be compatible with both python 2/3 def rethrow(exception, additional_message): """ Re-raise the last exception that was active in the current ...
Give user a more informative error in case it is not possible to properly calculate quantiles on the input dataframe (factor) def non_unique_bin_edges_error(func): """ Give user a more informative error in case it is not possible to properly calculate quantiles on the input dataframe (factor) """ ...
Computes period wise factor quantiles. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that f...
Infer the trading calendar from factor and price information. Parameters ---------- factor_idx : pd.DatetimeIndex The factor datetimes for which we are computing the forward returns prices_idx : pd.DatetimeIndex The prices datetimes associated withthe factor data Returns ------...
Finds the N period forward returns (as percent change) for each asset provided. Parameters ---------- factor : pd.Series - MultiIndex A MultiIndex Series indexed by timestamp (level 0) and asset (level 1), containing the values for a single alpha factor. - See full explanation ...
Convert forward returns to returns relative to mean period wise all-universe or group returns. group-wise normalization incorporates the assumption of a group neutral portfolio constraint and thus allows allows the factor to be evaluated across groups. For example, if AAPL 5 period return is 0.1% a...
Pretty print a pandas DataFrame. Uses HTML output if running inside Jupyter Notebook, otherwise formatted text output. Parameters ---------- table : pd.Series or pd.DataFrame Table to pretty-print. name : str, optional Table name to display in upper left corner. fmt : str, ...
Formats the factor data, forward return data, and group mappings into a DataFrame that contains aligned MultiIndex indices of timestamp and asset. The returned data will be formatted to be suitable for Alphalens functions. It is safe to skip a call to this function and still make use of Alphalens funct...
Formats the factor data, pricing data, and group mappings into a DataFrame that contains aligned MultiIndex indices of timestamp and asset. The returned data will be formatted to be suitable for Alphalens functions. It is safe to skip a call to this function and still make use of Alphalens functionalit...
Convert returns to 'one_period_len' rate of returns: that is the value the returns would have every 'one_period_len' if they had grown at a steady rate Parameters ---------- period_ret: pd.DataFrame DataFrame containing returns values with column headings representing the return per...
one_period_len standard deviation (or standard error) approximation Parameters ---------- period_std: pd.DataFrame DataFrame containing standard deviation or standard error values with column headings representing the return period. base_period: string The base period length use...
Utility that detects and returns the columns that are forward returns def get_forward_returns_columns(columns): """ Utility that detects and returns the columns that are forward returns """ pattern = re.compile(r"^(\d+([Dhms]|ms|us|ns))+$", re.IGNORECASE) valid_columns = [(pattern.match(col) is not...
Utility that converts a pandas.Timedelta to a string representation compatible with pandas.Timedelta constructor format Parameters ---------- timedelta: pd.Timedelta Returns ------- string string representation of 'timedelta' def timedelta_to_string(timedelta): """ Utility...
Add timedelta to 'input' taking into consideration custom frequency, which is used to deal with custom calendars, such as a trading calendar Parameters ---------- input : pd.DatetimeIndex or pd.Timestamp timedelta : pd.Timedelta freq : pd.DataOffset (CustomBusinessDay, Day or BusinessDay) ...
Compute the difference between two pd.Timedelta taking into consideration custom frequency, which is used to deal with custom calendars, such as a trading calendar Parameters ---------- start : pd.Timestamp end : pd.Timestamp freq : CustomBusinessDay (see infer_trading_calendar) freq : ...
Decorator to set plotting context and axes style during function call. def customize(func): """ Decorator to set plotting context and axes style during function call. """ @wraps(func) def call_w_context(*args, **kwargs): set_context = kwargs.pop('set_context', True) if set_context: ...
Plots Spearman Rank Information Coefficient and IC moving average for a given factor. Parameters ---------- ic : pd.DataFrame DataFrame indexed by date, with IC for each forward return. ax : matplotlib.Axes, optional Axes upon which to plot. Returns ------- ax : matplot...
Plots Spearman Rank Information Coefficient histogram for a given factor. Parameters ---------- ic : pd.DataFrame DataFrame indexed by date, with IC for each forward return. ax : matplotlib.Axes, optional Axes upon which to plot. Returns ------- ax : matplotlib.Axes ...
Plots Spearman Rank Information Coefficient "Q-Q" plot relative to a theoretical distribution. Parameters ---------- ic : pd.DataFrame DataFrame indexed by date, with IC for each forward return. theoretical_dist : scipy.stats._continuous_distns Continuous distribution generator. sci...
Plots mean period wise returns for factor quantiles. Parameters ---------- mean_ret_by_q : pd.DataFrame DataFrame with quantile, (group) and mean period wise return values. by_group : bool Disaggregated figures by group. ylim_percentiles : tuple of integers Percentiles of ob...
Plots a violin box plot of period wise returns for factor quantiles. Parameters ---------- return_by_q : pd.DataFrame - MultiIndex DataFrame with date and quantile as rows MultiIndex, forward return windows as columns, returns as values. ylim_percentiles : tuple of integers Perc...
Plots mean period wise returns for factor quantiles. Parameters ---------- mean_returns_spread : pd.Series Series with difference between quantile mean returns by period. std_err : pd.Series Series with standard error of difference between quantile mean returns each period. ...
Plots Spearman Rank Information Coefficient for a given factor over provided forward returns. Separates by group. Parameters ---------- ic_group : pd.DataFrame group-wise mean period wise returns. ax : matplotlib.Axes, optional Axes upon which to plot. Returns ------- a...
Plots factor rank autocorrelation over time. See factor_rank_autocorrelation for more details. Parameters ---------- factor_autocorrelation : pd.Series Rolling 1 period (defined by time_rule) autocorrelation of factor values. period: int, optional Period over which the autoc...
Plots period wise top and bottom quantile factor turnover. Parameters ---------- quantile_turnover: pd.Dataframe Quantile turnover (each DataFrame column a quantile). period: int, optional Period over which to calculate the turnover ax : matplotlib.Axes, optional Axes upon w...
Plots a heatmap of the information coefficient or returns by month. Parameters ---------- mean_monthly_ic : pd.DataFrame The mean monthly IC for N periods forward. Returns ------- ax : matplotlib.Axes The axes that were plotted on. def plot_monthly_ic_heatmap(mean_monthly_ic, ...
Plots the cumulative returns of the returns series passed in. Parameters ---------- factor_returns : pd.Series Period wise returns of dollar neutral portfolio weighted by factor value. period: pandas.Timedelta or string Length of period for which the returns are computed (e.g. 1...
Plots the cumulative returns of various factor quantiles. Parameters ---------- quantile_returns : pd.DataFrame Returns by factor quantile period: pandas.Timedelta or string Length of period for which the returns are computed (e.g. 1 day) if 'period' is a string it must follow p...
Plots sector-wise mean daily returns for factor quantiles across provided forward price movement columns. Parameters ---------- avg_cumulative_returns: pd.Dataframe The format is the one returned by performance.average_cumulative_return_by_quantile by_quantile : boolean, optional ...
Plots the distribution of events in time. Parameters ---------- events : pd.Series A pd.Series whose index contains at least 'date' level. num_bars : integer, optional Number of bars to plot ax : matplotlib.Axes, optional Axes upon which to plot. Returns ------- ...
Closing a cursor just exhausts all remaining data. def close(self): """ Closing a cursor just exhausts all remaining data. """ conn = self.connection if conn is None: return try: while self.nextset(): pass finally: ...
Get the next query set def _nextset(self, unbuffered=False): """Get the next query set""" conn = self._get_db() current_result = self._result if current_result is None or current_result is not conn._result: return None if not current_result.has_next: retu...
Returns the exact string that is sent to the database by calling the execute() method. This method follows the extension to the DB API 2.0 followed by Psycopg. def mogrify(self, query, args=None): """ Returns the exact string that is sent to the database by calling the execute(...
Execute a query :param str query: Query to execute. :param args: parameters used with query. (optional) :type args: tuple, list or dict :return: Number of affected rows :rtype: int If args is a list or tuple, %s can be used as a placeholder in the query. If ar...
Execute stored procedure procname with args procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any modified parameters must be returned. This ...
Fetch the next row def fetchone(self): """Fetch the next row""" self._check_executed() if self._rows is None or self.rownumber >= len(self._rows): return None result = self._rows[self.rownumber] self.rownumber += 1 return result
Fetch several rows def fetchmany(self, size=None): """Fetch several rows""" self._check_executed() if self._rows is None: return () end = self.rownumber + (size or self.arraysize) result = self._rows[self.rownumber:end] self.rownumber = min(end, len(self._row...