INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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...
def calculateImpliedVolatility( self, contract: Contract, optionPrice: float, underPrice: float, implVolOptions: List[TagValue] = None) -> OptionComputation: """ Calculate the volatility given the option price. This method is blocking. https://intera...
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...
def reqTickByTickData( self, contract: Contract, tickType: str, numberOfTicks: int = 0, ignoreSize: bool = False) -> Ticker: """ Subscribe to tick-by-tick data and return the Ticker that holds the ticks in ticker.tickByTicks. https://interactivebrokers.github.io/...
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...
def calculateOptionPrice( self, contract: Contract, volatility: float, underPrice: float, optPrcOptions=None) -> OptionComputation: """ Calculate the option price given the volatility. This method is blocking. https://interactivebrokers.github.io/tws...
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) -> OrderState: """ 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. ...
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...
def exerciseOptions( self, contract: Contract, exerciseAction: int, exerciseQuantity: int, account: str, override: int): """ Exercise an options contract. https://interactivebrokers.github.io/tws-api/options.html Args: contract: The option contract t...
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 ``reqRealTimeBars``. """ self.client.cancelRealTimeBars(bars.reqId) self.wrapper.endSubscription(bars)
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...
def reqMktDepth( self, contract: Contract, numRows: int = 5, isSmartDepth: bool = False, mktDepthOptions=None) -> Ticker: """ Subscribe to market depth data (a.k.a. DOM, L2 or order book). https://interactivebrokers.github.io/tws-api/market_depth.html Args: ...
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: s = '0.00 ' else: assert n < 9.99e26 log = ...
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())
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, *contracts: List[Contract], regulatorySnapshot: bool = False) -> List[Ticker]: """ Request and return a list of snapshot tickers. The list is returned when all tickers are ready. This method is blocking. Args: contracts:...
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...
def reqSecDefOptParams( self, underlyingSymbol: str, futFopExchange: str, underlyingSecType: str, underlyingConId: int) -> List[OptionChain]: """ Get the option chain. This method is blocking. https://interactivebrokers.github.io/tws-api/options.html...
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.isdigit(): dt = datetime.datetime.fromtimestamp( ...
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}
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 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]
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 contract object that was used to subscribe with. """ ticker = self.ticker(contract) reqId = self.wrapper.endTicker(ticker...
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: ...
def bracketOrder( self, action: str, quantity: float, limitPrice: float, takeProfitPrice: float, stopLossPrice: float, **kwargs) -> BracketOrder: """ Create a limit order that is bracketed by a take-profit order and a stop-loss order. Submit the bracket like: ...
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. modelCode: If specified, cancel for this account model. """ key = (account, modelCode) reqId = self.wrapper.pnlKey2ReqId.pop(ke...
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( time: Union[datetime.time, datetime.datetime], callback: Callable, *args): """ 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. ...
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...
def reqScannerData( self, subscription: ScannerSubscription, scannerSubscriptionOptions: List[TagValue] = None, scannerSubscriptionFilterOptions: List[TagValue] = None) -> ScanDataList: """ Do a blocking market scan by starting a subscription and canceling...
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...
def reqMatchingSymbols(self, pattern: str) -> List[ContractDescription]: """ 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 le...
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 = logging.StreamHandler() handler.setFormatter...
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:`.requestFA`. xml: The XML-formatted configuration string. """ self.client.replaceFA(faDataType, xml)
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...
def reqMarketRule(self, marketRuleId: int) -> PriceIncrement: """ 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 ...
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 = datetime.timedelta(seconds=step) t = sta...
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 ...
def reqHeadTimeStamp( self, contract: Contract, whatToShow: str, useRTH: bool, formatDate: int = 1) -> datetime.datetime: """ Get the datetime of earliest available historical data for the contract. Args: contract: Contract of interest. us...
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') handler = logging.FileHandler(path) handler.setF...
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 ...
def reqHistoricalTicks( self, contract: Contract, startDateTime: Union[str, datetime.date], endDateTime: Union[str, datetime.date], numberOfTicks: int, whatToShow: str, useRth: bool, ignoreSize: bool = False, miscOptions: List[TagValue] = None) -> ...
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 reqNewsArticle( self, providerCode: str, articleId: str, newsArticleOptions: List[TagValue] = None) -> NewsArticle: """ Get the body of a news article. This method is blocking. https://interactivebrokers.github.io/tws-api/news.html Args: ...
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, ...
def timeRange( start: datetime.time, end: datetime.time, step: float) -> Iterator[datetime.datetime]: """ 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, ...
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.astimezone() s = dt.strftime('%Y%m%d %H:%M:%S') ...
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...
def reqContractDetails(self, contract: Contract) -> List[ContractDetails]: """ 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 qu...
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...
def reqPnLSingle( self, account: str, modelCode: str, conId: int) -> PnLSingle: """ 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`. ...
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): """ 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`. ...
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, conId: int): """ Cancel PnLSingle subscription for the given account, modelCode and conId. Args: account: Cancel for this account name. modelCode: Cancel for this account model. conI...
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. """ import pandas as pd import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patc...
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...
def reqFundamentalData( self, contract: Contract, reportType: str, fundamentalDataOptions: List[TagValue] = None) -> str: """ Get fundamental data of a contract in XML format. This method is blocking. https://interactivebrokers.github.io/tws-api/fundamentals.htm...
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 bars. Args: bars: The bar list that was obtained from ``reqHistoricalData`` with a keepUpToDate subscription. """ self.client.cancelHistoricalDat...
Return values as a tuple.
def tuple(self): """ Return values as a tuple. """ return tuple(getattr(self, k) for k in self.__class__.defaults)
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: ExecutionFilter = None) -> List[Fill]: """ 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 spe...
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. ...
def reqHistogramData( self, contract: Contract, useRTH: bool, period: str) -> List[HistogramData]: """ Request histogram data. This method is blocking. https://interactivebrokers.github.io/tws-api/histograms.html Args: contract: Contract to ...
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, bytes)): return obj elif isinstance(obj, (datetime.date, datetime.time)): return obj...
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 and (v == v or d == d): # tests for NaN too nonDef...
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 container is a list by default. """ future = asyncio.Future() self._futures[key] = future self._results[ke...
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 popped of the general results. """ future = self._futures.pop(key, None) self._reqId2Contract.pop(key, None) ...
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 openOrder(self, orderId, contract, order, orderState): """ 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 cl...
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 orders have unset value execution.orderId = 0 key = se...
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() - self._startTime, self._n...
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() self.reset()
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 field in fields: typ = type(field) if field in...
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 method with the in-order message fields as parameters, skipping over the first ``skip`` fields, and parsed according to the ``types`` list. """ def handler(fields): ...
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 v = getattr(obj, k) if typ is int: ...
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: self.logger.exception(f'Error handling fields: ...
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 string like TradeConfirm, ChangeInDividendAccrual, Order, etc. """ cls = type(topic, (DynamicObject,), {}) results = [cls(**no...
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.SendRequest?' f't={token}&q={queryId}&v=3') ...
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. """ secType = kwargs.get('secType', '') cls = { '': Contract, 'STK': Stock, 'OPT': Option, ...
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 (midpoint); * close price. """ price = self.last if ( self.hasBidAsk() and self.bid <= self.last <= self.ask) else \...
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...
def add_keyword_from_file(self, keyword_file, encoding="utf-8"): """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: ke...
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"] ...
def add_keywords_from_dict(self, keyword_dict): """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"], ...
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"] ...
def remove_keywords_from_dict(self, keyword_dict): """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"], ...
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_list): """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_lis...
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_list(self, keyword_list): """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:...
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...
def get_all_keywords(self, term_so_far='', current_dict=None): """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 ...
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 ...
def extract_keywords(self, sentence, span_info=False): """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: ...
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 ...
def replace_keywords(self, sentence): """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_sente...
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...
def factor_information_coefficient(factor_data, group_adjust=False, by_group=False): """ Computes the Spearman Rank Correlation based Information Coefficient (IC) between factor values and N period forward returns for each period in t...
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 ...
def mean_information_coefficient(factor_data, group_adjust=False, by_group=False, by_time=None): """ Get the mean information coefficient of specified groups. Answers questions like: What is the mean IC fo...
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...
def factor_weights(factor_data, demeaned=True, group_adjust=False, equal_weight=False): """ Computes asset weights by factor values and dividing by the sum of their absolute value (achieving gross leverage of 1). Positive factor values will result...
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...
def factor_alpha_beta(factor_data, returns=None, demeaned=True, group_adjust=False, equal_weight=False): """ Compute the alpha (excess returns), alpha t-stat (alpha significance), and beta (market exposure) of a factor. ...
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...
def cumulative_returns(returns, period, freq=None): """ 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...
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 ...
def positions(weights, period, freq=None): """ 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...
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 ...
def mean_return_by_quantile(factor_data, by_date=False, by_group=False, demeaned=True, group_adjust=False): """ Computes mean returns for factor quantiles across provided forward returns columns. ...
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...
def compute_mean_returns_spread(mean_returns, upper_quant, lower_quant, std_err=None): """ Computes the difference between the mean returns of two quantiles. Optionally, computes the standard error of this di...
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 ...
def factor_rank_autocorrelation(factor_data, period=1): """ 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 ...
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...
def quantile_turnover(quantile_factor, quantile, period=1): """ 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 : i...
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...
def common_start_returns(factor, prices, before, after, cumulative=False, mean_by_date=False, demean_by=None): """ A date and equity pair is extracted from each i...
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...
def average_cumulative_return_by_quantile(factor_data, prices, periods_before=10, periods_after=15, demeaned=True, ...
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...
def factor_cumulative_returns(factor_data, period, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None): ...
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...
def factor_positions(factor_data, period, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None): """ Simulate a portfolio using the factor in input and r...
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...
def create_pyfolio_input(factor_data, period, capital=None, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None...
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 ...
def create_summary_tear_sheet(factor_data, long_short=True, group_neutral=False): """ Creates a small summary tear sheet with returns, information, and turnover analysis. Parameters ---------- factor_data : pd.DataFrame - MultiIndex ...
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...
def create_returns_tear_sheet(factor_data, long_short=True, group_neutral=False, by_group=False): """ Creates a tear sheet for returns analysis of a factor. Parameters ---------- factor_data : pd.DataFrame - M...
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...
def create_information_tear_sheet(factor_data, group_neutral=False, by_group=False): """ Creates a tear sheet for information analysis of a factor. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex ...
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...
def create_turnover_tear_sheet(factor_data, turnover_periods=None): """ 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), contain...
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...
def create_full_tear_sheet(factor_data, long_short=True, group_neutral=False, by_group=False): """ Creates a full tear sheet for analysis and evaluating single return predicting (alpha) factor. Parameters ---------- ...
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...
def create_event_returns_tear_sheet(factor_data, prices, avgretplot=(5, 15), long_short=True, group_neutral=False, std_bar=True, ...
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...
def create_event_study_tear_sheet(factor_data, prices=None, avgretplot=(5, 15), rate_of_ret=True, n_bars=50): """ Creates an event study tear sheet for analysis of a specific e...
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 scope without losing the stacktrace but adding an additional message. This is hacky because it has to be compatible with both python 2/3 """ e = exception m = additional_message if ...
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) """ message = """ An error occurred while computing bins/quantiles on the input provided. This usually happens when the inp...
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...
def quantize_factor(factor_data, quantiles=5, bins=None, by_group=False, no_raise=False, zero_aware=False): """ Computes period wise factor quantiles. Parameters ---------- factor_data : pd.DataFrame...
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 ------...
def infer_trading_calendar(factor_idx, prices_idx): """ 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 ...