INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Takes a function or coroutine func ( request ) - > response and returns an ASGI application. | def request_response(func: typing.Callable) -> ASGIApp:
"""
Takes a function or coroutine `func(request) -> response`,
and returns an ASGI application.
"""
is_coroutine = asyncio.iscoroutinefunction(func)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Reque... |
Takes a coroutine func ( session ) and returns an ASGI application. | def websocket_session(func: typing.Callable) -> ASGIApp:
"""
Takes a coroutine `func(session)`, and returns an ASGI application.
"""
# assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async"
async def app(scope: Scope, receive: Receive, send: Send) -> None:
session = W... |
Given a path string like:/ { username: str } return a three - tuple of ( regex format { param_name: convertor } ). | def compile_path(
path: str
) -> typing.Tuple[typing.Pattern, str, typing.Dict[str, Convertor]]:
"""
Given a path string, like: "/{username:str}", return a three-tuple
of (regex, format, {param_name:convertor}).
regex: "/(?P<username>[^/]+)"
format: "/{username}"
convertors: {"user... |
Given the routes yields the following information: | def get_endpoints(
self, routes: typing.List[BaseRoute]
) -> typing.List[EndpointInfo]:
"""
Given the routes, yields the following information:
- path
eg: /users/
- http_method
one of 'get', 'post', 'put', 'patch', 'delete', 'options'
- func
... |
Given a function parse the docstring as YAML and return a dictionary of info. | 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... |
Given directory and packages arugments return a list of all the directories that should be used for serving static files from. | 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 = []
... |
Given the ASGI scope return the path string to serve up with OS specific path seperators and any... components removed. | def get_path(self, scope: Scope) -> str:
"""
Given the ASGI scope, return the `path` string to serve up,
with OS specific path seperators, and any '..', '.' components removed.
"""
return os.path.normpath(os.path.join(*scope["path"].split("/"))) |
Returns an HTTP response given the incoming path method and request headers. | 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... |
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. | 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:
... |
Given the request and response headers return True if an HTTP Not Modified response could be returned instead. | 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... |
Builds a scope and request body into a WSGI environ object. | 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... |
Receive ASGI websocket messages ensuring valid state transitions. | 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... |
Send ASGI websocket messages ensuring valid state transitions. | 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... |
Finds the top long short and absolute positions. | 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
-----... |
Finds the max and median long and short position concentrations in each time period specified by the index of positions. | 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... |
Extract position values from backtest object as returned by get_backtest () on the Quantopian research platform. | def extract_pos(positions, cash):
"""
Extract position values from backtest object as returned by
get_backtest() on the Quantopian research platform.
Parameters
----------
positions : pd.DataFrame
timeseries containing one row per symbol (and potentially
duplicate datetime indic... |
Sum position exposures by sector. | def get_sector_exposures(positions, symbol_sector_map):
"""
Sum position exposures by sector.
Parameters
----------
positions : pd.DataFrame
Contains position values or amounts.
- Example
index 'AAPL' 'MSFT' 'CHK' cash
2004-01-09... |
Determines the long and short allocations in a portfolio. | 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 ... |
Returns style factor exposure of an algorithm s positions | 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... |
Plots DataFrame output of compute_style_factor_exposures as a line graph | 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... |
Returns arrays of long short and gross sector exposures of an algorithm s positions | 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 ... |
Plots outputs of compute_sector_exposures as area charts | 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... |
Plots output of compute_sector_exposures as area charts | 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... |
Plots output of compute_sector_exposures as line graphs | 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
... |
Returns arrays of long short and gross market cap exposures of an algorithm s positions | 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... |
Plots outputs of compute_cap_exposures as area charts | def plot_cap_exposures_longshort(long_exposures, short_exposures, ax=None):
"""
Plots outputs of compute_cap_exposures as area charts
Parameters
----------
long_exposures, short_exposures : arrays
Arrays of long and short market cap exposures (output of
compute_cap_exposures).
"... |
Plots outputs of compute_cap_exposures as area charts | def plot_cap_exposures_gross(gross_exposures, ax=None):
"""
Plots outputs of compute_cap_exposures as area charts
Parameters
----------
gross_exposures : array
Arrays of gross market cap exposures (output of compute_cap_exposures).
"""
if ax is None:
ax = plt.gca()
col... |
Plots outputs of compute_cap_exposures as line graphs | 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... |
Returns arrays of pth percentile of long short and gross volume exposures of an algorithm s held shares | 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... |
Plots outputs of compute_volume_exposures as line graphs | def plot_volume_exposures_longshort(longed_threshold, shorted_threshold,
percentile, ax=None):
"""
Plots outputs of compute_volume_exposures as line graphs
Parameters
----------
longed_threshold, shorted_threshold : pd.Series
Series of longed and shorted ... |
Plots outputs of compute_volume_exposures as line graphs | def plot_volume_exposures_gross(grossed_threshold, percentile, ax=None):
"""
Plots outputs of compute_volume_exposures as line graphs
Parameters
----------
grossed_threshold : pd.Series
Series of grossed volume exposures (output of
compute_volume_exposures).
percentile : float
... |
Generate a number of tear sheets that are useful for analyzing a strategy s performance. | def create_full_tear_sheet(returns,
positions=None,
transactions=None,
market_data=None,
benchmark_rets=None,
slippage=None,
live_start_date=None,
... |
Simpler version of create_full_tear_sheet ; generates summary performance statistics and important plots as a single image. | def create_simple_tear_sheet(returns,
positions=None,
transactions=None,
benchmark_rets=None,
slippage=None,
estimate_intraday='infer',
live_start... |
Generate a number of plots for analyzing a strategy s returns. | def create_returns_tear_sheet(returns, positions=None,
transactions=None,
live_start_date=None,
cone_std=(1.0, 1.5, 2.0),
benchmark_rets=None,
bootstrap=False,
... |
Generate a number of plots for analyzing a strategy s positions and holdings. | 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... |
Generate a number of plots for analyzing a strategy s transactions. | 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... |
Generate a number of figures and plots describing the duration frequency and profitability of trade round trips. A round trip is started when a new long or short position is opened and is only completed when the number of shares in that position returns to or crosses zero. | def create_round_trip_tear_sheet(returns, positions, transactions,
sector_mappings=None,
estimate_intraday='infer', return_fig=False):
"""
Generate a number of figures and plots describing the duration,
frequency, and profitability of trade "... |
Generate a number of returns plots around interesting points in time like the flash crash and 9/ 11. | def create_interesting_times_tear_sheet(
returns, benchmark_rets=None, legend_loc='best', return_fig=False):
"""
Generate a number of returns plots around interesting points in time,
like the flash crash and 9/11.
Plots: returns around the dotcom bubble burst, Lehmann Brothers' failure,
9/1... |
Generates a report detailing portfolio size constraints set by least liquid tickers. Plots a capacity sweep a curve describing projected sharpe ratio given the slippage penalties that are applied at various capital bases. | 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,
... |
Generate a number of Bayesian distributions and a Bayesian cone plot of returns. | def create_bayesian_tear_sheet(returns, benchmark_rets=None,
live_start_date=None, samples=2000,
return_fig=False, stoch_vol=False,
progressbar=True):
"""
Generate a number of Bayesian distributions and a Bayesian
c... |
Creates risk tear sheet: computes and plots style factor exposures sector exposures market cap exposures and volume exposures. | def create_risk_tear_sheet(positions,
style_factor_panel=None,
sectors=None,
caps=None,
shares_held=None,
volumes=None,
percentile=None,
... |
Generate plots and tables for analyzing a strategy s performance. | def create_perf_attrib_tear_sheet(returns,
positions,
factor_returns,
factor_loadings,
transactions=None,
pos_in_dollars=True,
... |
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. | 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 ... |
Compute the number of days that would have been required to fully liquidate each position on each day based on the trailing n day mean daily bar volume and a limit on the proportion of a daily bar that we are allowed to consume. | 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... |
Finds the longest estimated liquidation time for each traded name over the course of backtest ( or last n days of the backtest ). | def get_max_days_to_liquidate_by_ticker(positions, market_data,
max_bar_consumption=0.2,
capital_base=1e6,
mean_volume_window=5,
last_n_days=None):
"""
... |
For each traded name find the daily transaction total that consumed the greatest proportion of available daily bar volume. | 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
... |
Applies quadratic volumeshare slippage model to daily returns based on the proportion of the observed historical daily bar dollar volume consumed by the strategy s trades. Scales the size of trades based on the ratio of the starting capital we wish to test to the starting capital of the passed backtest data. | 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... |
Maps a single transaction row to a dictionary. | 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... |
Formats a transaction DataFrame. | 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... |
Extract daily transaction data from set of transaction objects. | 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.
... |
Apply a slippage penalty for every dollar traded. | 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... |
- Value of purchases and sales divided by either the actual gross book or the portfolio value for the time step. | 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.
-... |
Merge transactions of the same direction separated by less than max_delta time duration. | 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... |
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 computed. Crossings where a position changes from long to short and vice - versa are handled correctly. | 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... |
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. | 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... |
Translates round trip symbols to sectors. | 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... |
Generate various round - trip statistics. | 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... |
Print various round - trip statistics. Tries to pretty - print tables with HTML output if run inside IPython NB. | 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... |
Attributes the performance of a returns stream to a set of risk factors. | 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... |
Compute daily risk factor exposures. | 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
----------
... |
Takes perf attribution data over a period of time and computes annualized multifactor alpha multifactor sharpe risk exposures. | 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... |
Calls perf_attrib using inputs and displays outputs using utils. print_table. | 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... |
Plot total specific and common returns. | 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... |
Plot histogram of daily multi - factor alpha returns ( specific returns ). | def plot_alpha_returns(alpha_returns, ax=None):
"""
Plot histogram of daily multi-factor alpha returns (specific returns).
Parameters
----------
alpha_returns : pd.Series
series of daily alpha returns indexed by datetime
ax : matplotlib.axes.Axes
axes on which plots are made. ... |
Plot each factor s contribution to performance. | 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 ... |
Parameters ---------- exposures: pd. DataFrame df indexed by datetime with factors as columns - Example: momentum reversal dt 2017 - 01 - 01 - 0. 238655 0. 077123 2017 - 01 - 02 0. 821872 1. 520515 | def plot_risk_exposures(exposures, ax=None,
title='Daily risk factor exposures'):
"""
Parameters
----------
exposures : pd.DataFrame
df indexed by datetime, with factors as columns
- Example:
momentum reversal
dt
20... |
Make sure that all inputs have matching dates and tickers and raise warnings if necessary. | def _align_and_warn(returns,
positions,
factor_returns,
factor_loadings,
transactions=None,
pos_in_dollars=True):
"""
Make sure that all inputs have matching dates and tickers,
and raise warnings if necessary... |
Convert positions to percentages if necessary and change them to long format. | 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... |
Compute cumulative returns less costs. | def _cumulative_returns_less_costs(returns, costs):
"""
Compute cumulative returns, less costs.
"""
if costs is None:
return ep.cum_returns(returns)
return ep.cum_returns(returns - costs) |
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. | 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:
return asset
if isinstance(asset... |
Decorator so that functions can be written to work on Series but may still be called with DataFrames. | 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 func(df, *args, **kwargs)
elif df.ndim == 2:
return df.apply(func, *ar... |
Extract returns positions transactions and leverage from the backtest data structure returned by zipline. TradingAlgorithm. run (). | def extract_rets_pos_txn_from_zipline(backtest):
"""
Extract returns, positions, transactions and leverage from the
backtest data structure returned by zipline.TradingAlgorithm.run().
The returned data structures are in a format compatible with the
rest of pyfolio and can be directly passed to
... |
Pretty print a pandas DataFrame. | 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
-------... |
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 strategy is detected. | 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... |
Logic for checking if a strategy is intraday and processing it. | 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.
... |
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 with the positions at this point of day. The point of day is found by detecting when our expos... | 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... |
Drop entries from rets so that the start and end dates of rets match those of benchmark_rets. | 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 ... |
For use in tests ; applied UTC timestamp to DataFrame. | def to_utc(df):
"""
For use in tests; applied UTC timestamp to DataFrame.
"""
try:
df.index = df.index.tz_localize('UTC')
except TypeError:
df.index = df.index.tz_convert('UTC')
return df |
Calls the currently registered returns_func | 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
Earlies... |
Format legend for perf attribution plots: - put legend to the right of plot instead of overlapping with it - make legend order match up with graph lines - set colors according to colormap | def configure_legend(ax, autofmt_xdate=True, change_colors=False,
rotation=30, ha='right'):
"""
Format legend for perf attribution plots:
- put legend to the right of plot instead of overlapping with it
- make legend order match up with graph lines
- set colors according to colo... |
Sample a colormap from matplotlib | def sample_colormap(cmap_name, n_samples):
"""
Sample a colormap from matplotlib
"""
colors = []
colormap = cm.cmap_d[cmap_name]
for i in np.linspace(0, 1, n_samples):
colors.append(colormap(i))
return colors |
Decorator to set plotting context and axes style during function call. | def customize(func):
"""
Decorator to set plotting context and axes style during function call.
"""
@wraps(func)
def call_w_context(*args, **kwargs):
set_context = kwargs.pop('set_context', True)
if set_context:
with plotting_context(), axes_style():
retur... |
Create pyfolio default plotting style context. | 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... |
Create pyfolio default axes style context. | 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.
... |
Plots a heatmap of returns by month. | 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
... |
Plots a bar graph of returns by year. | def plot_annual_returns(returns, ax=None, **kwargs):
"""
Plots a bar graph of returns by year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional
... |
Plots a distribution of monthly returns. | def plot_monthly_returns_dist(returns, ax=None, **kwargs):
"""
Plots a distribution of monthly returns.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional... |
Plots total amount of stocks with an active position either short or long. Displays daily total daily average per month and all - time daily average. | def plot_holdings(returns, positions, legend_loc='best', ax=None, **kwargs):
"""
Plots total amount of stocks with an active position, either short
or long. Displays daily total, daily average per month, and
all-time daily average.
Parameters
----------
returns : pd.Series
Daily ret... |
Plots total amount of stocks with an active position breaking out short and long into transparent filled regions. | def plot_long_short_holdings(returns, positions,
legend_loc='upper left', ax=None, **kwargs):
"""
Plots total amount of stocks with an active position, breaking out
short and long into transparent filled regions.
Parameters
----------
returns : pd.Series
Dai... |
Plots cumulative returns highlighting top drawdown periods. | def plot_drawdown_periods(returns, top=10, ax=None, **kwargs):
"""
Plots cumulative returns highlighting top drawdown periods.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
top : i... |
Plots how far underwaterr returns are over time or plots current drawdown vs. date. | def plot_drawdown_underwater(returns, ax=None, **kwargs):
"""
Plots how far underwaterr returns are over time, or plots current
drawdown vs. date.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full... |
Create box plot of some performance metrics of the strategy. The width of the box whiskers is determined by a bootstrap. | def plot_perf_stats(returns, factor_returns, ax=None):
"""
Create box plot of some performance metrics of the strategy.
The width of the box whiskers is determined by a bootstrap.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full... |
Prints some performance metrics of the strategy. | def show_perf_stats(returns, factor_returns=None, positions=None,
transactions=None, turnover_denom='AGB',
live_start_date=None, bootstrap=False,
header_rows=None):
"""
Prints some performance metrics of the strategy.
- Shows amount of time the st... |
Plots raw returns over time. | def plot_returns(returns,
live_start_date=None,
ax=None):
"""
Plots raw returns over time.
Backtest returns are in green, and out-of-sample (live trading)
returns are in red.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, ... |
Plots cumulative rolling returns versus some benchmarks. | def plot_rolling_returns(returns,
factor_returns=None,
live_start_date=None,
logy=False,
cone_std=None,
legend_loc='best',
volatility_match=False,
... |
Plots the rolling 6 - month and 12 - month beta versus date. | def plot_rolling_beta(returns, factor_returns, legend_loc='best',
ax=None, **kwargs):
"""
Plots the rolling 6-month and 12-month beta versus date.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in... |
Plots the rolling volatility versus date. | def plot_rolling_volatility(returns, factor_returns=None,
rolling_window=APPROX_BDAYS_PER_MONTH * 6,
legend_loc='best', ax=None, **kwargs):
"""
Plots the rolling volatility versus date.
Parameters
----------
returns : pd.Series
Daily r... |
Plots the rolling Sharpe ratio versus date. | def plot_rolling_sharpe(returns, factor_returns=None,
rolling_window=APPROX_BDAYS_PER_MONTH * 6,
legend_loc='best', ax=None, **kwargs):
"""
Plots the rolling Sharpe ratio versus date.
Parameters
----------
returns : pd.Series
Daily returns of ... |
Plots gross leverage versus date. | def plot_gross_leverage(returns, positions, ax=None, **kwargs):
"""
Plots gross leverage versus date.
Gross leverage is the sum of long and short exposure per share
divided by net asset value.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
... |
Plots a cake chart of the long and short exposure. | def plot_exposures(returns, positions, ax=None, **kwargs):
"""
Plots a cake chart of the long and short exposure.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
positions_alloc : pd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.