_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q252000 | LineString.to_bounding_box | validation | def to_bounding_box(self):
"""
Generate a bounding box encapsulating the line string.
Returns
-------
None or imgaug.augmentables.bbs.BoundingBox
Bounding box encapsulating the line string.
``None`` if the line string contained no points.
| python | {
"resource": ""
} |
q252001 | LineString.to_polygon | validation | def to_polygon(self):
"""
Generate a polygon from the line string points.
Returns
-------
imgaug.augmentables.polys.Polygon
Polygon with the same corner points as the line string.
Note that the polygon might be invalid, e.g. contain less than 3
| python | {
"resource": ""
} |
q252002 | LineString.to_heatmap | validation | def to_heatmap(self, image_shape, size_lines=1, size_points=0,
antialiased=True, raise_if_out_of_image=False):
"""
Generate a heatmap object from the line string.
This is similar to
:func:`imgaug.augmentables.lines.LineString.draw_lines_heatmap_array`
executed... | python | {
"resource": ""
} |
q252003 | LineString.to_segmentation_map | validation | def to_segmentation_map(self, image_shape, size_lines=1, size_points=0,
raise_if_out_of_image=False):
"""
Generate a segmentation map object from the line string.
This is similar to
:func:`imgaug.augmentables.lines.LineString.draw_mask`.
The result is... | python | {
"resource": ""
} |
q252004 | LineString.coords_almost_equals | validation | def coords_almost_equals(self, other, max_distance=1e-6, points_per_edge=8):
"""
Compare this and another LineString's coordinates.
This is an approximate method based on pointwise distances and can
in rare corner cases produce wrong outputs.
Parameters
----------
... | python | {
"resource": ""
} |
q252005 | LineString.almost_equals | validation | def almost_equals(self, other, max_distance=1e-4, points_per_edge=8):
"""
Compare this and another LineString.
Parameters
----------
other: imgaug.augmentables.lines.LineString
The other line string. Must be a LineString instance, not just
its coordinates... | python | {
"resource": ""
} |
q252006 | LineString.copy | validation | def copy(self, coords=None, label=None):
"""
Create a shallow copy of the LineString object.
Parameters
----------
coords : None or iterable of tuple of number or ndarray
If not ``None``, then the coords of the copied object will be set
to this value.
... | python | {
"resource": ""
} |
q252007 | LineStringsOnImage.draw_on_image | validation | def draw_on_image(self, image,
color=(0, 255, 0), color_lines=None, color_points=None,
alpha=1.0, alpha_lines=None, alpha_points=None,
size=1, size_lines=None, size_points=None,
antialiased=True,
raise_if_out_o... | python | {
"resource": ""
} |
q252008 | LineStringsOnImage.clip_out_of_image | validation | def clip_out_of_image(self):
"""
Clip off all parts of the line strings that are outside of the image.
Returns
-------
imgaug.augmentables.lines.LineStringsOnImage
| python | {
"resource": ""
} |
q252009 | LineStringsOnImage.copy | validation | def copy(self, line_strings=None, shape=None):
"""
Create a shallow copy of the LineStringsOnImage object.
Parameters
----------
line_strings : None \
or list of imgaug.augmentables.lines.LineString, optional
List of line strings on the image.
... | python | {
"resource": ""
} |
q252010 | LineStringsOnImage.deepcopy | validation | def deepcopy(self, line_strings=None, shape=None):
"""
Create a deep copy of the LineStringsOnImage object.
Parameters
----------
line_strings : None \
or list of imgaug.augmentables.lines.LineString, optional
List of line strings on the image.... | python | {
"resource": ""
} |
q252011 | blend_alpha | validation | def blend_alpha(image_fg, image_bg, alpha, eps=1e-2):
"""
Blend two images using an alpha blending.
In an alpha blending, the two images are naively mixed. Let ``A`` be the foreground image
and ``B`` the background image and ``a`` is the alpha value. Each pixel intensity is then
computed as ``a * A... | python | {
"resource": ""
} |
q252012 | SimplexNoiseAlpha | validation | def SimplexNoiseAlpha(first=None, second=None, per_channel=False, size_px_max=(2, 16), upscale_method=None,
iterations=(1, 3), aggregation_method="max", sigmoid=True, sigmoid_thresh=None,
name=None, deterministic=False, random_state=None):
"""
Augmenter to alpha-blend... | python | {
"resource": ""
} |
q252013 | OneOf | validation | def OneOf(children, name=None, deterministic=False, random_state=None):
"""
Augmenter that always executes exactly one of its children.
dtype support::
See ``imgaug.augmenters.meta.SomeOf``.
Parameters
----------
children : list of imgaug.augmenters.meta.Augmenter
The choices ... | python | {
"resource": ""
} |
q252014 | AssertLambda | validation | def AssertLambda(func_images=None, func_heatmaps=None, func_keypoints=None,
func_polygons=None, name=None, deterministic=False,
random_state=None):
"""
Augmenter that runs an assert on each batch of input images
using a lambda function as condition.
This is useful to m... | python | {
"resource": ""
} |
q252015 | MotionBlur | validation | def MotionBlur(k=5, angle=(0, 360), direction=(-1.0, 1.0), order=1, name=None, deterministic=False, random_state=None):
"""
Augmenter that sharpens images and overlays the result with the original image.
dtype support::
See ``imgaug.augmenters.convolutional.Convolve``.
Parameters
--------... | python | {
"resource": ""
} |
q252016 | Clouds | validation | def Clouds(name=None, deterministic=False, random_state=None):
"""
Augmenter to draw clouds in images.
This is a wrapper around ``CloudLayer``. It executes 1 to 2 layers per image, leading to varying densities
and frequency patterns of clouds.
This augmenter seems to be fairly robust w.r.t. the im... | python | {
"resource": ""
} |
q252017 | Fog | validation | def Fog(name=None, deterministic=False, random_state=None):
"""
Augmenter to draw fog in images.
This is a wrapper around ``CloudLayer``. It executes a single layer per image with a configuration leading
to fairly dense clouds with low-frequency patterns.
This augmenter seems to be fairly robust w... | python | {
"resource": ""
} |
q252018 | Snowflakes | validation | def Snowflakes(density=(0.005, 0.075), density_uniformity=(0.3, 0.9), flake_size=(0.2, 0.7),
flake_size_uniformity=(0.4, 0.8), angle=(-30, 30), speed=(0.007, 0.03),
name=None, deterministic=False, random_state=None):
"""
Augmenter to add falling snowflakes to images.
This is a... | python | {
"resource": ""
} |
q252019 | SegmentationMapOnImage.draw | validation | def draw(self, size=None, background_threshold=0.01, background_class_id=None, colors=None,
return_foreground_mask=False):
"""
Render the segmentation map as an RGB image.
Parameters
----------
size : None or float or iterable of int or iterable of float, optional
... | python | {
"resource": ""
} |
q252020 | SegmentationMapOnImage.draw_on_image | validation | def draw_on_image(self, image, alpha=0.75, resize="segmentation_map", background_threshold=0.01,
background_class_id=None, colors=None, draw_background=False):
"""
Draw the segmentation map as an overlay over an image.
Parameters
----------
image : (H,W,3) ... | python | {
"resource": ""
} |
q252021 | SegmentationMapOnImage.pad_to_aspect_ratio | validation | def pad_to_aspect_ratio(self, aspect_ratio, mode="constant", cval=0.0, return_pad_amounts=False):
"""
Pad the segmentation map on its sides so that its matches a target aspect ratio.
Depending on which dimension is smaller (height or width), only the corresponding
sides (left/right or t... | python | {
"resource": ""
} |
q252022 | SegmentationMapOnImage.resize | validation | def resize(self, sizes, interpolation="cubic"):
"""
Resize the segmentation map array to the provided size given the provided interpolation.
Parameters
----------
sizes : float or iterable of int or iterable of float
New size of the array in ``(height, width)``.
... | python | {
"resource": ""
} |
q252023 | SegmentationMapOnImage.to_heatmaps | validation | def to_heatmaps(self, only_nonempty=False, not_none_if_no_nonempty=False):
"""
Convert segmentation map to heatmaps object.
Each segmentation map class will be represented as a single heatmap channel.
Parameters
----------
only_nonempty : bool, optional
If T... | python | {
"resource": ""
} |
q252024 | SegmentationMapOnImage.from_heatmaps | validation | def from_heatmaps(heatmaps, class_indices=None, nb_classes=None):
"""
Convert heatmaps to segmentation map.
Assumes that each class is represented as a single heatmap channel.
Parameters
----------
heatmaps : imgaug.HeatmapsOnImage
Heatmaps to convert.
... | python | {
"resource": ""
} |
q252025 | SegmentationMapOnImage.deepcopy | validation | def deepcopy(self):
"""
Create a deep copy of the segmentation map object.
Returns
-------
imgaug.SegmentationMapOnImage
| python | {
"resource": ""
} |
q252026 | EventQueue.offer | validation | def offer(self, p, e: Event):
"""
Offer a new event ``s`` at point ``p`` in this queue.
"""
existing = self.events_scan.setdefault(
p, ([], [], [], []) if USE_VERTICAL else
([], [], []))
# Can use double | python | {
"resource": ""
} |
q252027 | HeatmapsOnImage.draw | validation | def draw(self, size=None, cmap="jet"):
"""
Render the heatmaps as RGB images.
Parameters
----------
size : None or float or iterable of int or iterable of float, optional
Size of the rendered RGB image as ``(height, width)``.
See :func:`imgaug.imgaug.imre... | python | {
"resource": ""
} |
q252028 | HeatmapsOnImage.draw_on_image | validation | def draw_on_image(self, image, alpha=0.75, cmap="jet", resize="heatmaps"):
"""
Draw the heatmaps as overlays over an image.
Parameters
----------
image : (H,W,3) ndarray
Image onto which to draw the heatmaps. Expected to be of dtype uint8.
alpha : float, opt... | python | {
"resource": ""
} |
q252029 | HeatmapsOnImage.invert | validation | def invert(self):
"""
Inverts each value in the heatmap, shifting low towards high values and vice versa.
This changes each value to::
v' = max - (v - min)
where ``v`` is the value at some spatial location, ``min`` is the minimum value in the heatmap
and ``max`` is... | python | {
"resource": ""
} |
q252030 | HeatmapsOnImage.pad_to_aspect_ratio | validation | def pad_to_aspect_ratio(self, aspect_ratio, mode="constant", cval=0.0, return_pad_amounts=False):
"""
Pad the heatmaps on their sides so that they match a target aspect ratio.
Depending on which dimension is smaller (height or width), only the corresponding
sides (left/right or top/bott... | python | {
"resource": ""
} |
q252031 | HeatmapsOnImage.to_uint8 | validation | def to_uint8(self):
"""
Convert this heatmaps object to a 0-to-255 array.
Returns
-------
arr_uint8 : (H,W,C) ndarray
Heatmap as a 0-to-255 array (dtype is uint8).
"""
# TODO this always returns (H,W,C), even if input ndarray was originall (H,W)
| python | {
"resource": ""
} |
q252032 | HeatmapsOnImage.from_uint8 | validation | def from_uint8(arr_uint8, shape, min_value=0.0, max_value=1.0):
"""
Create a heatmaps object from an heatmap array containing values ranging from 0 to 255.
Parameters
----------
arr_uint8 : (H,W) ndarray or (H,W,C) ndarray
Heatmap(s) array, where ``H`` is height, ``W... | python | {
"resource": ""
} |
q252033 | HeatmapsOnImage.from_0to1 | validation | def from_0to1(arr_0to1, shape, min_value=0.0, max_value=1.0):
"""
Create a heatmaps object from an heatmap array containing values ranging from 0.0 to 1.0.
Parameters
----------
arr_0to1 : (H,W) or (H,W,C) ndarray
Heatmap(s) array, where ``H`` is height, ``W`` is wid... | python | {
"resource": ""
} |
q252034 | HeatmapsOnImage.change_normalization | validation | def change_normalization(cls, arr, source, target):
"""
Change the value range of a heatmap from one min-max to another min-max.
E.g. the value range may be changed from min=0.0, max=1.0 to min=-1.0, max=1.0.
Parameters
----------
arr : ndarray
Heatmap array... | python | {
"resource": ""
} |
q252035 | HeatmapsOnImage.deepcopy | validation | def deepcopy(self):
"""
Create a deep copy of the Heatmaps object.
Returns
-------
imgaug.HeatmapsOnImage
Deep copy.
"""
| python | {
"resource": ""
} |
q252036 | MutableHeaders.setdefault | validation | def setdefault(self, key: str, value: str) -> str:
"""
If the header `key` does not exist, then set it to `value`.
Returns the header value.
"""
set_key = key.lower().encode("latin-1")
| python | {
"resource": ""
} |
q252037 | MutableHeaders.append | validation | def append(self, key: str, value: str) -> None:
"""
Append a header, preserving any duplicate entries.
"""
append_key | python | {
"resource": ""
} |
q252038 | BaseSchemaGenerator.parse_docstring | validation | def parse_docstring(self, func_or_method: typing.Callable) -> dict:
"""
Given a function, parse the docstring as YAML and return a dictionary of info.
"""
docstring = func_or_method.__doc__
if not docstring:
return {}
# We support having regular docstrings be... | python | {
"resource": ""
} |
q252039 | StaticFiles.get_directories | validation | def get_directories(
self, directory: str = None, packages: typing.List[str] = None
) -> typing.List[str]:
"""
Given `directory` and `packages` arugments, return a list of all the
directories that should be used for serving static files from.
"""
directories = []
... | python | {
"resource": ""
} |
q252040 | StaticFiles.get_response | validation | async def get_response(self, path: str, scope: Scope) -> Response:
"""
Returns an HTTP response, given the incoming path, method and request headers.
"""
if scope["method"] not in ("GET", "HEAD"):
return PlainTextResponse("Method Not Allowed", status_code=405)
if pat... | python | {
"resource": ""
} |
q252041 | StaticFiles.check_config | validation | async def check_config(self) -> None:
"""
Perform a one-off configuration check that StaticFiles is actually
pointed at a directory, so that we can raise loud errors rather than
just returning 404 responses.
"""
if self.directory is None:
return
try:
... | python | {
"resource": ""
} |
q252042 | StaticFiles.is_not_modified | validation | def is_not_modified(
self, response_headers: Headers, request_headers: Headers
) -> bool:
"""
Given the request and response headers, return `True` if an HTTP
"Not Modified" response could be returned instead.
"""
try:
if_none_match = request_headers["if-n... | python | {
"resource": ""
} |
q252043 | build_environ | validation | def build_environ(scope: Scope, body: bytes) -> dict:
"""
Builds a scope and request body into a WSGI environ object.
"""
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": scope.get("root_path", ""),
"PATH_INFO": scope["path"],
"QUERY_STRING": scope["query_str... | python | {
"resource": ""
} |
q252044 | WebSocket.receive | validation | async def receive(self) -> Message:
"""
Receive ASGI websocket messages, ensuring valid state transitions.
"""
if self.client_state == WebSocketState.CONNECTING:
message = await self._receive()
message_type = message["type"]
assert message_type == "web... | python | {
"resource": ""
} |
q252045 | WebSocket.send | validation | async def send(self, message: Message) -> None:
"""
Send ASGI websocket messages, ensuring valid state transitions.
"""
if self.application_state == WebSocketState.CONNECTING:
message_type = message["type"]
assert message_type in {"websocket.accept", "websocket.cl... | python | {
"resource": ""
} |
q252046 | get_top_long_short_abs | validation | def get_top_long_short_abs(positions, top=10):
"""
Finds the top long, short, and absolute positions.
Parameters
----------
positions : pd.DataFrame
The positions that the strategy takes over time.
top : int, optional
How many of each to find (default 10).
Returns
-----... | python | {
"resource": ""
} |
q252047 | get_max_median_position_concentration | validation | def get_max_median_position_concentration(positions):
"""
Finds the max and median long and short position concentrations
in each time period specified by the index of positions.
Parameters
----------
positions : pd.DataFrame
The positions that the strategy takes over time.
Returns... | python | {
"resource": ""
} |
q252048 | get_long_short_pos | validation | def get_long_short_pos(positions):
"""
Determines the long and short allocations in a portfolio.
Parameters
----------
positions : pd.DataFrame
The positions that the strategy takes over time.
Returns
-------
df_long_short : pd.DataFrame
Long and short allocations as a ... | python | {
"resource": ""
} |
q252049 | compute_style_factor_exposures | validation | def compute_style_factor_exposures(positions, risk_factor):
"""
Returns style factor exposure of an algorithm's positions
Parameters
----------
positions : pd.DataFrame
Daily equity positions of algorithm, in dollars.
- See full explanation in create_risk_tear_sheet
risk_factor... | python | {
"resource": ""
} |
q252050 | plot_style_factor_exposures | validation | def plot_style_factor_exposures(tot_style_factor_exposure, factor_name=None,
ax=None):
"""
Plots DataFrame output of compute_style_factor_exposures as a line graph
Parameters
----------
tot_style_factor_exposure : pd.Series
Daily style factor exposures (outpu... | python | {
"resource": ""
} |
q252051 | compute_sector_exposures | validation | def compute_sector_exposures(positions, sectors, sector_dict=SECTORS):
"""
Returns arrays of long, short and gross sector exposures of an algorithm's
positions
Parameters
----------
positions : pd.DataFrame
Daily equity positions of algorithm, in dollars.
- See full explanation ... | python | {
"resource": ""
} |
q252052 | plot_sector_exposures_longshort | validation | def plot_sector_exposures_longshort(long_exposures, short_exposures,
sector_dict=SECTORS, ax=None):
"""
Plots outputs of compute_sector_exposures as area charts
Parameters
----------
long_exposures, short_exposures : arrays
Arrays of long and short sector... | python | {
"resource": ""
} |
q252053 | plot_sector_exposures_gross | validation | def plot_sector_exposures_gross(gross_exposures, sector_dict=None, ax=None):
"""
Plots output of compute_sector_exposures as area charts
Parameters
----------
gross_exposures : arrays
Arrays of gross sector exposures (output of compute_sector_exposures).
sector_dict : dict or OrderedDi... | python | {
"resource": ""
} |
q252054 | plot_sector_exposures_net | validation | def plot_sector_exposures_net(net_exposures, sector_dict=None, ax=None):
"""
Plots output of compute_sector_exposures as line graphs
Parameters
----------
net_exposures : arrays
Arrays of net sector exposures (output of compute_sector_exposures).
sector_dict : dict or OrderedDict
... | python | {
"resource": ""
} |
q252055 | compute_cap_exposures | validation | def compute_cap_exposures(positions, caps):
"""
Returns arrays of long, short and gross market cap exposures of an
algorithm's positions
Parameters
----------
positions : pd.DataFrame
Daily equity positions of algorithm, in dollars.
- See full explanation in compute_style_factor... | python | {
"resource": ""
} |
q252056 | plot_cap_exposures_net | validation | def plot_cap_exposures_net(net_exposures, ax=None):
"""
Plots outputs of compute_cap_exposures as line graphs
Parameters
----------
net_exposures : array
Arrays of gross market cap exposures (output of compute_cap_exposures).
"""
if ax is None:
ax = plt.gca()
color_lis... | python | {
"resource": ""
} |
q252057 | compute_volume_exposures | validation | def compute_volume_exposures(shares_held, volumes, percentile):
"""
Returns arrays of pth percentile of long, short and gross volume exposures
of an algorithm's held shares
Parameters
----------
shares_held : pd.DataFrame
Daily number of shares held by an algorithm.
- See full e... | python | {
"resource": ""
} |
q252058 | create_full_tear_sheet | validation | def create_full_tear_sheet(returns,
positions=None,
transactions=None,
market_data=None,
benchmark_rets=None,
slippage=None,
live_start_date=None,
... | python | {
"resource": ""
} |
q252059 | create_position_tear_sheet | validation | def create_position_tear_sheet(returns, positions,
show_and_plot_top_pos=2, hide_positions=False,
return_fig=False, sector_mappings=None,
transactions=None, estimate_intraday='infer'):
"""
Generate a number of plots for... | python | {
"resource": ""
} |
q252060 | create_txn_tear_sheet | validation | def create_txn_tear_sheet(returns, positions, transactions,
unadjusted_returns=None, estimate_intraday='infer',
return_fig=False):
"""
Generate a number of plots for analyzing a strategy's transactions.
Plots: turnover, daily volume, and a histogram of da... | python | {
"resource": ""
} |
q252061 | create_capacity_tear_sheet | validation | def create_capacity_tear_sheet(returns, positions, transactions,
market_data,
liquidation_daily_vol_limit=0.2,
trade_daily_vol_limit=0.05,
last_n_days=utils.APPROX_BDAYS_PER_MONTH * 6,
... | python | {
"resource": ""
} |
q252062 | create_perf_attrib_tear_sheet | validation | def create_perf_attrib_tear_sheet(returns,
positions,
factor_returns,
factor_loadings,
transactions=None,
pos_in_dollars=True,
... | python | {
"resource": ""
} |
q252063 | daily_txns_with_bar_data | validation | def daily_txns_with_bar_data(transactions, market_data):
"""
Sums the absolute value of shares traded in each name on each day.
Adds columns containing the closing price and total daily volume for
each day-ticker combination.
Parameters
----------
transactions : pd.DataFrame
Prices ... | python | {
"resource": ""
} |
q252064 | days_to_liquidate_positions | validation | def days_to_liquidate_positions(positions, market_data,
max_bar_consumption=0.2,
capital_base=1e6,
mean_volume_window=5):
"""
Compute the number of days that would have been required
to fully liquidate each posit... | python | {
"resource": ""
} |
q252065 | get_low_liquidity_transactions | validation | def get_low_liquidity_transactions(transactions, market_data,
last_n_days=None):
"""
For each traded name, find the daily transaction total that consumed
the greatest proportion of available daily bar volume.
Parameters
----------
transactions : pd.DataFrame
... | python | {
"resource": ""
} |
q252066 | apply_slippage_penalty | validation | def apply_slippage_penalty(returns, txn_daily, simulate_starting_capital,
backtest_starting_capital, impact=0.1):
"""
Applies quadratic volumeshare slippage model to daily returns based
on the proportion of the observed historical daily bar dollar volume
consumed by the strate... | python | {
"resource": ""
} |
q252067 | map_transaction | validation | def map_transaction(txn):
"""
Maps a single transaction row to a dictionary.
Parameters
----------
txn : pd.DataFrame
A single transaction object to convert to a dictionary.
Returns
-------
dict
Mapped transaction.
"""
if isinstance(txn['sid'], dict):
s... | python | {
"resource": ""
} |
q252068 | make_transaction_frame | validation | def make_transaction_frame(transactions):
"""
Formats a transaction DataFrame.
Parameters
----------
transactions : pd.DataFrame
Contains improperly formatted transactional data.
Returns
-------
df : pd.DataFrame
Daily transaction volume and dollar ammount.
- S... | python | {
"resource": ""
} |
q252069 | get_txn_vol | validation | def get_txn_vol(transactions):
"""
Extract daily transaction data from set of transaction objects.
Parameters
----------
transactions : pd.DataFrame
Time series containing one row per symbol (and potentially
duplicate datetime indices) and columns for amount and
price.
... | python | {
"resource": ""
} |
q252070 | adjust_returns_for_slippage | validation | def adjust_returns_for_slippage(returns, positions, transactions,
slippage_bps):
"""
Apply a slippage penalty for every dollar traded.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in c... | python | {
"resource": ""
} |
q252071 | get_turnover | validation | def get_turnover(positions, transactions, denominator='AGB'):
"""
- Value of purchases and sales divided
by either the actual gross book or the portfolio value
for the time step.
Parameters
----------
positions : pd.DataFrame
Contains daily position values including cash.
-... | python | {
"resource": ""
} |
q252072 | _groupby_consecutive | validation | def _groupby_consecutive(txn, max_delta=pd.Timedelta('8h')):
"""Merge transactions of the same direction separated by less than
max_delta time duration.
Parameters
----------
transactions : pd.DataFrame
Prices and amounts of executed round_trips. One row per trade.
- See full explan... | python | {
"resource": ""
} |
q252073 | extract_round_trips | validation | def extract_round_trips(transactions,
portfolio_value=None):
"""Group transactions into "round trips". First, transactions are
grouped by day and directionality. Then, long and short
transactions are matched to create round-trip round_trips for which
PnL, duration and returns are... | python | {
"resource": ""
} |
q252074 | add_closing_transactions | validation | def add_closing_transactions(positions, transactions):
"""
Appends transactions that close out all positions at the end of
the timespan covered by positions data. Utilizes pricing information
in the positions DataFrame to determine closing price.
Parameters
----------
positions : pd.DataFra... | python | {
"resource": ""
} |
q252075 | apply_sector_mappings_to_round_trips | validation | def apply_sector_mappings_to_round_trips(round_trips, sector_mappings):
"""
Translates round trip symbols to sectors.
Parameters
----------
round_trips : pd.DataFrame
DataFrame with one row per round trip trade.
- See full explanation in round_trips.extract_round_trips
sector_ma... | python | {
"resource": ""
} |
q252076 | gen_round_trip_stats | validation | def gen_round_trip_stats(round_trips):
"""Generate various round-trip statistics.
Parameters
----------
round_trips : pd.DataFrame
DataFrame with one row per round trip trade.
- See full explanation in round_trips.extract_round_trips
Returns
-------
stats : dict
A di... | python | {
"resource": ""
} |
q252077 | print_round_trip_stats | validation | def print_round_trip_stats(round_trips, hide_pos=False):
"""Print various round-trip statistics. Tries to pretty-print tables
with HTML output if run inside IPython NB.
Parameters
----------
round_trips : pd.DataFrame
DataFrame with one row per round trip trade.
- See full explanati... | python | {
"resource": ""
} |
q252078 | perf_attrib | validation | def perf_attrib(returns,
positions,
factor_returns,
factor_loadings,
transactions=None,
pos_in_dollars=True):
"""
Attributes the performance of a returns stream to a set of risk factors.
Preprocesses inputs, and then calls empy... | python | {
"resource": ""
} |
q252079 | compute_exposures | validation | def compute_exposures(positions, factor_loadings, stack_positions=True,
pos_in_dollars=True):
"""
Compute daily risk factor exposures.
Normalizes positions (if necessary) and calls ep.compute_exposures.
See empyrical.compute_exposures for more info.
Parameters
----------
... | python | {
"resource": ""
} |
q252080 | create_perf_attrib_stats | validation | def create_perf_attrib_stats(perf_attrib, risk_exposures):
"""
Takes perf attribution data over a period of time and computes annualized
multifactor alpha, multifactor sharpe, risk exposures.
"""
summary = OrderedDict()
total_returns = perf_attrib['total_returns']
specific_returns = perf_att... | python | {
"resource": ""
} |
q252081 | show_perf_attrib_stats | validation | def show_perf_attrib_stats(returns,
positions,
factor_returns,
factor_loadings,
transactions=None,
pos_in_dollars=True):
"""
Calls `perf_attrib` using inputs, and displays outpu... | python | {
"resource": ""
} |
q252082 | plot_returns | validation | def plot_returns(perf_attrib_data, cost=None, ax=None):
"""
Plot total, specific, and common returns.
Parameters
----------
perf_attrib_data : pd.DataFrame
df with factors, common returns, and specific returns as columns,
and datetimes as index. Assumes the `total_returns` column is... | python | {
"resource": ""
} |
q252083 | plot_factor_contribution_to_perf | validation | def plot_factor_contribution_to_perf(
perf_attrib_data,
ax=None,
title='Cumulative common returns attribution',
):
"""
Plot each factor's contribution to performance.
Parameters
----------
perf_attrib_data : pd.DataFrame
df with factors, common returns, and specific ... | python | {
"resource": ""
} |
q252084 | _stack_positions | validation | def _stack_positions(positions, pos_in_dollars=True):
"""
Convert positions to percentages if necessary, and change them
to long format.
Parameters
----------
positions: pd.DataFrame
Daily holdings (in dollars or percentages), indexed by date.
Will be converted to percentages if... | python | {
"resource": ""
} |
q252085 | _cumulative_returns_less_costs | validation | def _cumulative_returns_less_costs(returns, costs):
"""
Compute cumulative returns, less costs.
"""
if costs is None:
| python | {
"resource": ""
} |
q252086 | format_asset | validation | def format_asset(asset):
"""
If zipline asset objects are used, we want to print them out prettily
within the tear sheet. This function should only be applied directly
before displaying.
"""
try:
import zipline.assets
except ImportError:
| python | {
"resource": ""
} |
q252087 | vectorize | validation | def vectorize(func):
"""
Decorator so that functions can be written to work on Series but
may still be called with DataFrames.
"""
def wrapper(df, *args, **kwargs):
if df.ndim == 1:
return | python | {
"resource": ""
} |
q252088 | print_table | validation | def print_table(table,
name=None,
float_format=None,
formatters=None,
header_rows=None):
"""
Pretty print a pandas DataFrame.
Uses HTML output if running inside Jupyter Notebook, otherwise
formatted text output.
Parameters
-------... | python | {
"resource": ""
} |
q252089 | detect_intraday | validation | def detect_intraday(positions, transactions, threshold=0.25):
"""
Attempt to detect an intraday strategy. Get the number of
positions held at the end of the day, and divide that by the
number of unique stocks transacted every day. If the average quotient
is below a threshold, then an intraday strate... | python | {
"resource": ""
} |
q252090 | check_intraday | validation | def check_intraday(estimate, returns, positions, transactions):
"""
Logic for checking if a strategy is intraday and processing it.
Parameters
----------
estimate: boolean or str, optional
Approximate returns for intraday strategies.
See description in tears.create_full_tear_sheet.
... | python | {
"resource": ""
} |
q252091 | estimate_intraday | validation | def estimate_intraday(returns, positions, transactions, EOD_hour=23):
"""
Intraday strategies will often not hold positions at the day end.
This attempts to find the point in the day that best represents
the activity of the strategy on that day, and effectively resamples
the end-of-day positions wit... | python | {
"resource": ""
} |
q252092 | clip_returns_to_benchmark | validation | def clip_returns_to_benchmark(rets, benchmark_rets):
"""
Drop entries from rets so that the start and end dates of rets match those
of benchmark_rets.
Parameters
----------
rets : pd.Series
Daily returns of the strategy, noncumulative.
- See pf.tears.create_full_tear_sheet for ... | python | {
"resource": ""
} |
q252093 | to_utc | validation | def to_utc(df):
"""
For use in tests; applied UTC timestamp to DataFrame.
"""
try:
df.index = df.index.tz_localize('UTC')
| python | {
"resource": ""
} |
q252094 | get_symbol_rets | validation | def get_symbol_rets(symbol, start=None, end=None):
"""
Calls the currently registered 'returns_func'
Parameters
----------
symbol : object
An identifier for the asset whose return
series is desired.
e.g. ticker symbol or database ID
start : date, optional
| python | {
"resource": ""
} |
q252095 | sample_colormap | validation | def sample_colormap(cmap_name, n_samples):
"""
Sample a colormap from matplotlib
"""
colors = []
colormap = cm.cmap_d[cmap_name]
for i | python | {
"resource": ""
} |
q252096 | customize | validation | 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:
with plotting_context(), | python | {
"resource": ""
} |
q252097 | plotting_context | validation | def plotting_context(context='notebook', font_scale=1.5, rc=None):
"""
Create pyfolio default plotting style context.
Under the hood, calls and returns seaborn.plotting_context() with
some custom settings. Usually you would use in a with-context.
Parameters
----------
context : str, option... | python | {
"resource": ""
} |
q252098 | axes_style | validation | def axes_style(style='darkgrid', rc=None):
"""
Create pyfolio default axes style context.
Under the hood, calls and returns seaborn.axes_style() with
some custom settings. Usually you would use in a with-context.
Parameters
----------
style : str, optional
Name of seaborn style.
... | python | {
"resource": ""
} |
q252099 | plot_monthly_returns_heatmap | validation | def plot_monthly_returns_heatmap(returns, ax=None, **kwargs):
"""
Plots a heatmap of returns by month.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.