INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Same as extract but return the result as a pandas DataFrame.
def df(self, topic: str, parseNumbers=True): """ Same as extract but return the result as a pandas DataFrame. """ return util.df(self.extract(topic, parseNumbers))
Download report for the given token and queryId.
def download(self, token, queryId): """ Download report for the given ``token`` and ``queryId``. """ url = ( 'https://gdcdyn.interactivebrokers.com' f'/Universal/servlet/FlexStatementService.SendRequest?' f't={token}&q={queryId}&v=3') ...
Load report from XML file.
def load(self, path): """ Load report from XML file. """ with open(path, 'rb') as f: self.data = f.read() self.root = et.fromstring(self.data)
Save report to XML file.
def save(self, path): """ Save report to XML file. """ with open(path, 'wb') as f: f.write(self.data)
Create and a return a specialized contract based on the given secType or a general Contract if secType is not given.
def create(**kwargs): """ Create and a return a specialized contract based on the given secType, or a general Contract if secType is not given. """ secType = kwargs.get('secType', '') cls = { '': Contract, 'STK': Stock, 'OPT': Option, ...
See if this ticker has a valid bid and ask.
def hasBidAsk(self) -> bool: """ See if this ticker has a valid bid and ask. """ return ( self.bid != -1 and not isNan(self.bid) and self.bidSize > 0 and self.ask != -1 and not isNan(self.ask) and self.askSize > 0)
Return average of bid and ask or NaN if no valid bid and ask are available.
def midpoint(self) -> float: """ Return average of bid and ask, or NaN if no valid bid and ask are available. """ return (self.bid + self.ask) / 2 if self.hasBidAsk() else nan
Return the first available one of
def marketPrice(self) -> float: """ Return the first available one of * last price if within current bid/ask; * average of bid and ask (midpoint); * close price. """ price = self.last if ( self.hasBidAsk() and self.bid <= self.last <= self.ask) else \...
To add keywords from a file
def add_keyword_from_file(self, keyword_file, encoding="utf-8"): """To add keywords from a file Args: keyword_file : path to keywords file encoding : specify the encoding of the file Examples: keywords file format can be like: >>> # Option 1: ke...
To add keywords from a dictionary
def add_keywords_from_dict(self, keyword_dict): """To add keywords from a dictionary Args: keyword_dict (dict): A dictionary with `str` key and (list `str`) as value Examples: >>> keyword_dict = { "java": ["java_2e", "java programing"], ...
To remove keywords from a dictionary
def remove_keywords_from_dict(self, keyword_dict): """To remove keywords from a dictionary Args: keyword_dict (dict): A dictionary with `str` key and (list `str`) as value Examples: >>> keyword_dict = { "java": ["java_2e", "java programing"], ...
To add keywords from a list
def add_keywords_from_list(self, keyword_list): """To add keywords from a list Args: keyword_list (list(str)): List of keywords to add Examples: >>> keyword_processor.add_keywords_from_list(["java", "python"]}) Raises: AttributeError: If `keyword_lis...
To remove keywords present in list
def remove_keywords_from_list(self, keyword_list): """To remove keywords present in list Args: keyword_list (list(str)): List of keywords to remove Examples: >>> keyword_processor.remove_keywords_from_list(["java", "python"]}) Raises: AttributeError:...
Recursively builds a dictionary of keywords present in the dictionary And the clean name mapped to those keywords.
def get_all_keywords(self, term_so_far='', current_dict=None): """Recursively builds a dictionary of keywords present in the dictionary And the clean name mapped to those keywords. Args: term_so_far : string term built so far by adding all previous characters ...
Searches in the string for all keywords present in corpus. Keywords present are added to a list keywords_extracted and returned.
def extract_keywords(self, sentence, span_info=False): """Searches in the string for all keywords present in corpus. Keywords present are added to a list `keywords_extracted` and returned. Args: sentence (str): Line of text where we will search for keywords Returns: ...
Searches in the string for all keywords present in corpus. Keywords present are replaced by the clean name and a new string is returned.
def replace_keywords(self, sentence): """Searches in the string for all keywords present in corpus. Keywords present are replaced by the clean name and a new string is returned. Args: sentence (str): Line of text where we will replace keywords Returns: new_sente...
Computes the Spearman Rank Correlation based Information Coefficient ( IC ) between factor values and N period forward returns for each period in the factor index.
def factor_information_coefficient(factor_data, group_adjust=False, by_group=False): """ Computes the Spearman Rank Correlation based Information Coefficient (IC) between factor values and N period forward returns for each period in t...
Get the mean information coefficient of specified groups. Answers questions like: What is the mean IC for each month? What is the mean IC for each group for our whole timerange? What is the mean IC for for each group each week?
def mean_information_coefficient(factor_data, group_adjust=False, by_group=False, by_time=None): """ Get the mean information coefficient of specified groups. Answers questions like: What is the mean IC fo...
Computes asset weights by factor values and dividing by the sum of their absolute value ( achieving gross leverage of 1 ). Positive factor values will results in positive weights and negative values in negative weights.
def factor_weights(factor_data, demeaned=True, group_adjust=False, equal_weight=False): """ Computes asset weights by factor values and dividing by the sum of their absolute value (achieving gross leverage of 1). Positive factor values will result...
Computes period wise returns for portfolio weighted by factor values.
def factor_returns(factor_data, demeaned=True, group_adjust=False, equal_weight=False, by_asset=False): """ Computes period wise returns for portfolio weighted by factor values. Parameters ---------- factor_data : pd.Da...
Compute the alpha ( excess returns ) alpha t - stat ( alpha significance ) and beta ( market exposure ) of a factor. A regression is run with the period wise factor universe mean return as the independent variable and mean period wise return from a portfolio weighted by factor values as the dependent variable.
def factor_alpha_beta(factor_data, returns=None, demeaned=True, group_adjust=False, equal_weight=False): """ Compute the alpha (excess returns), alpha t-stat (alpha significance), and beta (market exposure) of a factor. ...
Builds cumulative returns from period returns. This function simulates the cumulative effect that a series of gains or losses ( the returns ) have on an original amount of capital over a period of time.
def cumulative_returns(returns, period, freq=None): """ Builds cumulative returns from 'period' returns. This function simulates the cumulative effect that a series of gains or losses (the 'returns') have on an original amount of capital over a period of time. if F is the frequency at which returns...
Builds net position values time series the portfolio percentage invested in each position.
def positions(weights, period, freq=None): """ Builds net position values time series, the portfolio percentage invested in each position. Parameters ---------- weights: pd.Series pd.Series containing factor weights, the index contains timestamps at which the trades are computed...
Computes mean returns for factor quantiles across provided forward returns columns.
def mean_return_by_quantile(factor_data, by_date=False, by_group=False, demeaned=True, group_adjust=False): """ Computes mean returns for factor quantiles across provided forward returns columns. ...
Computes the difference between the mean returns of two quantiles. Optionally computes the standard error of this difference.
def compute_mean_returns_spread(mean_returns, upper_quant, lower_quant, std_err=None): """ Computes the difference between the mean returns of two quantiles. Optionally, computes the standard error of this di...
Computes the proportion of names in a factor quantile that were not in that quantile in the previous period.
def quantile_turnover(quantile_factor, quantile, period=1): """ Computes the proportion of names in a factor quantile that were not in that quantile in the previous period. Parameters ---------- quantile_factor : pd.Series DataFrame with date, asset and factor quantile. quantile : i...
Computes autocorrelation of mean factor ranks in specified time spans. We must compare period to period factor ranks rather than factor values to account for systematic shifts in the factor values of all names or names within a group. This metric is useful for measuring the turnover of a factor. If the value of a facto...
def factor_rank_autocorrelation(factor_data, period=1): """ Computes autocorrelation of mean factor ranks in specified time spans. We must compare period to period factor ranks rather than factor values to account for systematic shifts in the factor values of all names or names within a group. This ...
A date and equity pair is extracted from each index row in the factor dataframe and for each of these pairs a return series is built starting from before the date and ending after the date specified in the pair. All those returns series are then aligned to a common index ( - before to after ) and returned as a single D...
def common_start_returns(factor, prices, before, after, cumulative=False, mean_by_date=False, demean_by=None): """ A date and equity pair is extracted from each i...
Plots average cumulative returns by factor quantiles in the period range defined by - periods_before to periods_after
def average_cumulative_return_by_quantile(factor_data, prices, periods_before=10, periods_after=15, demeaned=True, ...
Simulate a portfolio using the factor in input and returns the cumulative returns of the simulated portfolio
def factor_cumulative_returns(factor_data, period, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None): ...
Simulate a portfolio using the factor in input and returns the assets positions as percentage of the total portfolio.
def factor_positions(factor_data, period, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None): """ Simulate a portfolio using the factor in input and r...
Simulate a portfolio using the input factor and returns the portfolio performance data properly formatted for Pyfolio analysis.
def create_pyfolio_input(factor_data, period, capital=None, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None...
Creates a small summary tear sheet with returns information and turnover analysis.
def create_summary_tear_sheet(factor_data, long_short=True, group_neutral=False): """ Creates a small summary tear sheet with returns, information, and turnover analysis. Parameters ---------- factor_data : pd.DataFrame - MultiIndex ...
Creates a tear sheet for returns analysis of a factor.
def create_returns_tear_sheet(factor_data, long_short=True, group_neutral=False, by_group=False): """ Creates a tear sheet for returns analysis of a factor. Parameters ---------- factor_data : pd.DataFrame - M...
Creates a tear sheet for information analysis of a factor.
def create_information_tear_sheet(factor_data, group_neutral=False, by_group=False): """ Creates a tear sheet for information analysis of a factor. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex ...
Creates a tear sheet for analyzing the turnover properties of a factor.
def create_turnover_tear_sheet(factor_data, turnover_periods=None): """ Creates a tear sheet for analyzing the turnover properties of a factor. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), contain...
Creates a full tear sheet for analysis and evaluating single return predicting ( alpha ) factor.
def create_full_tear_sheet(factor_data, long_short=True, group_neutral=False, by_group=False): """ Creates a full tear sheet for analysis and evaluating single return predicting (alpha) factor. Parameters ---------- ...
Creates a tear sheet to view the average cumulative returns for a factor within a window ( pre and post event ).
def create_event_returns_tear_sheet(factor_data, prices, avgretplot=(5, 15), long_short=True, group_neutral=False, std_bar=True, ...
Creates an event study tear sheet for analysis of a specific event.
def create_event_study_tear_sheet(factor_data, prices=None, avgretplot=(5, 15), rate_of_ret=True, n_bars=50): """ Creates an event study tear sheet for analysis of a specific e...
Re - raise the last exception that was active in the current scope without losing the stacktrace but adding an additional message. This is hacky because it has to be compatible with both python 2/ 3
def rethrow(exception, additional_message): """ Re-raise the last exception that was active in the current scope without losing the stacktrace but adding an additional message. This is hacky because it has to be compatible with both python 2/3 """ e = exception m = additional_message if ...
Give user a more informative error in case it is not possible to properly calculate quantiles on the input dataframe ( factor )
def non_unique_bin_edges_error(func): """ Give user a more informative error in case it is not possible to properly calculate quantiles on the input dataframe (factor) """ message = """ An error occurred while computing bins/quantiles on the input provided. This usually happens when the inp...
Computes period wise factor quantiles.
def quantize_factor(factor_data, quantiles=5, bins=None, by_group=False, no_raise=False, zero_aware=False): """ Computes period wise factor quantiles. Parameters ---------- factor_data : pd.DataFrame...
Infer the trading calendar from factor and price information.
def infer_trading_calendar(factor_idx, prices_idx): """ Infer the trading calendar from factor and price information. Parameters ---------- factor_idx : pd.DatetimeIndex The factor datetimes for which we are computing the forward returns prices_idx : pd.DatetimeIndex The prices ...
Finds the N period forward returns ( as percent change ) for each asset provided.
def compute_forward_returns(factor, prices, periods=(1, 5, 10), filter_zscore=None, cumulative_returns=True): """ 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.
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.
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.
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.
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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:
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:
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 TIME column as a time object:
def convert_time(obj): """Returns a TIME column as a time object: >>> time_or_None('15:06:17') datetime.time(15, 6, 17) Illegal values are returned as None: >>> time_or_None('-25:06:17') is None True >>> time_or_None('random crap') is None True Note that MySQL always ...
Returns a DATE column as a date object:
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.
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.
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.
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.
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.
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.
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.
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...