repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
erdewit/ib_insync | ib_insync/util.py | startLoop | 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 kernel_handler():
kernel.do_one_iteration... | python | 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 kernel_handler():
kernel.do_one_iteration... | [
"def",
"startLoop",
"(",
")",
":",
"def",
"_ipython_loop_asyncio",
"(",
"kernel",
")",
":",
"'''\n Use asyncio event loop for the given IPython kernel.\n '''",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"def",
"kernel_handler",
"(",
")",
":",... | Use nested asyncio event loop for Jupyter notebooks. | [
"Use",
"nested",
"asyncio",
"event",
"loop",
"for",
"Jupyter",
"notebooks",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/util.py#L381-L409 | train |
erdewit/ib_insync | ib_insync/util.py | useQt | def useQt(qtLib: str = 'PyQt5', period: float = 0.01):
"""
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 qt_step():
loop.call_later(period, qt_step)
if not stack... | python | def useQt(qtLib: str = 'PyQt5', period: float = 0.01):
"""
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 qt_step():
loop.call_later(period, qt_step)
if not stack... | [
"def",
"useQt",
"(",
"qtLib",
":",
"str",
"=",
"'PyQt5'",
",",
"period",
":",
"float",
"=",
"0.01",
")",
":",
"def",
"qt_step",
"(",
")",
":",
"loop",
".",
"call_later",
"(",
"period",
",",
"qt_step",
")",
"if",
"not",
"stack",
":",
"qloop",
"=",
... | 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. | [
"Run",
"combined",
"Qt5",
"/",
"asyncio",
"event",
"loop",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/util.py#L412-L444 | train |
erdewit/ib_insync | ib_insync/util.py | formatIBDatetime | 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')
... | python | 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')
... | [
"def",
"formatIBDatetime",
"(",
"dt",
")",
"->",
"str",
":",
"if",
"not",
"dt",
":",
"s",
"=",
"''",
"elif",
"isinstance",
"(",
"dt",
",",
"datetime",
".",
"datetime",
")",
":",
"if",
"dt",
".",
"tzinfo",
":",
"# convert to local system timezone",
"dt",
... | Format date or datetime to string that IB uses. | [
"Format",
"date",
"or",
"datetime",
"to",
"string",
"that",
"IB",
"uses",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/util.py#L447-L462 | train |
erdewit/ib_insync | ib_insync/util.py | parseIBDatetime | 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(
... | python | 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(
... | [
"def",
"parseIBDatetime",
"(",
"s",
")",
":",
"if",
"len",
"(",
"s",
")",
"==",
"8",
":",
"# YYYYmmdd",
"y",
"=",
"int",
"(",
"s",
"[",
"0",
":",
"4",
"]",
")",
"m",
"=",
"int",
"(",
"s",
"[",
"4",
":",
"6",
"]",
")",
"d",
"=",
"int",
"... | Parse string in IB date or datetime format to datetime. | [
"Parse",
"string",
"in",
"IB",
"date",
"or",
"datetime",
"format",
"to",
"datetime",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/util.py#L465-L480 | train |
erdewit/ib_insync | ib_insync/objects.py | Object.tuple | def tuple(self):
"""
Return values as a tuple.
"""
return tuple(getattr(self, k) for k in self.__class__.defaults) | python | def tuple(self):
"""
Return values as a tuple.
"""
return tuple(getattr(self, k) for k in self.__class__.defaults) | [
"def",
"tuple",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"getattr",
"(",
"self",
",",
"k",
")",
"for",
"k",
"in",
"self",
".",
"__class__",
".",
"defaults",
")"
] | Return values as a tuple. | [
"Return",
"values",
"as",
"a",
"tuple",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/objects.py#L61-L65 | train |
erdewit/ib_insync | ib_insync/objects.py | Object.dict | def dict(self):
"""
Return key-value pairs as a dictionary.
"""
return {k: getattr(self, k) for k in self.__class__.defaults} | python | def dict(self):
"""
Return key-value pairs as a dictionary.
"""
return {k: getattr(self, k) for k in self.__class__.defaults} | [
"def",
"dict",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"getattr",
"(",
"self",
",",
"k",
")",
"for",
"k",
"in",
"self",
".",
"__class__",
".",
"defaults",
"}"
] | Return key-value pairs as a dictionary. | [
"Return",
"key",
"-",
"value",
"pairs",
"as",
"a",
"dictionary",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/objects.py#L67-L71 | train |
erdewit/ib_insync | ib_insync/objects.py | Object.diff | 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(other, k)
if left != right:
diff[k] = (left,... | python | 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(other, k)
if left != right:
diff[k] = (left,... | [
"def",
"diff",
"(",
"self",
",",
"other",
")",
":",
"diff",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"__class__",
".",
"defaults",
":",
"left",
"=",
"getattr",
"(",
"self",
",",
"k",
")",
"right",
"=",
"getattr",
"(",
"other",
",",
"k",
")... | Return differences between self and other as dictionary of 2-tuples. | [
"Return",
"differences",
"between",
"self",
"and",
"other",
"as",
"dictionary",
"of",
"2",
"-",
"tuples",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/objects.py#L81-L91 | train |
erdewit/ib_insync | ib_insync/objects.py | Object.nonDefaults | 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... | python | 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... | [
"def",
"nonDefaults",
"(",
"self",
")",
":",
"nonDefaults",
"=",
"{",
"}",
"for",
"k",
",",
"d",
"in",
"self",
".",
"__class__",
".",
"defaults",
".",
"items",
"(",
")",
":",
"v",
"=",
"getattr",
"(",
"self",
",",
"k",
")",
"if",
"v",
"!=",
"d"... | Get a dictionary of all attributes that differ from the default. | [
"Get",
"a",
"dictionary",
"of",
"all",
"attributes",
"that",
"differ",
"from",
"the",
"default",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/objects.py#L93-L102 | train |
erdewit/ib_insync | ib_insync/wrapper.py | Wrapper.startReq | 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... | python | 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... | [
"def",
"startReq",
"(",
"self",
",",
"key",
",",
"contract",
"=",
"None",
",",
"container",
"=",
"None",
")",
":",
"future",
"=",
"asyncio",
".",
"Future",
"(",
")",
"self",
".",
"_futures",
"[",
"key",
"]",
"=",
"future",
"self",
".",
"_results",
... | Start a new request and return the future that is associated
with with the key and container. The container is a list by default. | [
"Start",
"a",
"new",
"request",
"and",
"return",
"the",
"future",
"that",
"is",
"associated",
"with",
"with",
"the",
"key",
"and",
"container",
".",
"The",
"container",
"is",
"a",
"list",
"by",
"default",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/wrapper.py#L76-L86 | train |
erdewit/ib_insync | ib_insync/wrapper.py | Wrapper._endReq | 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)
... | python | 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)
... | [
"def",
"_endReq",
"(",
"self",
",",
"key",
",",
"result",
"=",
"None",
",",
"success",
"=",
"True",
")",
":",
"future",
"=",
"self",
".",
"_futures",
".",
"pop",
"(",
"key",
",",
"None",
")",
"self",
".",
"_reqId2Contract",
".",
"pop",
"(",
"key",
... | Finish the future of corresponding key with the given result.
If no result is given then it will be popped of the general results. | [
"Finish",
"the",
"future",
"of",
"corresponding",
"key",
"with",
"the",
"given",
"result",
".",
"If",
"no",
"result",
"is",
"given",
"then",
"it",
"will",
"be",
"popped",
"of",
"the",
"general",
"results",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/wrapper.py#L88-L102 | train |
erdewit/ib_insync | ib_insync/wrapper.py | Wrapper.startTicker | 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(contract))
if not ticker:
ticker = Ticker(
contract=contract, ticks=... | python | 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(contract))
if not ticker:
ticker = Ticker(
contract=contract, ticks=... | [
"def",
"startTicker",
"(",
"self",
",",
"reqId",
",",
"contract",
",",
"tickType",
")",
":",
"ticker",
"=",
"self",
".",
"tickers",
".",
"get",
"(",
"id",
"(",
"contract",
")",
")",
"if",
"not",
"ticker",
":",
"ticker",
"=",
"Ticker",
"(",
"contract"... | Start a tick request that has the reqId associated with the contract.
Return the ticker. | [
"Start",
"a",
"tick",
"request",
"that",
"has",
"the",
"reqId",
"associated",
"with",
"the",
"contract",
".",
"Return",
"the",
"ticker",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/wrapper.py#L104-L118 | train |
erdewit/ib_insync | ib_insync/wrapper.py | Wrapper.startSubscription | def startSubscription(self, reqId, subscriber, contract=None):
"""
Register a live subscription.
"""
self._reqId2Contract[reqId] = contract
self.reqId2Subscriber[reqId] = subscriber | python | def startSubscription(self, reqId, subscriber, contract=None):
"""
Register a live subscription.
"""
self._reqId2Contract[reqId] = contract
self.reqId2Subscriber[reqId] = subscriber | [
"def",
"startSubscription",
"(",
"self",
",",
"reqId",
",",
"subscriber",
",",
"contract",
"=",
"None",
")",
":",
"self",
".",
"_reqId2Contract",
"[",
"reqId",
"]",
"=",
"contract",
"self",
".",
"reqId2Subscriber",
"[",
"reqId",
"]",
"=",
"subscriber"
] | Register a live subscription. | [
"Register",
"a",
"live",
"subscription",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/wrapper.py#L125-L130 | train |
erdewit/ib_insync | ib_insync/wrapper.py | Wrapper.endSubscription | def endSubscription(self, subscriber):
"""
Unregister a live subscription.
"""
self._reqId2Contract.pop(subscriber.reqId, None)
self.reqId2Subscriber.pop(subscriber.reqId, None) | python | def endSubscription(self, subscriber):
"""
Unregister a live subscription.
"""
self._reqId2Contract.pop(subscriber.reqId, None)
self.reqId2Subscriber.pop(subscriber.reqId, None) | [
"def",
"endSubscription",
"(",
"self",
",",
"subscriber",
")",
":",
"self",
".",
"_reqId2Contract",
".",
"pop",
"(",
"subscriber",
".",
"reqId",
",",
"None",
")",
"self",
".",
"reqId2Subscriber",
".",
"pop",
"(",
"subscriber",
".",
"reqId",
",",
"None",
... | Unregister a live subscription. | [
"Unregister",
"a",
"live",
"subscription",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/wrapper.py#L132-L137 | train |
erdewit/ib_insync | ib_insync/wrapper.py | Wrapper.openOrder | 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... | python | 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... | [
"def",
"openOrder",
"(",
"self",
",",
"orderId",
",",
"contract",
",",
"order",
",",
"orderState",
")",
":",
"if",
"order",
".",
"whatIf",
":",
"# response to whatIfOrder",
"self",
".",
"_endReq",
"(",
"order",
".",
"orderId",
",",
"orderState",
")",
"else... | 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. | [
"This",
"wrapper",
"is",
"called",
"to",
":"
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/wrapper.py#L267-L299 | train |
erdewit/ib_insync | ib_insync/wrapper.py | Wrapper.execDetails | 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... | python | 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... | [
"def",
"execDetails",
"(",
"self",
",",
"reqId",
",",
"contract",
",",
"execution",
")",
":",
"if",
"execution",
".",
"orderId",
"==",
"UNSET_INTEGER",
":",
"# bug in TWS: executions of manual orders have unset value",
"execution",
".",
"orderId",
"=",
"0",
"key",
... | This wrapper handles both live fills and responses to reqExecutions. | [
"This",
"wrapper",
"handles",
"both",
"live",
"fills",
"and",
"responses",
"to",
"reqExecutions",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/wrapper.py#L347-L382 | train |
erdewit/ib_insync | ib_insync/client.py | Client.connectionStats | 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... | python | 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... | [
"def",
"connectionStats",
"(",
"self",
")",
"->",
"ConnectionStats",
":",
"if",
"not",
"self",
".",
"isReady",
"(",
")",
":",
"raise",
"ConnectionError",
"(",
"'Not connected'",
")",
"return",
"ConnectionStats",
"(",
"self",
".",
"_startTime",
",",
"time",
"... | Get statistics about the connection. | [
"Get",
"statistics",
"about",
"the",
"connection",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/client.py#L137-L147 | train |
erdewit/ib_insync | ib_insync/client.py | Client.getReqId | def getReqId(self) -> int:
"""
Get new request ID.
"""
if not self.isReady():
raise ConnectionError('Not connected')
newId = self._reqIdSeq
self._reqIdSeq += 1
return newId | python | def getReqId(self) -> int:
"""
Get new request ID.
"""
if not self.isReady():
raise ConnectionError('Not connected')
newId = self._reqIdSeq
self._reqIdSeq += 1
return newId | [
"def",
"getReqId",
"(",
"self",
")",
"->",
"int",
":",
"if",
"not",
"self",
".",
"isReady",
"(",
")",
":",
"raise",
"ConnectionError",
"(",
"'Not connected'",
")",
"newId",
"=",
"self",
".",
"_reqIdSeq",
"self",
".",
"_reqIdSeq",
"+=",
"1",
"return",
"... | Get new request ID. | [
"Get",
"new",
"request",
"ID",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/client.py#L149-L157 | train |
erdewit/ib_insync | ib_insync/client.py | Client.disconnect | 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() | python | 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() | [
"def",
"disconnect",
"(",
"self",
")",
":",
"self",
".",
"connState",
"=",
"Client",
".",
"DISCONNECTED",
"if",
"self",
".",
"conn",
"is",
"not",
"None",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Disconnecting'",
")",
"self",
".",
"conn",
".",
... | Disconnect from IB connection. | [
"Disconnect",
"from",
"IB",
"connection",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/client.py#L222-L231 | train |
erdewit/ib_insync | ib_insync/client.py | Client.send | 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... | python | 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... | [
"def",
"send",
"(",
"self",
",",
"*",
"fields",
")",
":",
"if",
"not",
"self",
".",
"isConnected",
"(",
")",
":",
"raise",
"ConnectionError",
"(",
"'Not connected'",
")",
"msg",
"=",
"io",
".",
"StringIO",
"(",
")",
"for",
"field",
"in",
"fields",
":... | Serialize and send the given fields using the IB socket protocol. | [
"Serialize",
"and",
"send",
"the",
"given",
"fields",
"using",
"the",
"IB",
"socket",
"protocol",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/client.py#L233-L264 | train |
erdewit/ib_insync | ib_insync/decoder.py | Decoder.wrap | 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):
... | python | 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):
... | [
"def",
"wrap",
"(",
"self",
",",
"methodName",
",",
"types",
",",
"skip",
"=",
"2",
")",
":",
"def",
"handler",
"(",
"fields",
")",
":",
"try",
":",
"args",
"=",
"[",
"field",
"if",
"typ",
"is",
"str",
"else",
"int",
"(",
"field",
"or",
"0",
")... | 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. | [
"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",
"ty... | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/decoder.py#L159-L179 | train |
erdewit/ib_insync | ib_insync/decoder.py | Decoder.interpret | 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: ... | python | 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: ... | [
"def",
"interpret",
"(",
"self",
",",
"fields",
")",
":",
"try",
":",
"msgId",
"=",
"int",
"(",
"fields",
"[",
"0",
"]",
")",
"handler",
"=",
"self",
".",
"handlers",
"[",
"msgId",
"]",
"handler",
"(",
"fields",
")",
"except",
"Exception",
":",
"se... | Decode fields and invoke corresponding wrapper method. | [
"Decode",
"fields",
"and",
"invoke",
"corresponding",
"wrapper",
"method",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/decoder.py#L181-L190 | train |
erdewit/ib_insync | ib_insync/decoder.py | Decoder.parse | 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:
... | python | 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:
... | [
"def",
"parse",
"(",
"self",
",",
"obj",
")",
":",
"for",
"k",
",",
"default",
"in",
"obj",
".",
"__class__",
".",
"defaults",
".",
"items",
"(",
")",
":",
"typ",
"=",
"type",
"(",
"default",
")",
"if",
"typ",
"is",
"str",
":",
"continue",
"v",
... | Parse the object's properties according to its default types. | [
"Parse",
"the",
"object",
"s",
"properties",
"according",
"to",
"its",
"default",
"types",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/decoder.py#L192-L206 | train |
erdewit/ib_insync | ib_insync/flexreport.py | FlexReport.topics | 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) | python | 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) | [
"def",
"topics",
"(",
"self",
")",
":",
"return",
"set",
"(",
"node",
".",
"tag",
"for",
"node",
"in",
"self",
".",
"root",
".",
"iter",
"(",
")",
"if",
"node",
".",
"attrib",
")"
] | Get the set of topics that can be extracted from this report. | [
"Get",
"the",
"set",
"of",
"topics",
"that",
"can",
"be",
"extracted",
"from",
"this",
"report",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/flexreport.py#L49-L53 | train |
erdewit/ib_insync | ib_insync/flexreport.py | FlexReport.extract | 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... | python | 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... | [
"def",
"extract",
"(",
"self",
",",
"topic",
":",
"str",
",",
"parseNumbers",
"=",
"True",
")",
"->",
"list",
":",
"cls",
"=",
"type",
"(",
"topic",
",",
"(",
"DynamicObject",
",",
")",
",",
"{",
"}",
")",
"results",
"=",
"[",
"cls",
"(",
"*",
... | Extract items of given topic and return as list of objects.
The topic is a string like TradeConfirm, ChangeInDividendAccrual,
Order, etc. | [
"Extract",
"items",
"of",
"given",
"topic",
"and",
"return",
"as",
"list",
"of",
"objects",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/flexreport.py#L55-L71 | train |
erdewit/ib_insync | ib_insync/flexreport.py | FlexReport.df | 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)) | python | 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)) | [
"def",
"df",
"(",
"self",
",",
"topic",
":",
"str",
",",
"parseNumbers",
"=",
"True",
")",
":",
"return",
"util",
".",
"df",
"(",
"self",
".",
"extract",
"(",
"topic",
",",
"parseNumbers",
")",
")"
] | Same as extract but return the result as a pandas DataFrame. | [
"Same",
"as",
"extract",
"but",
"return",
"the",
"result",
"as",
"a",
"pandas",
"DataFrame",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/flexreport.py#L73-L77 | train |
erdewit/ib_insync | ib_insync/flexreport.py | FlexReport.download | 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')
... | python | 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')
... | [
"def",
"download",
"(",
"self",
",",
"token",
",",
"queryId",
")",
":",
"url",
"=",
"(",
"'https://gdcdyn.interactivebrokers.com'",
"f'/Universal/servlet/FlexStatementService.SendRequest?'",
"f't={token}&q={queryId}&v=3'",
")",
"resp",
"=",
"urlopen",
"(",
"url",
")",
"... | Download report for the given ``token`` and ``queryId``. | [
"Download",
"report",
"for",
"the",
"given",
"token",
"and",
"queryId",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/flexreport.py#L79-L114 | train |
erdewit/ib_insync | ib_insync/flexreport.py | FlexReport.load | 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) | python | 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) | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"self",
".",
"data",
"=",
"f",
".",
"read",
"(",
")",
"self",
".",
"root",
"=",
"et",
".",
"fromstring",
"(",
"self",
".",
"data... | Load report from XML file. | [
"Load",
"report",
"from",
"XML",
"file",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/flexreport.py#L116-L122 | train |
erdewit/ib_insync | ib_insync/flexreport.py | FlexReport.save | def save(self, path):
"""
Save report to XML file.
"""
with open(path, 'wb') as f:
f.write(self.data) | python | def save(self, path):
"""
Save report to XML file.
"""
with open(path, 'wb') as f:
f.write(self.data) | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"data",
")"
] | Save report to XML file. | [
"Save",
"report",
"to",
"XML",
"file",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/flexreport.py#L124-L129 | train |
erdewit/ib_insync | ib_insync/contract.py | Contract.create | 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,
... | python | 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,
... | [
"def",
"create",
"(",
"*",
"*",
"kwargs",
")",
":",
"secType",
"=",
"kwargs",
".",
"get",
"(",
"'secType'",
",",
"''",
")",
"cls",
"=",
"{",
"''",
":",
"Contract",
",",
"'STK'",
":",
"Stock",
",",
"'OPT'",
":",
"Option",
",",
"'FUT'",
":",
"Futur... | Create and a return a specialized contract based on the given secType,
or a general Contract if secType is not given. | [
"Create",
"and",
"a",
"return",
"a",
"specialized",
"contract",
"based",
"on",
"the",
"given",
"secType",
"or",
"a",
"general",
"Contract",
"if",
"secType",
"is",
"not",
"given",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/contract.py#L102-L128 | train |
erdewit/ib_insync | ib_insync/ticker.py | Ticker.hasBidAsk | 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) | python | 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) | [
"def",
"hasBidAsk",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"(",
"self",
".",
"bid",
"!=",
"-",
"1",
"and",
"not",
"isNan",
"(",
"self",
".",
"bid",
")",
"and",
"self",
".",
"bidSize",
">",
"0",
"and",
"self",
".",
"ask",
"!=",
"-",
"1",... | See if this ticker has a valid bid and ask. | [
"See",
"if",
"this",
"ticker",
"has",
"a",
"valid",
"bid",
"and",
"ask",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/ticker.py#L107-L113 | train |
erdewit/ib_insync | ib_insync/ticker.py | Ticker.midpoint | 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 | python | 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 | [
"def",
"midpoint",
"(",
"self",
")",
"->",
"float",
":",
"return",
"(",
"self",
".",
"bid",
"+",
"self",
".",
"ask",
")",
"/",
"2",
"if",
"self",
".",
"hasBidAsk",
"(",
")",
"else",
"nan"
] | Return average of bid and ask, or NaN if no valid bid and ask
are available. | [
"Return",
"average",
"of",
"bid",
"and",
"ask",
"or",
"NaN",
"if",
"no",
"valid",
"bid",
"and",
"ask",
"are",
"available",
"."
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/ticker.py#L115-L120 | train |
erdewit/ib_insync | ib_insync/ticker.py | Ticker.marketPrice | 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 \... | python | 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 \... | [
"def",
"marketPrice",
"(",
"self",
")",
"->",
"float",
":",
"price",
"=",
"self",
".",
"last",
"if",
"(",
"self",
".",
"hasBidAsk",
"(",
")",
"and",
"self",
".",
"bid",
"<=",
"self",
".",
"last",
"<=",
"self",
".",
"ask",
")",
"else",
"self",
"."... | Return the first available one of
* last price if within current bid/ask;
* average of bid and ask (midpoint);
* close price. | [
"Return",
"the",
"first",
"available",
"one",
"of"
] | d0646a482590f5cb7bfddbd1f0870f8c4bc1df80 | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/ticker.py#L122-L135 | train |
vi3k6i5/flashtext | flashtext/keyword.py | KeywordProcessor.add_keyword_from_file | 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... | python | 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... | [
"def",
"add_keyword_from_file",
"(",
"self",
",",
"keyword_file",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"keyword_file",
")",
":",
"raise",
"IOError",
"(",
"\"Invalid file path {}\"",
".",
"format",
"... | 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",
"file"
] | 50c45f1f4a394572381249681046f57e2bf5a591 | https://github.com/vi3k6i5/flashtext/blob/50c45f1f4a394572381249681046f57e2bf5a591/flashtext/keyword.py#L291-L327 | train |
vi3k6i5/flashtext | flashtext/keyword.py | KeywordProcessor.add_keywords_from_dict | 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"],
... | python | 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"],
... | [
"def",
"add_keywords_from_dict",
"(",
"self",
",",
"keyword_dict",
")",
":",
"for",
"clean_name",
",",
"keywords",
"in",
"keyword_dict",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"keywords",
",",
"list",
")",
":",
"raise",
"AttributeError"... | 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",
"add",
"keywords",
"from",
"a",
"dictionary"
] | 50c45f1f4a394572381249681046f57e2bf5a591 | https://github.com/vi3k6i5/flashtext/blob/50c45f1f4a394572381249681046f57e2bf5a591/flashtext/keyword.py#L329-L351 | train |
vi3k6i5/flashtext | flashtext/keyword.py | KeywordProcessor.remove_keywords_from_dict | 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"],
... | python | 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"],
... | [
"def",
"remove_keywords_from_dict",
"(",
"self",
",",
"keyword_dict",
")",
":",
"for",
"clean_name",
",",
"keywords",
"in",
"keyword_dict",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"keywords",
",",
"list",
")",
":",
"raise",
"AttributeErr... | 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",
"remove",
"keywords",
"from",
"a",
"dictionary"
] | 50c45f1f4a394572381249681046f57e2bf5a591 | https://github.com/vi3k6i5/flashtext/blob/50c45f1f4a394572381249681046f57e2bf5a591/flashtext/keyword.py#L353-L375 | train |
vi3k6i5/flashtext | flashtext/keyword.py | KeywordProcessor.add_keywords_from_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... | python | 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... | [
"def",
"add_keywords_from_list",
"(",
"self",
",",
"keyword_list",
")",
":",
"if",
"not",
"isinstance",
"(",
"keyword_list",
",",
"list",
")",
":",
"raise",
"AttributeError",
"(",
"\"keyword_list should be a list\"",
")",
"for",
"keyword",
"in",
"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_list` is not a list. | [
"To",
"add",
"keywords",
"from",
"a",
"list"
] | 50c45f1f4a394572381249681046f57e2bf5a591 | https://github.com/vi3k6i5/flashtext/blob/50c45f1f4a394572381249681046f57e2bf5a591/flashtext/keyword.py#L377-L393 | train |
vi3k6i5/flashtext | flashtext/keyword.py | KeywordProcessor.remove_keywords_from_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:... | python | 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:... | [
"def",
"remove_keywords_from_list",
"(",
"self",
",",
"keyword_list",
")",
":",
"if",
"not",
"isinstance",
"(",
"keyword_list",
",",
"list",
")",
":",
"raise",
"AttributeError",
"(",
"\"keyword_list should be a list\"",
")",
"for",
"keyword",
"in",
"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: If `keyword_list` is not a list. | [
"To",
"remove",
"keywords",
"present",
"in",
"list"
] | 50c45f1f4a394572381249681046f57e2bf5a591 | https://github.com/vi3k6i5/flashtext/blob/50c45f1f4a394572381249681046f57e2bf5a591/flashtext/keyword.py#L395-L411 | train |
vi3k6i5/flashtext | flashtext/keyword.py | KeywordProcessor.get_all_keywords | 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
... | python | 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
... | [
"def",
"get_all_keywords",
"(",
"self",
",",
"term_so_far",
"=",
"''",
",",
"current_dict",
"=",
"None",
")",
":",
"terms_present",
"=",
"{",
"}",
"if",
"not",
"term_so_far",
":",
"term_so_far",
"=",
"''",
"if",
"current_dict",
"is",
"None",
":",
"current_... | 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... | [
"Recursively",
"builds",
"a",
"dictionary",
"of",
"keywords",
"present",
"in",
"the",
"dictionary",
"And",
"the",
"clean",
"name",
"mapped",
"to",
"those",
"keywords",
"."
] | 50c45f1f4a394572381249681046f57e2bf5a591 | https://github.com/vi3k6i5/flashtext/blob/50c45f1f4a394572381249681046f57e2bf5a591/flashtext/keyword.py#L413-L448 | train |
vi3k6i5/flashtext | flashtext/keyword.py | KeywordProcessor.extract_keywords | 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:
... | python | 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:
... | [
"def",
"extract_keywords",
"(",
"self",
",",
"sentence",
",",
"span_info",
"=",
"False",
")",
":",
"keywords_extracted",
"=",
"[",
"]",
"if",
"not",
"sentence",
":",
"# if sentence is empty or none just return empty list",
"return",
"keywords_extracted",
"if",
"not",
... | 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",
"added",
"to",
"a",
"list",
"keywords_extracted",
"and",
"returned",
"."
] | 50c45f1f4a394572381249681046f57e2bf5a591 | https://github.com/vi3k6i5/flashtext/blob/50c45f1f4a394572381249681046f57e2bf5a591/flashtext/keyword.py#L450-L558 | train |
vi3k6i5/flashtext | flashtext/keyword.py | KeywordProcessor.replace_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... | python | 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... | [
"def",
"replace_keywords",
"(",
"self",
",",
"sentence",
")",
":",
"if",
"not",
"sentence",
":",
"# if sentence is empty or none just return the same.",
"return",
"sentence",
"new_sentence",
"=",
"[",
"]",
"orig_sentence",
"=",
"sentence",
"if",
"not",
"self",
".",
... | 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
... | [
"Searches",
"in",
"the",
"string",
"for",
"all",
"keywords",
"present",
"in",
"corpus",
".",
"Keywords",
"present",
"are",
"replaced",
"by",
"the",
"clean",
"name",
"and",
"a",
"new",
"string",
"is",
"returned",
"."
] | 50c45f1f4a394572381249681046f57e2bf5a591 | https://github.com/vi3k6i5/flashtext/blob/50c45f1f4a394572381249681046f57e2bf5a591/flashtext/keyword.py#L560-L681 | train |
quantopian/alphalens | alphalens/performance.py | factor_information_coefficient | 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... | python | 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... | [
"def",
"factor_information_coefficient",
"(",
"factor_data",
",",
"group_adjust",
"=",
"False",
",",
"by_group",
"=",
"False",
")",
":",
"def",
"src_ic",
"(",
"group",
")",
":",
"f",
"=",
"group",
"[",
"'factor'",
"]",
"_ic",
"=",
"group",
"[",
"utils",
... | 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... | [
"Computes",
"the",
"Spearman",
"Rank",
"Correlation",
"based",
"Information",
"Coefficient",
"(",
"IC",
")",
"between",
"factor",
"values",
"and",
"N",
"period",
"forward",
"returns",
"for",
"each",
"period",
"in",
"the",
"factor",
"index",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L27-L73 | train |
quantopian/alphalens | alphalens/performance.py | mean_information_coefficient | 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... | python | 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... | [
"def",
"mean_information_coefficient",
"(",
"factor_data",
",",
"group_adjust",
"=",
"False",
",",
"by_group",
"=",
"False",
",",
"by_time",
"=",
"None",
")",
":",
"ic",
"=",
"factor_information_coefficient",
"(",
"factor_data",
",",
"group_adjust",
",",
"by_group... | 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
... | [
"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",
... | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L76-L125 | train |
quantopian/alphalens | alphalens/performance.py | factor_weights | 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... | python | 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... | [
"def",
"factor_weights",
"(",
"factor_data",
",",
"demeaned",
"=",
"True",
",",
"group_adjust",
"=",
"False",
",",
"equal_weight",
"=",
"False",
")",
":",
"def",
"to_weights",
"(",
"group",
",",
"_demeaned",
",",
"_equal_weight",
")",
":",
"if",
"_equal_weig... | 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",
"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",
"positiv... | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L128-L204 | train |
quantopian/alphalens | alphalens/performance.py | factor_returns | def factor_returns(factor_data,
demeaned=True,
group_adjust=False,
equal_weight=False,
by_asset=False):
"""
Computes period wise returns for portfolio weighted by factor
values.
Parameters
----------
factor_data : pd.Da... | python | def factor_returns(factor_data,
demeaned=True,
group_adjust=False,
equal_weight=False,
by_asset=False):
"""
Computes period wise returns for portfolio weighted by factor
values.
Parameters
----------
factor_data : pd.Da... | [
"def",
"factor_returns",
"(",
"factor_data",
",",
"demeaned",
"=",
"True",
",",
"group_adjust",
"=",
"False",
",",
"equal_weight",
"=",
"False",
",",
"by_asset",
"=",
"False",
")",
":",
"weights",
"=",
"factor_weights",
"(",
"factor_data",
",",
"demeaned",
"... | 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... | [
"Computes",
"period",
"wise",
"returns",
"for",
"portfolio",
"weighted",
"by",
"factor",
"values",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L207-L254 | train |
quantopian/alphalens | alphalens/performance.py | factor_alpha_beta | 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. ... | python | 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. ... | [
"def",
"factor_alpha_beta",
"(",
"factor_data",
",",
"returns",
"=",
"None",
",",
"demeaned",
"=",
"True",
",",
"group_adjust",
"=",
"False",
",",
"equal_weight",
"=",
"False",
")",
":",
"if",
"returns",
"is",
"None",
":",
"returns",
"=",
"factor_returns",
... | 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... | [
"Compute",
"the",
"alpha",
"(",
"excess",
"returns",
")",
"alpha",
"t",
"-",
"stat",
"(",
"alpha",
"significance",
")",
"and",
"beta",
"(",
"market",
"exposure",
")",
"of",
"a",
"factor",
".",
"A",
"regression",
"is",
"run",
"with",
"the",
"period",
"w... | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L257-L329 | train |
quantopian/alphalens | alphalens/performance.py | cumulative_returns | 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... | python | 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... | [
"def",
"cumulative_returns",
"(",
"returns",
",",
"period",
",",
"freq",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"period",
",",
"pd",
".",
"Timedelta",
")",
":",
"period",
"=",
"pd",
".",
"Timedelta",
"(",
"period",
")",
"if",
"freq",
... | 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",
"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",
"... | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L332-L494 | train |
quantopian/alphalens | alphalens/performance.py | positions | 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... | python | 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... | [
"def",
"positions",
"(",
"weights",
",",
"period",
",",
"freq",
"=",
"None",
")",
":",
"weights",
"=",
"weights",
".",
"unstack",
"(",
")",
"if",
"not",
"isinstance",
"(",
"period",
",",
"pd",
".",
"Timedelta",
")",
":",
"period",
"=",
"pd",
".",
"... | 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
... | [
"Builds",
"net",
"position",
"values",
"time",
"series",
"the",
"portfolio",
"percentage",
"invested",
"in",
"each",
"position",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L497-L592 | train |
quantopian/alphalens | alphalens/performance.py | mean_return_by_quantile | 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.
... | python | 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.
... | [
"def",
"mean_return_by_quantile",
"(",
"factor_data",
",",
"by_date",
"=",
"False",
",",
"by_group",
"=",
"False",
",",
"demeaned",
"=",
"True",
",",
"group_adjust",
"=",
"False",
")",
":",
"if",
"group_adjust",
":",
"grouper",
"=",
"[",
"factor_data",
".",
... | 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",
"mean",
"returns",
"for",
"factor",
"quantiles",
"across",
"provided",
"forward",
"returns",
"columns",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L595-L659 | train |
quantopian/alphalens | alphalens/performance.py | compute_mean_returns_spread | 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... | python | 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... | [
"def",
"compute_mean_returns_spread",
"(",
"mean_returns",
",",
"upper_quant",
",",
"lower_quant",
",",
"std_err",
"=",
"None",
")",
":",
"mean_return_difference",
"=",
"mean_returns",
".",
"xs",
"(",
"upper_quant",
",",
"level",
"=",
"'factor_quantile'",
")",
"-"... | 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",
"difference",
"between",
"the",
"mean",
"returns",
"of",
"two",
"quantiles",
".",
"Optionally",
"computes",
"the",
"standard",
"error",
"of",
"this",
"difference",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L662-L707 | train |
quantopian/alphalens | alphalens/performance.py | quantile_turnover | 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... | python | 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... | [
"def",
"quantile_turnover",
"(",
"quantile_factor",
",",
"quantile",
",",
"period",
"=",
"1",
")",
":",
"quant_names",
"=",
"quantile_factor",
"[",
"quantile_factor",
"==",
"quantile",
"]",
"quant_name_sets",
"=",
"quant_names",
".",
"groupby",
"(",
"level",
"="... | 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",
"the",
"proportion",
"of",
"names",
"in",
"a",
"factor",
"quantile",
"that",
"were",
"not",
"in",
"that",
"quantile",
"in",
"the",
"previous",
"period",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L710-L748 | train |
quantopian/alphalens | alphalens/performance.py | factor_rank_autocorrelation | 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 ... | python | 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 ... | [
"def",
"factor_rank_autocorrelation",
"(",
"factor_data",
",",
"period",
"=",
"1",
")",
":",
"grouper",
"=",
"[",
"factor_data",
".",
"index",
".",
"get_level_values",
"(",
"'date'",
")",
"]",
"ranks",
"=",
"factor_data",
".",
"groupby",
"(",
"grouper",
")",... | 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 ... | [
"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",
... | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L751-L799 | train |
quantopian/alphalens | alphalens/performance.py | common_start_returns | 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... | python | 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... | [
"def",
"common_start_returns",
"(",
"factor",
",",
"prices",
",",
"before",
",",
"after",
",",
"cumulative",
"=",
"False",
",",
"mean_by_date",
"=",
"False",
",",
"demean_by",
"=",
"None",
")",
":",
"if",
"cumulative",
":",
"returns",
"=",
"prices",
"else"... | 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... | [
"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",
... | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L802-L892 | train |
quantopian/alphalens | alphalens/performance.py | average_cumulative_return_by_quantile | def average_cumulative_return_by_quantile(factor_data,
prices,
periods_before=10,
periods_after=15,
demeaned=True,
... | python | def average_cumulative_return_by_quantile(factor_data,
prices,
periods_before=10,
periods_after=15,
demeaned=True,
... | [
"def",
"average_cumulative_return_by_quantile",
"(",
"factor_data",
",",
"prices",
",",
"periods_before",
"=",
"10",
",",
"periods_after",
"=",
"15",
",",
"demeaned",
"=",
"True",
",",
"group_adjust",
"=",
"False",
",",
"by_group",
"=",
"False",
")",
":",
"def... | 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... | [
"Plots",
"average",
"cumulative",
"returns",
"by",
"factor",
"quantiles",
"in",
"the",
"period",
"range",
"defined",
"by",
"-",
"periods_before",
"to",
"periods_after"
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L895-L1018 | train |
quantopian/alphalens | alphalens/performance.py | factor_cumulative_returns | def factor_cumulative_returns(factor_data,
period,
long_short=True,
group_neutral=False,
equal_weight=False,
quantiles=None,
groups=None):
... | python | def factor_cumulative_returns(factor_data,
period,
long_short=True,
group_neutral=False,
equal_weight=False,
quantiles=None,
groups=None):
... | [
"def",
"factor_cumulative_returns",
"(",
"factor_data",
",",
"period",
",",
"long_short",
"=",
"True",
",",
"group_neutral",
"=",
"False",
",",
"equal_weight",
"=",
"False",
",",
"quantiles",
"=",
"None",
",",
"groups",
"=",
"None",
")",
":",
"fwd_ret_cols",
... | 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",
"cumulative",
"returns",
"of",
"the",
"simulated",
"portfolio"
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L1021-L1088 | train |
quantopian/alphalens | alphalens/performance.py | factor_positions | 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... | python | 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... | [
"def",
"factor_positions",
"(",
"factor_data",
",",
"period",
",",
"long_short",
"=",
"True",
",",
"group_neutral",
"=",
"False",
",",
"equal_weight",
"=",
"False",
",",
"quantiles",
"=",
"None",
",",
"groups",
"=",
"None",
")",
":",
"fwd_ret_cols",
"=",
"... | 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",
"factor",
"in",
"input",
"and",
"returns",
"the",
"assets",
"positions",
"as",
"percentage",
"of",
"the",
"total",
"portfolio",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L1091-L1160 | train |
quantopian/alphalens | alphalens/performance.py | create_pyfolio_input | def create_pyfolio_input(factor_data,
period,
capital=None,
long_short=True,
group_neutral=False,
equal_weight=False,
quantiles=None,
groups=None... | python | def create_pyfolio_input(factor_data,
period,
capital=None,
long_short=True,
group_neutral=False,
equal_weight=False,
quantiles=None,
groups=None... | [
"def",
"create_pyfolio_input",
"(",
"factor_data",
",",
"period",
",",
"capital",
"=",
"None",
",",
"long_short",
"=",
"True",
",",
"group_neutral",
"=",
"False",
",",
"equal_weight",
"=",
"False",
",",
"quantiles",
"=",
"None",
",",
"groups",
"=",
"None",
... | 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... | [
"Simulate",
"a",
"portfolio",
"using",
"the",
"input",
"factor",
"and",
"returns",
"the",
"portfolio",
"performance",
"data",
"properly",
"formatted",
"for",
"Pyfolio",
"analysis",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/performance.py#L1163-L1320 | train |
quantopian/alphalens | alphalens/tears.py | create_summary_tear_sheet | 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
... | python | 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
... | [
"def",
"create_summary_tear_sheet",
"(",
"factor_data",
",",
"long_short",
"=",
"True",
",",
"group_neutral",
"=",
"False",
")",
":",
"# Returns Analysis",
"mean_quant_ret",
",",
"std_quantile",
"=",
"perf",
".",
"mean_return_by_quantile",
"(",
"factor_data",
",",
"... | 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",
"small",
"summary",
"tear",
"sheet",
"with",
"returns",
"information",
"and",
"turnover",
"analysis",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/tears.py#L63-L162 | train |
quantopian/alphalens | alphalens/tears.py | create_returns_tear_sheet | 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... | python | 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... | [
"def",
"create_returns_tear_sheet",
"(",
"factor_data",
",",
"long_short",
"=",
"True",
",",
"group_neutral",
"=",
"False",
",",
"by_group",
"=",
"False",
")",
":",
"factor_returns",
"=",
"perf",
".",
"factor_returns",
"(",
"factor_data",
",",
"long_short",
",",... | 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",
"returns",
"analysis",
"of",
"a",
"factor",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/tears.py#L166-L321 | train |
quantopian/alphalens | alphalens/tears.py | create_information_tear_sheet | 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 ... | python | 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 ... | [
"def",
"create_information_tear_sheet",
"(",
"factor_data",
",",
"group_neutral",
"=",
"False",
",",
"by_group",
"=",
"False",
")",
":",
"ic",
"=",
"perf",
".",
"factor_information_coefficient",
"(",
"factor_data",
",",
"group_neutral",
")",
"plotting",
".",
"plot... | 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",
"information",
"analysis",
"of",
"a",
"factor",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/tears.py#L325-L382 | train |
quantopian/alphalens | alphalens/tears.py | create_turnover_tear_sheet | 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... | python | 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... | [
"def",
"create_turnover_tear_sheet",
"(",
"factor_data",
",",
"turnover_periods",
"=",
"None",
")",
":",
"if",
"turnover_periods",
"is",
"None",
":",
"turnover_periods",
"=",
"utils",
".",
"get_forward_returns_columns",
"(",
"factor_data",
".",
"columns",
")",
"quan... | 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",
"tear",
"sheet",
"for",
"analyzing",
"the",
"turnover",
"properties",
"of",
"a",
"factor",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/tears.py#L386-L446 | train |
quantopian/alphalens | alphalens/tears.py | create_full_tear_sheet | 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
----------
... | python | 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
----------
... | [
"def",
"create_full_tear_sheet",
"(",
"factor_data",
",",
"long_short",
"=",
"True",
",",
"group_neutral",
"=",
"False",
",",
"by_group",
"=",
"False",
")",
":",
"plotting",
".",
"plot_quantile_statistics_table",
"(",
"factor_data",
")",
"create_returns_tear_sheet",
... | 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",
"full",
"tear",
"sheet",
"for",
"analysis",
"and",
"evaluating",
"single",
"return",
"predicting",
"(",
"alpha",
")",
"factor",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/tears.py#L450-L490 | train |
quantopian/alphalens | alphalens/tears.py | create_event_returns_tear_sheet | def create_event_returns_tear_sheet(factor_data,
prices,
avgretplot=(5, 15),
long_short=True,
group_neutral=False,
std_bar=True,
... | python | def create_event_returns_tear_sheet(factor_data,
prices,
avgretplot=(5, 15),
long_short=True,
group_neutral=False,
std_bar=True,
... | [
"def",
"create_event_returns_tear_sheet",
"(",
"factor_data",
",",
"prices",
",",
"avgretplot",
"=",
"(",
"5",
",",
"15",
")",
",",
"long_short",
"=",
"True",
",",
"group_neutral",
"=",
"False",
",",
"std_bar",
"=",
"True",
",",
"by_group",
"=",
"False",
"... | 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",
"a",
"tear",
"sheet",
"to",
"view",
"the",
"average",
"cumulative",
"returns",
"for",
"a",
"factor",
"within",
"a",
"window",
"(",
"pre",
"and",
"post",
"event",
")",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/tears.py#L494-L591 | train |
quantopian/alphalens | alphalens/tears.py | create_event_study_tear_sheet | 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... | python | 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... | [
"def",
"create_event_study_tear_sheet",
"(",
"factor_data",
",",
"prices",
"=",
"None",
",",
"avgretplot",
"=",
"(",
"5",
",",
"15",
")",
",",
"rate_of_ret",
"=",
"True",
",",
"n_bars",
"=",
"50",
")",
":",
"long_short",
"=",
"False",
"plotting",
".",
"p... | 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... | [
"Creates",
"an",
"event",
"study",
"tear",
"sheet",
"for",
"analysis",
"of",
"a",
"specific",
"event",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/tears.py#L595-L701 | train |
quantopian/alphalens | alphalens/utils.py | rethrow | 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 ... | python | 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 ... | [
"def",
"rethrow",
"(",
"exception",
",",
"additional_message",
")",
":",
"e",
"=",
"exception",
"m",
"=",
"additional_message",
"if",
"not",
"e",
".",
"args",
":",
"e",
".",
"args",
"=",
"(",
"m",
",",
")",
"else",
":",
"e",
".",
"args",
"=",
"(",
... | 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 | [
"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",
"b... | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L33-L45 | train |
quantopian/alphalens | alphalens/utils.py | non_unique_bin_edges_error | 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... | python | 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... | [
"def",
"non_unique_bin_edges_error",
"(",
"func",
")",
":",
"message",
"=",
"\"\"\"\n\n An error occurred while computing bins/quantiles on the input provided.\n This usually happens when the input contains too many identical\n values and they span more than one quantile. The quantiles are ... | Give user a more informative error in case it is not possible
to properly calculate quantiles on the input dataframe (factor) | [
"Give",
"user",
"a",
"more",
"informative",
"error",
"in",
"case",
"it",
"is",
"not",
"possible",
"to",
"properly",
"calculate",
"quantiles",
"on",
"the",
"input",
"dataframe",
"(",
"factor",
")"
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L48-L80 | train |
quantopian/alphalens | alphalens/utils.py | quantize_factor | 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... | python | 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... | [
"def",
"quantize_factor",
"(",
"factor_data",
",",
"quantiles",
"=",
"5",
",",
"bins",
"=",
"None",
",",
"by_group",
"=",
"False",
",",
"no_raise",
"=",
"False",
",",
"zero_aware",
"=",
"False",
")",
":",
"if",
"not",
"(",
"(",
"quantiles",
"is",
"not"... | 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... | [
"Computes",
"period",
"wise",
"factor",
"quantiles",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L84-L169 | train |
quantopian/alphalens | alphalens/utils.py | infer_trading_calendar | 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 ... | python | 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 ... | [
"def",
"infer_trading_calendar",
"(",
"factor_idx",
",",
"prices_idx",
")",
":",
"full_idx",
"=",
"factor_idx",
".",
"union",
"(",
"prices_idx",
")",
"traded_weekdays",
"=",
"[",
"]",
"holidays",
"=",
"[",
"]",
"days_of_the_week",
"=",
"[",
"'Mon'",
",",
"'T... | 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
------... | [
"Infer",
"the",
"trading",
"calendar",
"from",
"factor",
"and",
"price",
"information",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L172-L212 | train |
quantopian/alphalens | alphalens/utils.py | compute_forward_returns | def compute_forward_returns(factor,
prices,
periods=(1, 5, 10),
filter_zscore=None,
cumulative_returns=True):
"""
Finds the N period forward returns (as percent change) for each asset
provided.
... | python | def compute_forward_returns(factor,
prices,
periods=(1, 5, 10),
filter_zscore=None,
cumulative_returns=True):
"""
Finds the N period forward returns (as percent change) for each asset
provided.
... | [
"def",
"compute_forward_returns",
"(",
"factor",
",",
"prices",
",",
"periods",
"=",
"(",
"1",
",",
"5",
",",
"10",
")",
",",
"filter_zscore",
"=",
"None",
",",
"cumulative_returns",
"=",
"True",
")",
":",
"factor_dateindex",
"=",
"factor",
".",
"index",
... | 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 ... | [
"Finds",
"the",
"N",
"period",
"forward",
"returns",
"(",
"as",
"percent",
"change",
")",
"for",
"each",
"asset",
"provided",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L215-L343 | train |
quantopian/alphalens | alphalens/utils.py | demean_forward_returns | def demean_forward_returns(factor_data, grouper=None):
"""
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... | python | def demean_forward_returns(factor_data, grouper=None):
"""
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... | [
"def",
"demean_forward_returns",
"(",
"factor_data",
",",
"grouper",
"=",
"None",
")",
":",
"factor_data",
"=",
"factor_data",
".",
"copy",
"(",
")",
"if",
"not",
"grouper",
":",
"grouper",
"=",
"factor_data",
".",
"index",
".",
"get_level_values",
"(",
"'da... | 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... | [
"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",
"por... | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L346-L383 | train |
quantopian/alphalens | alphalens/utils.py | print_table | def print_table(table, name=None, fmt=None):
"""
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
Ta... | python | def print_table(table, name=None, fmt=None):
"""
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
Ta... | [
"def",
"print_table",
"(",
"table",
",",
"name",
"=",
"None",
",",
"fmt",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"table",
",",
"pd",
".",
"Series",
")",
":",
"table",
"=",
"pd",
".",
"DataFrame",
"(",
"table",
")",
"if",
"isinstance",
"(",... | 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, ... | [
"Pretty",
"print",
"a",
"pandas",
"DataFrame",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L386-L417 | train |
quantopian/alphalens | alphalens/utils.py | get_clean_factor | def get_clean_factor(factor,
forward_returns,
groupby=None,
binning_by_group=False,
quantiles=5,
bins=None,
groupby_labels=None,
max_loss=0.35,
zero_awa... | python | def get_clean_factor(factor,
forward_returns,
groupby=None,
binning_by_group=False,
quantiles=5,
bins=None,
groupby_labels=None,
max_loss=0.35,
zero_awa... | [
"def",
"get_clean_factor",
"(",
"factor",
",",
"forward_returns",
",",
"groupby",
"=",
"None",
",",
"binning_by_group",
"=",
"False",
",",
"quantiles",
"=",
"5",
",",
"bins",
"=",
"None",
",",
"groupby_labels",
"=",
"None",
",",
"max_loss",
"=",
"0.35",
",... | 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",
"forward",
"return",
"data",
"and",
"group",
"mappings",
"into",
"a",
"DataFrame",
"that",
"contains",
"aligned",
"MultiIndex",
"indices",
"of",
"timestamp",
"and",
"asset",
".",
"The",
"returned",
"data",
"will",
"be",
"for... | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L420-L629 | train |
quantopian/alphalens | alphalens/utils.py | get_clean_factor_and_forward_returns | def get_clean_factor_and_forward_returns(factor,
prices,
groupby=None,
binning_by_group=False,
quantiles=5,
bins=No... | python | def get_clean_factor_and_forward_returns(factor,
prices,
groupby=None,
binning_by_group=False,
quantiles=5,
bins=No... | [
"def",
"get_clean_factor_and_forward_returns",
"(",
"factor",
",",
"prices",
",",
"groupby",
"=",
"None",
",",
"binning_by_group",
"=",
"False",
",",
"quantiles",
"=",
"5",
",",
"bins",
"=",
"None",
",",
"periods",
"=",
"(",
"1",
",",
"5",
",",
"10",
")"... | 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... | [
"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",
"... | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L632-L799 | train |
quantopian/alphalens | alphalens/utils.py | rate_of_return | def rate_of_return(period_ret, base_period):
"""
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... | python | def rate_of_return(period_ret, base_period):
"""
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... | [
"def",
"rate_of_return",
"(",
"period_ret",
",",
"base_period",
")",
":",
"period_len",
"=",
"period_ret",
".",
"name",
"conversion_factor",
"=",
"(",
"pd",
".",
"Timedelta",
"(",
"base_period",
")",
"/",
"pd",
".",
"Timedelta",
"(",
"period_len",
")",
")",
... | 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... | [
"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"
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L802-L827 | train |
quantopian/alphalens | alphalens/utils.py | std_conversion | def std_conversion(period_std, base_period):
"""
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.
... | python | def std_conversion(period_std, base_period):
"""
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.
... | [
"def",
"std_conversion",
"(",
"period_std",
",",
"base_period",
")",
":",
"period_len",
"=",
"period_std",
".",
"name",
"conversion_factor",
"=",
"(",
"pd",
".",
"Timedelta",
"(",
"period_len",
")",
"/",
"pd",
".",
"Timedelta",
"(",
"base_period",
")",
")",
... | 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... | [
"one_period_len",
"standard",
"deviation",
"(",
"or",
"standard",
"error",
")",
"approximation"
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L830-L853 | train |
quantopian/alphalens | alphalens/utils.py | get_forward_returns_columns | 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 None) for col in columns]
return columns[valid_columns] | python | 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 None) for col in columns]
return columns[valid_columns] | [
"def",
"get_forward_returns_columns",
"(",
"columns",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"^(\\d+([Dhms]|ms|us|ns))+$\"",
",",
"re",
".",
"IGNORECASE",
")",
"valid_columns",
"=",
"[",
"(",
"pattern",
".",
"match",
"(",
"col",
")",
"is",
"... | Utility that detects and returns the columns that are forward returns | [
"Utility",
"that",
"detects",
"and",
"returns",
"the",
"columns",
"that",
"are",
"forward",
"returns"
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L856-L862 | train |
quantopian/alphalens | alphalens/utils.py | timedelta_to_string | def timedelta_to_string(timedelta):
"""
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'
"""
... | python | def timedelta_to_string(timedelta):
"""
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",
")",
":",
"c",
"=",
"timedelta",
".",
"components",
"format",
"=",
"''",
"if",
"c",
".",
"days",
"!=",
"0",
":",
"format",
"+=",
"'%dD'",
"%",
"c",
".",
"days",
"if",
"c",
".",
"hours",
">",
"0",
":",... | 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' | [
"Utility",
"that",
"converts",
"a",
"pandas",
".",
"Timedelta",
"to",
"a",
"string",
"representation",
"compatible",
"with",
"pandas",
".",
"Timedelta",
"constructor",
"format"
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L865-L895 | train |
quantopian/alphalens | alphalens/utils.py | add_custom_calendar_timedelta | def add_custom_calendar_timedelta(input, timedelta, freq):
"""
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... | python | def add_custom_calendar_timedelta(input, timedelta, freq):
"""
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... | [
"def",
"add_custom_calendar_timedelta",
"(",
"input",
",",
"timedelta",
",",
"freq",
")",
":",
"if",
"not",
"isinstance",
"(",
"freq",
",",
"(",
"Day",
",",
"BusinessDay",
",",
"CustomBusinessDay",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"freq must be Day... | 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)
... | [
"Add",
"timedelta",
"to",
"input",
"taking",
"into",
"consideration",
"custom",
"frequency",
"which",
"is",
"used",
"to",
"deal",
"with",
"custom",
"calendars",
"such",
"as",
"a",
"trading",
"calendar"
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L898-L918 | train |
quantopian/alphalens | alphalens/utils.py | diff_custom_calendar_timedeltas | def diff_custom_calendar_timedeltas(start, end, freq):
"""
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
... | python | def diff_custom_calendar_timedeltas(start, end, freq):
"""
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
... | [
"def",
"diff_custom_calendar_timedeltas",
"(",
"start",
",",
"end",
",",
"freq",
")",
":",
"if",
"not",
"isinstance",
"(",
"freq",
",",
"(",
"Day",
",",
"BusinessDay",
",",
"CustomBusinessDay",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"freq must be Day, Bu... | 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 : ... | [
"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"
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L921-L966 | train |
quantopian/alphalens | alphalens/plotting.py | customize | 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:
color_palette = sns.color_palette('colorblind')
... | python | 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:
color_palette = sns.color_palette('colorblind')
... | [
"def",
"customize",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"call_w_context",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"set_context",
"=",
"kwargs",
".",
"pop",
"(",
"'set_context'",
",",
"True",
")",
"if",
"set_cont... | Decorator to set plotting context and axes style during function call. | [
"Decorator",
"to",
"set",
"plotting",
"context",
"and",
"axes",
"style",
"during",
"function",
"call",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L34-L48 | train |
quantopian/alphalens | alphalens/plotting.py | plot_ic_ts | def plot_ic_ts(ic, ax=None):
"""
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.
... | python | def plot_ic_ts(ic, ax=None):
"""
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.
... | [
"def",
"plot_ic_ts",
"(",
"ic",
",",
"ax",
"=",
"None",
")",
":",
"ic",
"=",
"ic",
".",
"copy",
"(",
")",
"num_plots",
"=",
"len",
"(",
"ic",
".",
"columns",
")",
"if",
"ax",
"is",
"None",
":",
"f",
",",
"ax",
"=",
"plt",
".",
"subplots",
"("... | 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",
"and",
"IC",
"moving",
"average",
"for",
"a",
"given",
"factor",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L192-L245 | train |
quantopian/alphalens | alphalens/plotting.py | plot_ic_hist | def plot_ic_hist(ic, ax=None):
"""
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
... | python | def plot_ic_hist(ic, ax=None):
"""
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
... | [
"def",
"plot_ic_hist",
"(",
"ic",
",",
"ax",
"=",
"None",
")",
":",
"ic",
"=",
"ic",
".",
"copy",
"(",
")",
"num_plots",
"=",
"len",
"(",
"ic",
".",
"columns",
")",
"v_spaces",
"=",
"(",
"(",
"num_plots",
"-",
"1",
")",
"//",
"3",
")",
"+",
"... | 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",
"histogram",
"for",
"a",
"given",
"factor",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L248-L289 | train |
quantopian/alphalens | alphalens/plotting.py | plot_ic_qq | def plot_ic_qq(ic, theoretical_dist=stats.norm, ax=None):
"""
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.s... | python | def plot_ic_qq(ic, theoretical_dist=stats.norm, ax=None):
"""
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.s... | [
"def",
"plot_ic_qq",
"(",
"ic",
",",
"theoretical_dist",
"=",
"stats",
".",
"norm",
",",
"ax",
"=",
"None",
")",
":",
"ic",
"=",
"ic",
".",
"copy",
"(",
")",
"num_plots",
"=",
"len",
"(",
"ic",
".",
"columns",
")",
"v_spaces",
"=",
"(",
"(",
"num... | 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",
"Spearman",
"Rank",
"Information",
"Coefficient",
"Q",
"-",
"Q",
"plot",
"relative",
"to",
"a",
"theoretical",
"distribution",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L292-L338 | train |
quantopian/alphalens | alphalens/plotting.py | plot_quantile_returns_bar | def plot_quantile_returns_bar(mean_ret_by_q,
by_group=False,
ylim_percentiles=None,
ax=None):
"""
Plots mean period wise returns for factor quantiles.
Parameters
----------
mean_ret_by_q : pd.DataFrame
... | python | def plot_quantile_returns_bar(mean_ret_by_q,
by_group=False,
ylim_percentiles=None,
ax=None):
"""
Plots mean period wise returns for factor quantiles.
Parameters
----------
mean_ret_by_q : pd.DataFrame
... | [
"def",
"plot_quantile_returns_bar",
"(",
"mean_ret_by_q",
",",
"by_group",
"=",
"False",
",",
"ylim_percentiles",
"=",
"None",
",",
"ax",
"=",
"None",
")",
":",
"mean_ret_by_q",
"=",
"mean_ret_by_q",
".",
"copy",
"(",
")",
"if",
"ylim_percentiles",
"is",
"not"... | 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",
"mean",
"period",
"wise",
"returns",
"for",
"factor",
"quantiles",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L341-L409 | train |
quantopian/alphalens | alphalens/plotting.py | plot_quantile_returns_violin | def plot_quantile_returns_violin(return_by_q,
ylim_percentiles=None,
ax=None):
"""
Plots a violin box plot of period wise returns for factor quantiles.
Parameters
----------
return_by_q : pd.DataFrame - MultiIndex
DataFrame w... | python | def plot_quantile_returns_violin(return_by_q,
ylim_percentiles=None,
ax=None):
"""
Plots a violin box plot of period wise returns for factor quantiles.
Parameters
----------
return_by_q : pd.DataFrame - MultiIndex
DataFrame w... | [
"def",
"plot_quantile_returns_violin",
"(",
"return_by_q",
",",
"ylim_percentiles",
"=",
"None",
",",
"ax",
"=",
"None",
")",
":",
"return_by_q",
"=",
"return_by_q",
".",
"copy",
"(",
")",
"if",
"ylim_percentiles",
"is",
"not",
"None",
":",
"ymin",
"=",
"(",... | 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",
"a",
"violin",
"box",
"plot",
"of",
"period",
"wise",
"returns",
"for",
"factor",
"quantiles",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L412-L469 | train |
quantopian/alphalens | alphalens/plotting.py | plot_mean_quantile_returns_spread_time_series | def plot_mean_quantile_returns_spread_time_series(mean_returns_spread,
std_err=None,
bandwidth=1,
ax=None):
"""
Plots mean period wise returns for factor quantile... | python | def plot_mean_quantile_returns_spread_time_series(mean_returns_spread,
std_err=None,
bandwidth=1,
ax=None):
"""
Plots mean period wise returns for factor quantile... | [
"def",
"plot_mean_quantile_returns_spread_time_series",
"(",
"mean_returns_spread",
",",
"std_err",
"=",
"None",
",",
"bandwidth",
"=",
"1",
",",
"ax",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"mean_returns_spread",
",",
"pd",
".",
"DataFrame",
")",
":",
... | 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",
"mean",
"period",
"wise",
"returns",
"for",
"factor",
"quantiles",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L472-L555 | train |
quantopian/alphalens | alphalens/plotting.py | plot_ic_by_group | def plot_ic_by_group(ic_group, ax=None):
"""
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
Ax... | python | def plot_ic_by_group(ic_group, ax=None):
"""
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
Ax... | [
"def",
"plot_ic_by_group",
"(",
"ic_group",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"f",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
"figsize",
"=",
"(",
"18",
",",
"6",
")",
")",
"ic_group",
".",
... | 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",
"Spearman",
"Rank",
"Information",
"Coefficient",
"for",
"a",
"given",
"factor",
"over",
"provided",
"forward",
"returns",
".",
"Separates",
"by",
"group",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L558-L582 | train |
quantopian/alphalens | alphalens/plotting.py | plot_factor_rank_auto_correlation | def plot_factor_rank_auto_correlation(factor_autocorrelation,
period=1,
ax=None):
"""
Plots factor rank autocorrelation over time.
See factor_rank_autocorrelation for more details.
Parameters
----------
factor_autocorre... | python | def plot_factor_rank_auto_correlation(factor_autocorrelation,
period=1,
ax=None):
"""
Plots factor rank autocorrelation over time.
See factor_rank_autocorrelation for more details.
Parameters
----------
factor_autocorre... | [
"def",
"plot_factor_rank_auto_correlation",
"(",
"factor_autocorrelation",
",",
"period",
"=",
"1",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"f",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
"figsize",
"=",
... | 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",
"factor",
"rank",
"autocorrelation",
"over",
"time",
".",
"See",
"factor_rank_autocorrelation",
"for",
"more",
"details",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L585-L620 | train |
quantopian/alphalens | alphalens/plotting.py | plot_top_bottom_quantile_turnover | def plot_top_bottom_quantile_turnover(quantile_turnover, period=1, ax=None):
"""
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 ov... | python | def plot_top_bottom_quantile_turnover(quantile_turnover, period=1, ax=None):
"""
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 ov... | [
"def",
"plot_top_bottom_quantile_turnover",
"(",
"quantile_turnover",
",",
"period",
"=",
"1",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"f",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
"figsize",
"=",
"(",... | 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",
"period",
"wise",
"top",
"and",
"bottom",
"quantile",
"factor",
"turnover",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L623-L653 | train |
quantopian/alphalens | alphalens/plotting.py | plot_monthly_ic_heatmap | def plot_monthly_ic_heatmap(mean_monthly_ic, ax=None):
"""
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 t... | python | def plot_monthly_ic_heatmap(mean_monthly_ic, ax=None):
"""
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 t... | [
"def",
"plot_monthly_ic_heatmap",
"(",
"mean_monthly_ic",
",",
"ax",
"=",
"None",
")",
":",
"mean_monthly_ic",
"=",
"mean_monthly_ic",
".",
"copy",
"(",
")",
"num_plots",
"=",
"len",
"(",
"mean_monthly_ic",
".",
"columns",
")",
"v_spaces",
"=",
"(",
"(",
"nu... | 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. | [
"Plots",
"a",
"heatmap",
"of",
"the",
"information",
"coefficient",
"or",
"returns",
"by",
"month",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L656-L711 | train |
quantopian/alphalens | alphalens/plotting.py | plot_cumulative_returns | def plot_cumulative_returns(factor_returns, period, freq, title=None, ax=None):
"""
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: pa... | python | def plot_cumulative_returns(factor_returns, period, freq, title=None, ax=None):
"""
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: pa... | [
"def",
"plot_cumulative_returns",
"(",
"factor_returns",
",",
"period",
",",
"freq",
",",
"title",
"=",
"None",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"f",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
... | 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",
"the",
"returns",
"series",
"passed",
"in",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L714-L754 | train |
quantopian/alphalens | alphalens/plotting.py | plot_cumulative_returns_by_quantile | def plot_cumulative_returns_by_quantile(quantile_returns,
period,
freq,
ax=None):
"""
Plots the cumulative returns of various factor quantiles.
Parameters
----------
quantile_retu... | python | def plot_cumulative_returns_by_quantile(quantile_returns,
period,
freq,
ax=None):
"""
Plots the cumulative returns of various factor quantiles.
Parameters
----------
quantile_retu... | [
"def",
"plot_cumulative_returns_by_quantile",
"(",
"quantile_returns",
",",
"period",
",",
"freq",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"f",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
"figsize",
"=",
... | 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",
"the",
"cumulative",
"returns",
"of",
"various",
"factor",
"quantiles",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L757-L807 | train |
quantopian/alphalens | alphalens/plotting.py | plot_quantile_average_cumulative_return | def plot_quantile_average_cumulative_return(avg_cumulative_returns,
by_quantile=False,
std_bar=False,
title=None,
ax=None):
"""
Plots se... | python | def plot_quantile_average_cumulative_return(avg_cumulative_returns,
by_quantile=False,
std_bar=False,
title=None,
ax=None):
"""
Plots se... | [
"def",
"plot_quantile_average_cumulative_return",
"(",
"avg_cumulative_returns",
",",
"by_quantile",
"=",
"False",
",",
"std_bar",
"=",
"False",
",",
"title",
"=",
"None",
",",
"ax",
"=",
"None",
")",
":",
"avg_cumulative_returns",
"=",
"avg_cumulative_returns",
"."... | 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",
"sector",
"-",
"wise",
"mean",
"daily",
"returns",
"for",
"factor",
"quantiles",
"across",
"provided",
"forward",
"price",
"movement",
"columns",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L810-L895 | train |
quantopian/alphalens | alphalens/plotting.py | plot_events_distribution | def plot_events_distribution(events, num_bars=50, ax=None):
"""
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... | python | def plot_events_distribution(events, num_bars=50, ax=None):
"""
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... | [
"def",
"plot_events_distribution",
"(",
"events",
",",
"num_bars",
"=",
"50",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"f",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
"figsize",
"=",
"(",
"18",
",",
... | 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
-------
... | [
"Plots",
"the",
"distribution",
"of",
"events",
"in",
"time",
"."
] | d43eac871bb061e956df936794d3dd514da99e44 | https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/plotting.py#L898-L928 | train |
PyMySQL/PyMySQL | pymysql/cursors.py | Cursor.close | 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:
self.connection = None | python | 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:
self.connection = None | [
"def",
"close",
"(",
"self",
")",
":",
"conn",
"=",
"self",
".",
"connection",
"if",
"conn",
"is",
"None",
":",
"return",
"try",
":",
"while",
"self",
".",
"nextset",
"(",
")",
":",
"pass",
"finally",
":",
"self",
".",
"connection",
"=",
"None"
] | Closing a cursor just exhausts all remaining data. | [
"Closing",
"a",
"cursor",
"just",
"exhausts",
"all",
"remaining",
"data",
"."
] | 3674bc6fd064bf88524e839c07690e8c35223709 | https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L47-L58 | train |
PyMySQL/PyMySQL | pymysql/cursors.py | Cursor._nextset | 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:
return None
self._re... | python | 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:
return None
self._re... | [
"def",
"_nextset",
"(",
"self",
",",
"unbuffered",
"=",
"False",
")",
":",
"conn",
"=",
"self",
".",
"_get_db",
"(",
")",
"current_result",
"=",
"self",
".",
"_result",
"if",
"current_result",
"is",
"None",
"or",
"current_result",
"is",
"not",
"conn",
".... | Get the next query set | [
"Get",
"the",
"next",
"query",
"set"
] | 3674bc6fd064bf88524e839c07690e8c35223709 | https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L85-L97 | train |
PyMySQL/PyMySQL | pymysql/cursors.py | Cursor.mogrify | def mogrify(self, query, args=None):
"""
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.
"""
conn = self._get_db()
if PY2: # Use bytes on Python 2 alw... | python | def mogrify(self, query, args=None):
"""
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.
"""
conn = self._get_db()
if PY2: # Use bytes on Python 2 alw... | [
"def",
"mogrify",
"(",
"self",
",",
"query",
",",
"args",
"=",
"None",
")",
":",
"conn",
"=",
"self",
".",
"_get_db",
"(",
")",
"if",
"PY2",
":",
"# Use bytes on Python 2 always",
"query",
"=",
"self",
".",
"_ensure_bytes",
"(",
"query",
",",
"encoding",... | 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. | [
"Returns",
"the",
"exact",
"string",
"that",
"is",
"sent",
"to",
"the",
"database",
"by",
"calling",
"the",
"execute",
"()",
"method",
"."
] | 3674bc6fd064bf88524e839c07690e8c35223709 | https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L128-L142 | train |
PyMySQL/PyMySQL | pymysql/cursors.py | Cursor.execute | def execute(self, query, args=None):
"""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 u... | python | def execute(self, query, args=None):
"""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 u... | [
"def",
"execute",
"(",
"self",
",",
"query",
",",
"args",
"=",
"None",
")",
":",
"while",
"self",
".",
"nextset",
"(",
")",
":",
"pass",
"query",
"=",
"self",
".",
"mogrify",
"(",
"query",
",",
"args",
")",
"result",
"=",
"self",
".",
"_query",
"... | 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",
"a",
"query"
] | 3674bc6fd064bf88524e839c07690e8c35223709 | https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L144-L165 | train |
PyMySQL/PyMySQL | pymysql/cursors.py | Cursor.callproc | def callproc(self, procname, args=()):
"""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 m... | python | def callproc(self, procname, args=()):
"""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 m... | [
"def",
"callproc",
"(",
"self",
",",
"procname",
",",
"args",
"=",
"(",
")",
")",
":",
"conn",
"=",
"self",
".",
"_get_db",
"(",
")",
"if",
"args",
":",
"fmt",
"=",
"'@_{0}_%d=%s'",
".",
"format",
"(",
"procname",
")",
"self",
".",
"_query",
"(",
... | 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 ... | [
"Execute",
"stored",
"procedure",
"procname",
"with",
"args"
] | 3674bc6fd064bf88524e839c07690e8c35223709 | https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L231-L271 | train |
PyMySQL/PyMySQL | pymysql/cursors.py | Cursor.fetchone | 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 | python | 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 | [
"def",
"fetchone",
"(",
"self",
")",
":",
"self",
".",
"_check_executed",
"(",
")",
"if",
"self",
".",
"_rows",
"is",
"None",
"or",
"self",
".",
"rownumber",
">=",
"len",
"(",
"self",
".",
"_rows",
")",
":",
"return",
"None",
"result",
"=",
"self",
... | Fetch the next row | [
"Fetch",
"the",
"next",
"row"
] | 3674bc6fd064bf88524e839c07690e8c35223709 | https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L273-L280 | train |
PyMySQL/PyMySQL | pymysql/cursors.py | Cursor.fetchmany | 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._rows))
return r... | python | 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._rows))
return r... | [
"def",
"fetchmany",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"self",
".",
"_check_executed",
"(",
")",
"if",
"self",
".",
"_rows",
"is",
"None",
":",
"return",
"(",
")",
"end",
"=",
"self",
".",
"rownumber",
"+",
"(",
"size",
"or",
"self",
... | Fetch several rows | [
"Fetch",
"several",
"rows"
] | 3674bc6fd064bf88524e839c07690e8c35223709 | https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L282-L290 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.