Search is not available for this dataset
text
stringlengths
75
104k
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...
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...
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...
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 ...
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...
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 = [] ...
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("/")))
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...
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: ...
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...
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...
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...
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...
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 -----...
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...
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...
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...
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 ...
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...
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...
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 ...
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...
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...
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 ...
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...
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). "...
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...
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...
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...
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 ...
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 ...
def create_full_tear_sheet(returns, positions=None, transactions=None, market_data=None, benchmark_rets=None, slippage=None, live_start_date=None, ...
def create_simple_tear_sheet(returns, positions=None, transactions=None, benchmark_rets=None, slippage=None, estimate_intraday='infer', live_start...
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, ...
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...
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...
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 "...
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...
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, ...
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...
def create_risk_tear_sheet(positions, style_factor_panel=None, sectors=None, caps=None, shares_held=None, volumes=None, percentile=None, ...
def create_perf_attrib_tear_sheet(returns, positions, factor_returns, factor_loadings, transactions=None, pos_in_dollars=True, ...
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 ...
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...
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): """ ...
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 ...
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...
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...
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...
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. ...
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...
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. -...
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...
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...
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...
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...
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...
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...
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...
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 ---------- ...
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...
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...
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...
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. ...
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 ...
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...
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...
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...
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)
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...
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...
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 ...
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 -------...
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...
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. ...
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...
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 ...
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
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...
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...
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
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...
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...
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. ...
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 ...
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 ...
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...
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...
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...
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...
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...
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...
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...
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, ...
def plot_rolling_returns(returns, factor_returns=None, live_start_date=None, logy=False, cone_std=None, legend_loc='best', volatility_match=False, ...
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...
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...
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 ...
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. ...
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...