INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Finds the N period forward returns (as percent change) for each asset provided. Parameters ---------- factor : pd.Series - MultiIndex A MultiIndex Series indexed by timestamp (level 0) and asset (level 1), containing the values for a single alpha factor. - See full explanation ...
def compute_forward_returns(factor, prices, periods=(1, 5, 10), filter_zscore=None, cumulative_returns=True): """ Finds the N period forward returns (as percent change) for each asset provided. ...
Convert forward returns to returns relative to mean period wise all-universe or group returns. group-wise normalization incorporates the assumption of a group neutral portfolio constraint and thus allows allows the factor to be evaluated across groups. For example, if AAPL 5 period return is 0.1% a...
def demean_forward_returns(factor_data, grouper=None): """ Convert forward returns to returns relative to mean period wise all-universe or group returns. group-wise normalization incorporates the assumption of a group neutral portfolio constraint and thus allows allows the factor to be evaluated...
Pretty print a pandas DataFrame. Uses HTML output if running inside Jupyter Notebook, otherwise formatted text output. Parameters ---------- table : pd.Series or pd.DataFrame Table to pretty-print. name : str, optional Table name to display in upper left corner. fmt : str, ...
def print_table(table, name=None, fmt=None): """ Pretty print a pandas DataFrame. Uses HTML output if running inside Jupyter Notebook, otherwise formatted text output. Parameters ---------- table : pd.Series or pd.DataFrame Table to pretty-print. name : str, optional Ta...
Formats the factor data, forward return data, and group mappings into a DataFrame that contains aligned MultiIndex indices of timestamp and asset. The returned data will be formatted to be suitable for Alphalens functions. It is safe to skip a call to this function and still make use of Alphalens funct...
def get_clean_factor(factor, forward_returns, groupby=None, binning_by_group=False, quantiles=5, bins=None, groupby_labels=None, max_loss=0.35, zero_awa...
Formats the factor data, pricing data, and group mappings into a DataFrame that contains aligned MultiIndex indices of timestamp and asset. The returned data will be formatted to be suitable for Alphalens functions. It is safe to skip a call to this function and still make use of Alphalens functionalit...
def get_clean_factor_and_forward_returns(factor, prices, groupby=None, binning_by_group=False, quantiles=5, bins=No...
Convert returns to 'one_period_len' rate of returns: that is the value the returns would have every 'one_period_len' if they had grown at a steady rate Parameters ---------- period_ret: pd.DataFrame DataFrame containing returns values with column headings representing the return per...
def rate_of_return(period_ret, base_period): """ Convert returns to 'one_period_len' rate of returns: that is the value the returns would have every 'one_period_len' if they had grown at a steady rate Parameters ---------- period_ret: pd.DataFrame DataFrame containing returns values...
one_period_len standard deviation (or standard error) approximation Parameters ---------- period_std: pd.DataFrame DataFrame containing standard deviation or standard error values with column headings representing the return period. base_period: string The base period length use...
def std_conversion(period_std, base_period): """ one_period_len standard deviation (or standard error) approximation Parameters ---------- period_std: pd.DataFrame DataFrame containing standard deviation or standard error values with column headings representing the return period. ...
Utility that detects and returns the columns that are forward returns
def get_forward_returns_columns(columns): """ Utility that detects and returns the columns that are forward returns """ pattern = re.compile(r"^(\d+([Dhms]|ms|us|ns))+$", re.IGNORECASE) valid_columns = [(pattern.match(col) is not None) for col in columns] return columns[valid_columns]
Utility that converts a pandas.Timedelta to a string representation compatible with pandas.Timedelta constructor format Parameters ---------- timedelta: pd.Timedelta Returns ------- string string representation of 'timedelta'
def timedelta_to_string(timedelta): """ Utility that converts a pandas.Timedelta to a string representation compatible with pandas.Timedelta constructor format Parameters ---------- timedelta: pd.Timedelta Returns ------- string string representation of 'timedelta' """ ...
Add timedelta to 'input' taking into consideration custom frequency, which is used to deal with custom calendars, such as a trading calendar Parameters ---------- input : pd.DatetimeIndex or pd.Timestamp timedelta : pd.Timedelta freq : pd.DataOffset (CustomBusinessDay, Day or BusinessDay) ...
def add_custom_calendar_timedelta(input, timedelta, freq): """ Add timedelta to 'input' taking into consideration custom frequency, which is used to deal with custom calendars, such as a trading calendar Parameters ---------- input : pd.DatetimeIndex or pd.Timestamp timedelta : pd.Timedelta...
Compute the difference between two pd.Timedelta taking into consideration custom frequency, which is used to deal with custom calendars, such as a trading calendar Parameters ---------- start : pd.Timestamp end : pd.Timestamp freq : CustomBusinessDay (see infer_trading_calendar) freq : ...
def diff_custom_calendar_timedeltas(start, end, freq): """ Compute the difference between two pd.Timedelta taking into consideration custom frequency, which is used to deal with custom calendars, such as a trading calendar Parameters ---------- start : pd.Timestamp end : pd.Timestamp ...
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: color_palette = sns.color_palette('colorblind') ...
Plots Spearman Rank Information Coefficient and IC moving average for a given factor. Parameters ---------- ic : pd.DataFrame DataFrame indexed by date, with IC for each forward return. ax : matplotlib.Axes, optional Axes upon which to plot. Returns ------- ax : matplot...
def plot_ic_ts(ic, ax=None): """ Plots Spearman Rank Information Coefficient and IC moving average for a given factor. Parameters ---------- ic : pd.DataFrame DataFrame indexed by date, with IC for each forward return. ax : matplotlib.Axes, optional Axes upon which to plot. ...
Plots Spearman Rank Information Coefficient histogram for a given factor. Parameters ---------- ic : pd.DataFrame DataFrame indexed by date, with IC for each forward return. ax : matplotlib.Axes, optional Axes upon which to plot. Returns ------- ax : matplotlib.Axes ...
def plot_ic_hist(ic, ax=None): """ Plots Spearman Rank Information Coefficient histogram for a given factor. Parameters ---------- ic : pd.DataFrame DataFrame indexed by date, with IC for each forward return. ax : matplotlib.Axes, optional Axes upon which to plot. Returns ...
Plots Spearman Rank Information Coefficient "Q-Q" plot relative to a theoretical distribution. Parameters ---------- ic : pd.DataFrame DataFrame indexed by date, with IC for each forward return. theoretical_dist : scipy.stats._continuous_distns Continuous distribution generator. sci...
def plot_ic_qq(ic, theoretical_dist=stats.norm, ax=None): """ Plots Spearman Rank Information Coefficient "Q-Q" plot relative to a theoretical distribution. Parameters ---------- ic : pd.DataFrame DataFrame indexed by date, with IC for each forward return. theoretical_dist : scipy.s...
Plots mean period wise returns for factor quantiles. Parameters ---------- mean_ret_by_q : pd.DataFrame DataFrame with quantile, (group) and mean period wise return values. by_group : bool Disaggregated figures by group. ylim_percentiles : tuple of integers Percentiles of ob...
def plot_quantile_returns_bar(mean_ret_by_q, by_group=False, ylim_percentiles=None, ax=None): """ Plots mean period wise returns for factor quantiles. Parameters ---------- mean_ret_by_q : pd.DataFrame ...
Plots a violin box plot of period wise returns for factor quantiles. Parameters ---------- return_by_q : pd.DataFrame - MultiIndex DataFrame with date and quantile as rows MultiIndex, forward return windows as columns, returns as values. ylim_percentiles : tuple of integers Perc...
def plot_quantile_returns_violin(return_by_q, ylim_percentiles=None, ax=None): """ Plots a violin box plot of period wise returns for factor quantiles. Parameters ---------- return_by_q : pd.DataFrame - MultiIndex DataFrame w...
Plots mean period wise returns for factor quantiles. Parameters ---------- mean_returns_spread : pd.Series Series with difference between quantile mean returns by period. std_err : pd.Series Series with standard error of difference between quantile mean returns each period. ...
def plot_mean_quantile_returns_spread_time_series(mean_returns_spread, std_err=None, bandwidth=1, ax=None): """ Plots mean period wise returns for factor quantile...
Plots Spearman Rank Information Coefficient for a given factor over provided forward returns. Separates by group. Parameters ---------- ic_group : pd.DataFrame group-wise mean period wise returns. ax : matplotlib.Axes, optional Axes upon which to plot. Returns ------- a...
def plot_ic_by_group(ic_group, ax=None): """ Plots Spearman Rank Information Coefficient for a given factor over provided forward returns. Separates by group. Parameters ---------- ic_group : pd.DataFrame group-wise mean period wise returns. ax : matplotlib.Axes, optional Ax...
Plots factor rank autocorrelation over time. See factor_rank_autocorrelation for more details. Parameters ---------- factor_autocorrelation : pd.Series Rolling 1 period (defined by time_rule) autocorrelation of factor values. period: int, optional Period over which the autoc...
def plot_factor_rank_auto_correlation(factor_autocorrelation, period=1, ax=None): """ Plots factor rank autocorrelation over time. See factor_rank_autocorrelation for more details. Parameters ---------- factor_autocorre...
Plots period wise top and bottom quantile factor turnover. Parameters ---------- quantile_turnover: pd.Dataframe Quantile turnover (each DataFrame column a quantile). period: int, optional Period over which to calculate the turnover ax : matplotlib.Axes, optional Axes upon w...
def plot_top_bottom_quantile_turnover(quantile_turnover, period=1, ax=None): """ Plots period wise top and bottom quantile factor turnover. Parameters ---------- quantile_turnover: pd.Dataframe Quantile turnover (each DataFrame column a quantile). period: int, optional Period ov...
Plots a heatmap of the information coefficient or returns by month. Parameters ---------- mean_monthly_ic : pd.DataFrame The mean monthly IC for N periods forward. Returns ------- ax : matplotlib.Axes The axes that were plotted on.
def plot_monthly_ic_heatmap(mean_monthly_ic, ax=None): """ Plots a heatmap of the information coefficient or returns by month. Parameters ---------- mean_monthly_ic : pd.DataFrame The mean monthly IC for N periods forward. Returns ------- ax : matplotlib.Axes The axes t...
Plots the cumulative returns of the returns series passed in. Parameters ---------- factor_returns : pd.Series Period wise returns of dollar neutral portfolio weighted by factor value. period: pandas.Timedelta or string Length of period for which the returns are computed (e.g. 1...
def plot_cumulative_returns(factor_returns, period, freq, title=None, ax=None): """ Plots the cumulative returns of the returns series passed in. Parameters ---------- factor_returns : pd.Series Period wise returns of dollar neutral portfolio weighted by factor value. period: pa...
Plots the cumulative returns of various factor quantiles. Parameters ---------- quantile_returns : pd.DataFrame Returns by factor quantile period: pandas.Timedelta or string Length of period for which the returns are computed (e.g. 1 day) if 'period' is a string it must follow p...
def plot_cumulative_returns_by_quantile(quantile_returns, period, freq, ax=None): """ Plots the cumulative returns of various factor quantiles. Parameters ---------- quantile_retu...
Plots sector-wise mean daily returns for factor quantiles across provided forward price movement columns. Parameters ---------- avg_cumulative_returns: pd.Dataframe The format is the one returned by performance.average_cumulative_return_by_quantile by_quantile : boolean, optional ...
def plot_quantile_average_cumulative_return(avg_cumulative_returns, by_quantile=False, std_bar=False, title=None, ax=None): """ Plots se...
Plots the distribution of events in time. Parameters ---------- events : pd.Series A pd.Series whose index contains at least 'date' level. num_bars : integer, optional Number of bars to plot ax : matplotlib.Axes, optional Axes upon which to plot. Returns ------- ...
def plot_events_distribution(events, num_bars=50, ax=None): """ Plots the distribution of events in time. Parameters ---------- events : pd.Series A pd.Series whose index contains at least 'date' level. num_bars : integer, optional Number of bars to plot ax : matplotlib.Axes...
Closing a cursor just exhausts all remaining data.
def close(self): """ Closing a cursor just exhausts all remaining data. """ conn = self.connection if conn is None: return try: while self.nextset(): pass finally: self.connection = None
Get the next query set
def _nextset(self, unbuffered=False): """Get the next query set""" conn = self._get_db() current_result = self._result if current_result is None or current_result is not conn._result: return None if not current_result.has_next: return None self._re...
Returns the exact string that is sent to the database by calling the execute() method. This method follows the extension to the DB API 2.0 followed by Psycopg.
def mogrify(self, query, args=None): """ Returns the exact string that is sent to the database by calling the execute() method. This method follows the extension to the DB API 2.0 followed by Psycopg. """ conn = self._get_db() if PY2: # Use bytes on Python 2 alw...
Execute a query :param str query: Query to execute. :param args: parameters used with query. (optional) :type args: tuple, list or dict :return: Number of affected rows :rtype: int If args is a list or tuple, %s can be used as a placeholder in the query. If ar...
def execute(self, query, args=None): """Execute a query :param str query: Query to execute. :param args: parameters used with query. (optional) :type args: tuple, list or dict :return: Number of affected rows :rtype: int If args is a list or tuple, %s can be u...
Execute stored procedure procname with args procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any modified parameters must be returned. This ...
def callproc(self, procname, args=()): """Execute stored procedure procname with args procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any m...
Fetch the next row
def fetchone(self): """Fetch the next row""" self._check_executed() if self._rows is None or self.rownumber >= len(self._rows): return None result = self._rows[self.rownumber] self.rownumber += 1 return result
Fetch several rows
def fetchmany(self, size=None): """Fetch several rows""" self._check_executed() if self._rows is None: return () end = self.rownumber + (size or self.arraysize) result = self._rows[self.rownumber:end] self.rownumber = min(end, len(self._rows)) return r...
Fetch all the rows
def fetchall(self): """Fetch all the rows""" self._check_executed() if self._rows is None: return () if self.rownumber: result = self._rows[self.rownumber:] else: result = self._rows self.rownumber = len(self._rows) return resul...
Fetch next row
def fetchone(self): """Fetch next row""" self._check_executed() row = self.read_next() if row is None: return None self.rownumber += 1 return row
Fetch many
def fetchmany(self, size=None): """Fetch many""" self._check_executed() if size is None: size = self.arraysize rows = [] for i in range_type(size): row = self.read_next() if row is None: break rows.append(row) ...
Returns a DATETIME or TIMESTAMP column value as a datetime object: >>> datetime_or_None('2007-02-25 23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) >>> datetime_or_None('2007-02-25T23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) Illegal values are returned as None: >>> dat...
def convert_datetime(obj): """Returns a DATETIME or TIMESTAMP column value as a datetime object: >>> datetime_or_None('2007-02-25 23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) >>> datetime_or_None('2007-02-25T23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) Illegal values ar...
Returns a TIME column as a timedelta object: >>> timedelta_or_None('25:06:17') datetime.timedelta(1, 3977) >>> timedelta_or_None('-25:06:17') datetime.timedelta(-2, 83177) Illegal values are returned as None: >>> timedelta_or_None('random crap') is None True Note that MyS...
def convert_timedelta(obj): """Returns a TIME column as a timedelta object: >>> timedelta_or_None('25:06:17') datetime.timedelta(1, 3977) >>> timedelta_or_None('-25:06:17') datetime.timedelta(-2, 83177) Illegal values are returned as None: >>> timedelta_or_None('random crap') is...
Returns a DATE column as a date object: >>> date_or_None('2007-02-26') datetime.date(2007, 2, 26) Illegal values are returned as None: >>> date_or_None('2007-02-31') is None True >>> date_or_None('0000-00-00') is None True
def convert_date(obj): """Returns a DATE column as a date object: >>> date_or_None('2007-02-26') datetime.date(2007, 2, 26) Illegal values are returned as None: >>> date_or_None('2007-02-31') is None True >>> date_or_None('0000-00-00') is None True """ if not PY2 ...
Write the given bytes or bytearray object *b* to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned.
def write(self, b): """Write the given bytes or bytearray object *b* to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned. """ se...
Close the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared.
def close(self): """Close the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared. """ if self.closed: return io.RawIOBase.close(self) self._sock._decref_socketios() self._sock = None
Read the first 'size' bytes in packet and advance cursor past them.
def read(self, size): """Read the first 'size' bytes in packet and advance cursor past them.""" result = self._data[self._position:(self._position+size)] if len(result) != size: error = ('Result length not requested length:\n' 'Expected=%s. Actual=%s. Position:...
Read all remaining data in the packet. (Subsequent read() will return errors.)
def read_all(self): """Read all remaining data in the packet. (Subsequent read() will return errors.) """ result = self._data[self._position:] self._position = None # ensure no subsequent read() return result
Advance the cursor in data buffer 'length' bytes.
def advance(self, length): """Advance the cursor in data buffer 'length' bytes.""" new_position = self._position + length if new_position < 0 or new_position > len(self._data): raise Exception('Invalid advance amount (%s) for cursor. ' 'Position=%s' % (le...
Set the position of the data buffer cursor to 'position'.
def rewind(self, position=0): """Set the position of the data buffer cursor to 'position'.""" if position < 0 or position > len(self._data): raise Exception("Invalid position to rewind cursor to: %s." % position) self._position = position
Read a 'Length Coded Binary' number from the data buffer. Length coded numbers can be anywhere from 1 to 9 bytes depending on the value of the first byte.
def read_length_encoded_integer(self): """Read a 'Length Coded Binary' number from the data buffer. Length coded numbers can be anywhere from 1 to 9 bytes depending on the value of the first byte. """ c = self.read_uint8() if c == NULL_COLUMN: return None ...
Parse the 'Field Descriptor' (Metadata) packet. This is compatible with MySQL 4.1+ (not compatible with MySQL 4.0).
def _parse_field_descriptor(self, encoding): """Parse the 'Field Descriptor' (Metadata) packet. This is compatible with MySQL 4.1+ (not compatible with MySQL 4.0). """ self.catalog = self.read_length_coded_string() self.db = self.read_length_coded_string() self.table_nam...
Provides a 7-item tuple compatible with the Python PEP249 DB Spec.
def description(self): """Provides a 7-item tuple compatible with the Python PEP249 DB Spec.""" return ( self.name, self.type_code, None, # TODO: display_length; should this be self.length? self.get_column_length(), # 'internal_size' self.get...
Send the quit message and close the socket. See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_ in the specification. :raise Error: If the connection is already closed.
def close(self): """ Send the quit message and close the socket. See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_ in the specification. :raise Error: If the connection is already closed. """ if self._closed: rais...
Close connection without QUIT message
def _force_close(self): """Close connection without QUIT message""" if self._sock: try: self._sock.close() except: # noqa pass self._sock = None self._rfile = None
Set whether or not to commit after every execute()
def _send_autocommit_mode(self): """Set whether or not to commit after every execute()""" self._execute_command(COMMAND.COM_QUERY, "SET AUTOCOMMIT = %s" % self.escape(self.autocommit_mode)) self._read_ok_packet()
Escape whatever value you pass to it. Non-standard, for internal use; do not use this in your applications.
def escape(self, obj, mapping=None): """Escape whatever value you pass to it. Non-standard, for internal use; do not use this in your applications. """ if isinstance(obj, str_type): return "'" + self.escape_string(obj) + "'" if isinstance(obj, (bytes, bytearray)): ...
Check if the server is alive. :param reconnect: If the connection is closed, reconnect. :raise Error: If the connection is closed and reconnect=False.
def ping(self, reconnect=True): """ Check if the server is alive. :param reconnect: If the connection is closed, reconnect. :raise Error: If the connection is closed and reconnect=False. """ if self._sock is None: if reconnect: self.connect() ...
Read an entire "mysql packet" in its entirety from the network and return a MysqlPacket type that represents the results. :raise OperationalError: If the connection to the MySQL server is lost. :raise InternalError: If the packet sequence number is wrong.
def _read_packet(self, packet_type=MysqlPacket): """Read an entire "mysql packet" in its entirety from the network and return a MysqlPacket type that represents the results. :raise OperationalError: If the connection to the MySQL server is lost. :raise InternalError: If the packet seque...
:raise InterfaceError: If the connection is closed. :raise ValueError: If no username was specified.
def _execute_command(self, command, sql): """ :raise InterfaceError: If the connection is closed. :raise ValueError: If no username was specified. """ if not self._sock: raise err.InterfaceError("(0, '')") # If the last query was unbuffered, make sure it fini...
Send data packets from the local file to the server
def send_data(self): """Send data packets from the local file to the server""" if not self.connection._sock: raise err.InterfaceError("(0, '')") conn = self.connection try: with open(self.filename, 'rb') as open_file: packet_size = min(conn.max_al...
Scramble used for mysql_native_password
def scramble_native_password(password, message): """Scramble used for mysql_native_password""" if not password: return b'' stage1 = sha1_new(password).digest() stage2 = sha1_new(stage1).digest() s = sha1_new() s.update(message[:SCRAMBLE_LENGTH]) s.update(stage2) result = s.diges...
Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password.
def sha2_rsa_encrypt(password, salt, public_key): """Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password. """ if not _have_cryptography: raise RuntimeError("'cryptography' package is required for sha256_password or caching_sha2_password auth methods") ...
Scramble algorithm used in cached_sha2_password fast path. XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce))
def scramble_caching_sha2(password, nonce): # (bytes, bytes) -> bytes """Scramble algorithm used in cached_sha2_password fast path. XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce)) """ if not password: return b'' p1 = hashlib.sha256(password).digest() p2 = hashlib.sha...
Model factory for the transitive closure extension.
def ClosureTable(model_class, foreign_key=None, referencing_class=None, referencing_key=None): """Model factory for the transitive closure extension.""" if referencing_class is None: referencing_class = model_class if foreign_key is None: for field_obj in model_class._meta....
Usage: # Format string *must* be pcnalx # Second parameter to bm25 specifies the index of the column, on # the table being queries. bm25(matchinfo(document_tbl, 'pcnalx'), 1) AS rank
def bm25(raw_match_info, *args): """ Usage: # Format string *must* be pcnalx # Second parameter to bm25 specifies the index of the column, on # the table being queries. bm25(matchinfo(document_tbl, 'pcnalx'), 1) AS rank """ match_info = _parse_match_info(raw_match_info) ...
Full-text search using selected `term`.
def search(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" return cls._search( term, weights, with_score, score_alias, cls.rank, ...
Full-text search for selected `term` using BM25 algorithm.
def search_bm25(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
Full-text search for selected `term` using BM25 algorithm.
def search_bm25f(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
Full-text search for selected `term` using BM25 algorithm.
def search_lucene(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
Simple helper function to indicate whether a search query is a valid FTS5 query. Note: this simply looks at the characters being used, and is not guaranteed to catch all problematic queries.
def validate_query(query): """ Simple helper function to indicate whether a search query is a valid FTS5 query. Note: this simply looks at the characters being used, and is not guaranteed to catch all problematic queries. """ tokens = _quote_re.findall(query) for ...
Clean a query of invalid tokens.
def clean_query(query, replace=chr(26)): """ Clean a query of invalid tokens. """ accum = [] any_invalid = False tokens = _quote_re.findall(query) for token in tokens: if token.startswith('"') and token.endswith('"'): accum.append(token...
Full-text search using selected `term`.
def search(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" return cls.search_bm25( FTS5Model.clean_query(term), weights, with_score, score_alias, ...
Full-text search using selected `term`.
def search_bm25(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" if not weights: rank = SQL('rank') elif isinstance(weights, dict): weight_args = [] for ...
Close the underlying connection without returning it to the pool.
def manual_close(self): """ Close the underlying connection without returning it to the pool. """ if self.is_closed(): return False # Obtain reference to the connection in-use by the calling thread. conn = self.connection() # A connection will only b...
Get a breakdown of top pages per interval, i.e. day url count 2014-01-01 /blog/ 11 2014-01-02 /blog/ 14 2014-01-03 /blog/ 9
def top_pages_by_time_period(self, interval='day'): """ Get a breakdown of top pages per interval, i.e. day url count 2014-01-01 /blog/ 11 2014-01-02 /blog/ 14 2014-01-03 /blog/ 9 """ date_trunc = fn.date_trunc(interval, PageView.timesta...
Retrieve the cookies header from all the users who visited.
def cookies(self): """ Retrieve the cookies header from all the users who visited. """ return (self.get_query() .select(PageView.ip, PageView.headers['Cookie']) .where(PageView.headers['Cookie'].is_null(False)) .tuples())
Retrieve user-agents, sorted by most common to least common.
def user_agents(self): """ Retrieve user-agents, sorted by most common to least common. """ return (self.get_query() .select( PageView.headers['User-Agent'], fn.Count(PageView.id)) .group_by(PageView.headers['User-Ag...
Retrieve languages, sorted by most common to least common. The Accept-Languages header sometimes looks weird, i.e. "en-US,en;q=0.8,is;q=0.6,da;q=0.4" We will split on the first semi- colon.
def languages(self): """ Retrieve languages, sorted by most common to least common. The Accept-Languages header sometimes looks weird, i.e. "en-US,en;q=0.8,is;q=0.6,da;q=0.4" We will split on the first semi- colon. """ language = PageView.headers['Accept-Language'...
Get all visitors by IP and then list the pages they visited in order.
def trail(self): """ Get all visitors by IP and then list the pages they visited in order. """ inner = (self.get_query() .select(PageView.ip, PageView.url) .order_by(PageView.timestamp)) return (PageView .select( ...
What domains send us the most traffic?
def top_referrers(self, domain_only=True): """ What domains send us the most traffic? """ referrer = self._referrer_clause(domain_only) return (self.get_query() .select(referrer, fn.Count(PageView.id)) .group_by(referrer) .order_by(...
Add entry
def add_entry(): """Add entry""" print('Enter your entry. Press ctrl+d when finished.') data = sys.stdin.read().strip() if data and raw_input('Save entry? [Yn] ') != 'n': Entry.create(content=data) print('Saved successfully.')
View previous entries
def view_entries(search_query=None): """View previous entries""" query = Entry.select().order_by(Entry.timestamp.desc()) if search_query: query = query.where(Entry.content.contains(search_query)) for entry in query: timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:%M%p') pr...
Generate HTML representation of the markdown-formatted blog entry, and also convert any media URLs into rich media objects such as video players or images.
def html_content(self): """ Generate HTML representation of the markdown-formatted blog entry, and also convert any media URLs into rich media objects such as video players or images. """ hilite = CodeHiliteExtension(linenums=False, css_class='highlight') extras =...
Convert a model instance (and any related objects) to a dictionary. :param bool recurse: Whether foreign-keys should be recursed. :param bool backrefs: Whether lists of related objects should be recursed. :param only: A list (or set) of field instances indicating which fields should be included. ...
def model_to_dict(model, recurse=True, backrefs=False, only=None, exclude=None, seen=None, extra_attrs=None, fields_from_query=None, max_depth=None, manytomany=False): """ Convert a model instance (and any related objects) to a dictionary. :param bool recurse: Whether fo...
Lightweight factory which returns a method that builds an Expression consisting of the left-hand and right-hand operands, using `op`.
def _e(op, inv=False): """ Lightweight factory which returns a method that builds an Expression consisting of the left-hand and right-hand operands, using `op`. """ def inner(self, rhs): if inv: return Expression(rhs, op, self) return Expre...
Returns the intraday exchange rate for any pair of physical currency (e.g., EUR) or physical currency (e.g., USD). Keyword Arguments: from_symbol: The currency you would like to get the exchange rate for. For example: from_currency=EUR or from_currency=USD. ...
def get_currency_exchange_intraday(self, from_symbol, to_symbol, interval='15min', outputsize='compact'): """ Returns the intraday exchange rate for any pair of physical currency (e.g., EUR) or physical currency (e.g., USD). Keyword Arguments: from_symbol: The currency you would lik...
Decorator for forming the api call with the arguments of the function, it works by taking the arguments given to the function and building the url to call the api on it Keyword Arguments: func: The function to be decorated
def _call_api_on_func(cls, func): """ Decorator for forming the api call with the arguments of the function, it works by taking the arguments given to the function and building the url to call the api on it Keyword Arguments: func: The function to be decorated """ ...
Decorator in charge of giving the output its right format, either json or pandas Keyword Arguments: func: The function to be decorated override: Override the internal format of the call, default None
def _output_format(cls, func, override=None): """ Decorator in charge of giving the output its right format, either json or pandas Keyword Arguments: func: The function to be decorated override: Override the internal format of the call, default None """ ...
Convert to the alpha vantage math type integer. It returns an integer correspondent to the type of math to apply to a function. It raises ValueError if an integer greater than the supported math types is given. Keyword Arguments: matype: The math type of the alpha vantage a...
def map_to_matype(self, matype): """ Convert to the alpha vantage math type integer. It returns an integer correspondent to the type of math to apply to a function. It raises ValueError if an integer greater than the supported math types is given. Keyword Arguments: ...
Decorator in charge of giving the output its right format, either json or pandas (replacing the % for usable floats, range 0-1.0) Keyword Arguments: func: The function to be decorated override: Override the internal format of the call, default None Returns: A...
def _output_format_sector(func, override=None): """ Decorator in charge of giving the output its right format, either json or pandas (replacing the % for usable floats, range 0-1.0) Keyword Arguments: func: The function to be decorated override: Override the internal for...
Return the moving average convergence/divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive ...
def get_macd(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, signalperiod=None): """ Return the moving average convergence/divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise K...
Return the moving average convergence/divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive ...
def get_macdext(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, signalperiod=None, fastmatype=None, slowmatype=None, signalmatype=None): """ Return the moving average convergence/divergence time series in two json objects as ...
Return the stochatic oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, ...
def get_stoch(self, symbol, interval='daily', fastkperiod=None, slowkperiod=None, slowdperiod=None, slowkmatype=None, slowdmatype=None): """ Return the stochatic oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keywo...
Return the stochatic relative strength index in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, ...
def get_stochrsi(self, symbol, interval='daily', time_period=20, series_type='close', fastkperiod=None, fastdperiod=None, fastdmatype=None): """ Return the stochatic relative strength index in two json objects as data and meta_data. It raises ValueError when problems arise ...
Return the absolute price oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, ...
def get_apo(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, matype=None): """ Return the absolute price oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: ...
Return the bollinger bands values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, sup...
def get_bbands(self, symbol, interval='daily', time_period=20, series_type='close', nbdevup=None, nbdevdn=None, matype=None): """ Return the bollinger bands values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: ...
Return a three tuple of data, code, and headers
def unpack(value): """Return a three tuple of data, code, and headers""" if not isinstance(value, tuple): return value, 200, {} try: data, code, headers = value return data, code, headers except ValueError: pass try: data, code = value return data, c...
Makes a Flask response with a XML encoded body
def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" resp = make_response(dumps({'response' :data}), code) resp.headers.extend(headers or {}) return resp
Makes a Flask response with a JSON encoded body
def output_json(data, code, headers=None): """Makes a Flask response with a JSON encoded body""" settings = current_app.config.get('RESTFUL_JSON', {}) # If we're in debug mode, and the indent is not set, we set it to a # reasonable value here. Note that this won't override any existing value # th...
Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing.
def abort(http_status_code, **kwargs): """Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing. """ #noinspection PyUnresolvedReferences try: original_flask_abort(http_status_code) except HTTPException as e: if l...
Takes raw data (in the form of a dict, list, object) and a dict of fields to output and filters the data based on those fields. :param data: the actual object(s) from which the fields are taken from :param fields: a dict of whose keys will make up the final serialized response output ...
def marshal(data, fields, envelope=None): """Takes raw data (in the form of a dict, list, object) and a dict of fields to output and filters the data based on those fields. :param data: the actual object(s) from which the fields are taken from :param fields: a dict of whose keys will make up the final ...
Initialize this class with the given :class:`flask.Flask` application or :class:`flask.Blueprint` object. :param app: the Flask application or blueprint object :type app: flask.Flask :type app: flask.Blueprint Examples:: api = Api() api.add_resource(......
def init_app(self, app): """Initialize this class with the given :class:`flask.Flask` application or :class:`flask.Blueprint` object. :param app: the Flask application or blueprint object :type app: flask.Flask :type app: flask.Blueprint Examples:: api = Ap...
This method is used to defer the construction of the final url in the case that the Api is created with a Blueprint. :param url_part: The part of the url the endpoint is registered with :param registration_prefix: The part of the url contributed by the blueprint. Generally speaking...
def _complete_url(self, url_part, registration_prefix): """This method is used to defer the construction of the final url in the case that the Api is created with a Blueprint. :param url_part: The part of the url the endpoint is registered with :param registration_prefix: The part of th...
Perform initialization actions with the given :class:`flask.Flask` object. :param app: The flask application object :type app: flask.Flask
def _init_app(self, app): """Perform initialization actions with the given :class:`flask.Flask` object. :param app: The flask application object :type app: flask.Flask """ app.handle_exception = partial(self.error_router, app.handle_exception) app.handle_user_exc...