code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def plot_scatter_matrix(self, freq=None, title=None, figsize=(10, 10), **kwargs):
"""
Wrapper around pandas' scatter_matrix.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figu... |
Wrapper around pandas' scatter_matrix.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure size
* title (str): Title if default not appropriate
* kwargs: pas... | plot_scatter_matrix | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def plot_histograms(self, freq=None, title=None, figsize=(10, 10), **kwargs):
"""
Wrapper around pandas' hist.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure size
... |
Wrapper around pandas' hist.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure size
* title (str): Title if default not appropriate
* kwargs: passed to pan... | plot_histograms | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def plot_correlation(self, freq=None, title=None, figsize=(12, 6), **kwargs):
"""
Utility function to plot correlations.
Args:
* freq (str): Pandas data frequency alias string
* title (str): Plot title
* figsize (tuple (x,y)): figure size
* kwargs... |
Utility function to plot correlations.
Args:
* freq (str): Pandas data frequency alias string
* title (str): Plot title
* figsize (tuple (x,y)): figure size
* kwargs: passed to Pandas' plot_corr_heatmap function
| plot_correlation | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def to_csv(self, sep=",", path=None):
"""
Returns a CSV string with appropriate formatting.
If path is not None, the string will be saved to file
at path.
Args:
* sep (char): Separator
* path (str): If None, CSV string returned. Else file
... |
Returns a CSV string with appropriate formatting.
If path is not None, the string will be saved to file
at path.
Args:
* sep (char): Separator
* path (str): If None, CSV string returned. Else file
written to specified path.
| to_csv | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def calc_stats(prices):
"""
Calculates performance stats of a given object.
If object is Series, a PerformanceStats object is
returned. If object is DataFrame, a GroupStats object
is returned.
Args:
* prices (Series, DataFrame): Set of prices
"""
if isinstance(prices, pd.Series... |
Calculates performance stats of a given object.
If object is Series, a PerformanceStats object is
returned. If object is DataFrame, a GroupStats object
is returned.
Args:
* prices (Series, DataFrame): Set of prices
| calc_stats | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def to_drawdown_series(prices):
"""
Calculates the `drawdown <https://www.investopedia.com/terms/d/drawdown.asp>`_ series.
This returns a series representing a drawdown.
When the price is at all time highs, the drawdown
is 0. However, when prices are below high water marks,
the drawdown series ... |
Calculates the `drawdown <https://www.investopedia.com/terms/d/drawdown.asp>`_ series.
This returns a series representing a drawdown.
When the price is at all time highs, the drawdown
is 0. However, when prices are below high water marks,
the drawdown series = current / hwm - 1
The max drawdo... | to_drawdown_series | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def calc_mtd(daily_prices, monthly_prices):
"""
Calculates mtd return of a price series.
Use daily_prices if prices are only available from same month
else use monthly_prices
"""
if len(monthly_prices) == 1:
return daily_prices.iloc[-1] / daily_prices.iloc[0] - 1
else:
return... |
Calculates mtd return of a price series.
Use daily_prices if prices are only available from same month
else use monthly_prices
| calc_mtd | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def calc_ytd(daily_prices, yearly_prices):
"""
Calculates ytd return of a price series.
Use daily_prices if prices are only available from same year
else use yearly_prices
"""
if len(yearly_prices) == 1:
return daily_prices.iloc[-1] / daily_prices.iloc[0] - 1
else:
return dai... |
Calculates ytd return of a price series.
Use daily_prices if prices are only available from same year
else use yearly_prices
| calc_ytd | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def drawdown_details(drawdown, index_type=pd.DatetimeIndex):
"""
Returns a data frame with start, end, days (duration) and
drawdown for each drawdown in a drawdown series.
.. note::
days are actual calendar days, not trading days
Args:
* drawdown (pandas.Series): A drawdown Series... |
Returns a data frame with start, end, days (duration) and
drawdown for each drawdown in a drawdown series.
.. note::
days are actual calendar days, not trading days
Args:
* drawdown (pandas.Series): A drawdown Series
(can be obtained w/ drawdown(prices).
Returns:
... | drawdown_details | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def calc_cagr(prices):
"""
Calculates the `CAGR (compound annual growth rate) <https://www.investopedia.com/terms/c/cagr.asp>`_ for a given price series.
Args:
* prices (pandas.Series): A Series of prices.
Returns:
* float -- cagr.
"""
start = prices.index[0]
end = prices.i... |
Calculates the `CAGR (compound annual growth rate) <https://www.investopedia.com/terms/c/cagr.asp>`_ for a given price series.
Args:
* prices (pandas.Series): A Series of prices.
Returns:
* float -- cagr.
| calc_cagr | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def calc_sharpe(returns, rf=0.0, nperiods=None, annualize=True):
"""
Calculates the `Sharpe ratio <https://www.investopedia.com/terms/s/sharperatio.asp>`_
(see `Sharpe vs. Sortino <https://www.investopedia.com/ask/answers/010815/what-difference-between-sharpe-ratio-and-sortino-ratio.asp>`_).
If rf is n... |
Calculates the `Sharpe ratio <https://www.investopedia.com/terms/s/sharperatio.asp>`_
(see `Sharpe vs. Sortino <https://www.investopedia.com/ask/answers/010815/what-difference-between-sharpe-ratio-and-sortino-ratio.asp>`_).
If rf is non-zero and a float, you must specify nperiods. In this case, rf is assu... | calc_sharpe | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def calc_information_ratio(returns, benchmark_returns):
"""
Calculates the `Information ratio <https://www.investopedia.com/terms/i/informationratio.asp>`_ (or `from Wikipedia <http://en.wikipedia.org/wiki/Information_ratio>`_).
"""
diff_rets = returns - benchmark_returns
diff_std = np.std(diff_rets... |
Calculates the `Information ratio <https://www.investopedia.com/terms/i/informationratio.asp>`_ (or `from Wikipedia <http://en.wikipedia.org/wiki/Information_ratio>`_).
| calc_information_ratio | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def year_frac(start, end):
"""
Similar to excel's yearfrac function. Returns
a year fraction between two dates (i.e. 1.53 years).
Approximation using the average number of seconds
in a year.
Args:
* start (datetime): start date
* end (datetime): end date
"""
if start >... |
Similar to excel's yearfrac function. Returns
a year fraction between two dates (i.e. 1.53 years).
Approximation using the average number of seconds
in a year.
Args:
* start (datetime): start date
* end (datetime): end date
| year_frac | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def merge(*series):
"""
Merge Series and/or DataFrames together.
Returns a DataFrame.
"""
dfs = []
for s in series:
if isinstance(s, pd.DataFrame):
dfs.append(s)
elif isinstance(s, pd.Series):
tmpdf = pd.DataFrame({s.name: s})
dfs.append(tmpdf... |
Merge Series and/or DataFrames together.
Returns a DataFrame.
| merge | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def drop_duplicate_cols(df):
"""
Removes duplicate columns from a dataframe
and keeps column w/ longest history
"""
names = set(df.columns)
for n in names:
if len(df[n].shape) > 1:
# get subset of df w/ colname n
sub = df[n]
# make unique colnames
... |
Removes duplicate columns from a dataframe
and keeps column w/ longest history
| drop_duplicate_cols | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def asfreq_actual(series, freq, method="ffill", how="end", normalize=False):
"""
Similar to pandas' asfreq but keeps the actual dates.
For example, if last data point in Jan is on the 29th,
that date will be used instead of the 31st.
"""
orig = series
is_series = False
if isinstance(seri... |
Similar to pandas' asfreq but keeps the actual dates.
For example, if last data point in Jan is on the 29th,
that date will be used instead of the 31st.
| asfreq_actual | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def calc_inv_vol_weights(returns):
"""
Calculates weights proportional to inverse volatility of each column.
Returns weights that are inversely proportional to the column's
volatility resulting in a set of portfolio weights where each position
has the same level of volatility.
Note, that asset... |
Calculates weights proportional to inverse volatility of each column.
Returns weights that are inversely proportional to the column's
volatility resulting in a set of portfolio weights where each position
has the same level of volatility.
Note, that assets with returns all equal to NaN or 0 are e... | calc_inv_vol_weights | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def _erc_weights_slsqp(x0, cov, b, maximum_iterations, tolerance):
"""
Calculates the equal risk contribution / risk parity weights given
a DataFrame of returns.
Args:
* x0 (np.array): Starting asset weights.
* cov (np.array): covariance matrix.
* b (np.array): Risk target weights. By d... |
Calculates the equal risk contribution / risk parity weights given
a DataFrame of returns.
Args:
* x0 (np.array): Starting asset weights.
* cov (np.array): covariance matrix.
* b (np.array): Risk target weights. By definition target total risk contributions are all equal which makes this r... | _erc_weights_slsqp | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def _erc_weights_ccd(x0, cov, b, maximum_iterations, tolerance):
"""
Calculates the equal risk contribution / risk parity weights given
a DataFrame of returns.
Args:
* x0 (np.array): Starting asset weights.
* cov (np.array): covariance matrix.
* b (np.array): Risk target weights... |
Calculates the equal risk contribution / risk parity weights given
a DataFrame of returns.
Args:
* x0 (np.array): Starting asset weights.
* cov (np.array): covariance matrix.
* b (np.array): Risk target weights.
* maximum_iterations (int): Maximum iterations in iterative so... | _erc_weights_ccd | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def calc_erc_weights(
returns,
initial_weights=None,
risk_weights=None,
covar_method="ledoit-wolf",
risk_parity_method="ccd",
maximum_iterations=100,
tolerance=1e-8,
):
"""
Calculates the equal risk contribution / risk parity weights given a
DataFrame of returns.
Args:
... |
Calculates the equal risk contribution / risk parity weights given a
DataFrame of returns.
Args:
* returns (DataFrame): Returns for multiple securities.
* initial_weights (list): Starting asset weights [default inverse vol].
* risk_weights (list): Risk target weights [default equal... | calc_erc_weights | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def get_num_days_required(offset, period="d", perc_required=0.90, annualization_factor=252):
"""
Estimates the number of days required to assume that data is OK.
Helper function used to determine if there are enough "good" data
days over a given period.
Args:
* offset (DateOffset): Offset ... |
Estimates the number of days required to assume that data is OK.
Helper function used to determine if there are enough "good" data
days over a given period.
Args:
* offset (DateOffset): Offset (lookback) period.
* period (str): Period string.
* perc_required (float): percentag... | get_num_days_required | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def calc_clusters(returns, n=None, plot=False):
"""
Calculates the clusters based on k-means
clustering.
Args:
* returns (pd.DataFrame): DataFrame of returns
* n (int): Specify # of clusters. If None, this
will be automatically determined
* plot (bool): Show plot?
... |
Calculates the clusters based on k-means
clustering.
Args:
* returns (pd.DataFrame): DataFrame of returns
* n (int): Specify # of clusters. If None, this
will be automatically determined
* plot (bool): Show plot?
Returns:
* dict with structure: {cluster# : ... | calc_clusters | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def calc_ftca(returns, threshold=0.5):
"""
Implementation of David Varadi's `Fast Threshold Clustering Algorithm (FTCA) <http://cssanalytics.wordpress.com/2013/11/26/fast-threshold-clustering-algorithm-ftca/>`_.
http://cssanalytics.wordpress.com/2013/11/26/fast-threshold-clustering-algorithm-ftca/ # NOQA
... |
Implementation of David Varadi's `Fast Threshold Clustering Algorithm (FTCA) <http://cssanalytics.wordpress.com/2013/11/26/fast-threshold-clustering-algorithm-ftca/>`_.
http://cssanalytics.wordpress.com/2013/11/26/fast-threshold-clustering-algorithm-ftca/ # NOQA
More stable than k-means for clustering p... | calc_ftca | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def random_weights(n, bounds=(0.0, 1.0), total=1.0):
"""
Generate pseudo-random weights.
Returns a list of random weights that is of length
n, where each weight is in the range bounds, and
where the weights sum up to total.
Useful for creating random portfolios when benchmarking.
Args:
... |
Generate pseudo-random weights.
Returns a list of random weights that is of length
n, where each weight is in the range bounds, and
where the weights sum up to total.
Useful for creating random portfolios when benchmarking.
Args:
* n (int): number of random weights
* bounds (... | random_weights | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def plot_heatmap(data, title="Heatmap", show_legend=True, show_labels=True, label_fmt=".2f", vmin=None, vmax=None, figsize=None, label_color="w", cmap="RdBu", **kwargs):
"""
Plot a heatmap using matplotlib's pcolor.
Args:
* data (DataFrame): DataFrame to plot. Usually small matrix (ex.
... |
Plot a heatmap using matplotlib's pcolor.
Args:
* data (DataFrame): DataFrame to plot. Usually small matrix (ex.
correlation matrix).
* title (string): Plot title
* show_legend (bool): Show color legend
* show_labels (bool): Show value labels
* label_fmt (st... | plot_heatmap | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def rollapply(data, window, fn):
"""
Apply a function fn over a rolling window of size window.
Args:
* data (Series or DataFrame): Series or DataFrame
* window (int): Window size
* fn (function): Function to apply over the rolling window.
For a series, the return value i... |
Apply a function fn over a rolling window of size window.
Args:
* data (Series or DataFrame): Series or DataFrame
* window (int): Window size
* fn (function): Function to apply over the rolling window.
For a series, the return value is expected to be a single
nu... | rollapply | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def _winsorize_wrapper(x, limits):
"""
Wraps scipy winsorize function to drop na's
"""
if isinstance(x, pd.Series):
if x.count() == 0:
return x
notnanx = ~np.isnan(x)
x[notnanx] = scipy.stats.mstats.winsorize(x[notnanx], limits=limits)
return x
else:
... |
Wraps scipy winsorize function to drop na's
| _winsorize_wrapper | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def rescale(x, min=0.0, max=1.0, axis=0):
"""
Rescale values to fit a certain range [min, max]
"""
def innerfn(x, min, max):
return np.interp(x, [np.min(x), np.max(x)], [min, max])
if isinstance(x, pd.DataFrame):
return x.apply(
innerfn,
axis=axis,
... |
Rescale values to fit a certain range [min, max]
| rescale | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def deannualize(returns, nperiods):
"""
Convert return expressed in annual terms on a different basis.
Args:
* returns (float, Series, DataFrame): Return(s)
* nperiods (int): Target basis, typically 252 for daily, 12 for
monthly, etc.
"""
if nperiods is None:
np... |
Convert return expressed in annual terms on a different basis.
Args:
* returns (float, Series, DataFrame): Return(s)
* nperiods (int): Target basis, typically 252 for daily, 12 for
monthly, etc.
| deannualize | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def infer_freq(data):
"""
Infer the most likely frequency given the input index. If the frequency is
uncertain or index is not DateTime like, just return None
Args:
* data (DataFrame, Series): Any timeseries dataframe or series
"""
try:
if _PANDAS_TWO:
ret... |
Infer the most likely frequency given the input index. If the frequency is
uncertain or index is not DateTime like, just return None
Args:
* data (DataFrame, Series): Any timeseries dataframe or series
| infer_freq | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def calc_sortino_ratio(returns, rf=0.0, nperiods=None, annualize=True):
"""
Calculates the `Sortino ratio <https://www.investopedia.com/terms/s/sortinoratio.asp>`_ given a series of returns
(see `Sharpe vs. Sortino <https://www.investopedia.com/ask/answers/010815/what-difference-between-sharpe-ratio-and-sor... |
Calculates the `Sortino ratio <https://www.investopedia.com/terms/s/sortinoratio.asp>`_ given a series of returns
(see `Sharpe vs. Sortino <https://www.investopedia.com/ask/answers/010815/what-difference-between-sharpe-ratio-and-sortino-ratio.asp>`_).
Args:
* returns (Series or DataFrame): Returns... | calc_sortino_ratio | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def to_excess_returns(returns, rf, nperiods=None):
"""
Given a series of returns, it will return the excess returns over rf.
Args:
* returns (Series, DataFrame): Returns
* rf (float, Series): `Risk-Free rate(s) <https://www.investopedia.com/terms/r/risk-freerate.asp>`_ expressed in annualiz... |
Given a series of returns, it will return the excess returns over rf.
Args:
* returns (Series, DataFrame): Returns
* rf (float, Series): `Risk-Free rate(s) <https://www.investopedia.com/terms/r/risk-freerate.asp>`_ expressed in annualized term or return series
* nperiods (int): Optiona... | to_excess_returns | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def to_ulcer_index(prices):
"""
Calculates the Ulcer Index for a series of investment returns.
Converts from prices -> `Ulcer index <https://www.investopedia.com/terms/u/ulcerindex.asp>`_
See https://en.wikipedia.org/wiki/Ulcer_index
Args:
prices (pandas.Series or numpy.ndarray): A series... |
Calculates the Ulcer Index for a series of investment returns.
Converts from prices -> `Ulcer index <https://www.investopedia.com/terms/u/ulcerindex.asp>`_
See https://en.wikipedia.org/wiki/Ulcer_index
Args:
prices (pandas.Series or numpy.ndarray): A series of investment returns.
Return... | to_ulcer_index | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def to_ulcer_performance_index(prices, rf=0.0, nperiods=None):
"""
Converts from prices -> `ulcer performance index <https://www.investopedia.com/terms/u/ulcerindex.asp>`_.
See https://en.wikipedia.org/wiki/Ulcer_index
Args:
* prices (Series, DataFrame): Prices
* rf (float, Series): `R... |
Converts from prices -> `ulcer performance index <https://www.investopedia.com/terms/u/ulcerindex.asp>`_.
See https://en.wikipedia.org/wiki/Ulcer_index
Args:
* prices (Series, DataFrame): Prices
* rf (float, Series): `Risk-free rate of return <https://www.investopedia.com/terms/r/risk-fre... | to_ulcer_performance_index | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def resample_returns(returns, func, seed=0, num_trials=100):
"""
Resample the returns and calculate any statistic on every new sample.
https://en.wikipedia.org/wiki/Resampling_(statistics)
:param returns (Series, DataFrame): Returns
:param func: Given the resampled returns calculate a statistic
... |
Resample the returns and calculate any statistic on every new sample.
https://en.wikipedia.org/wiki/Resampling_(statistics)
:param returns (Series, DataFrame): Returns
:param func: Given the resampled returns calculate a statistic
:param seed: Seed for random number generator
:param num_trial... | resample_returns | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def extend_pandas():
"""
Extends pandas' PandasObject (Series, Series,
DataFrame) with some functions defined in this file.
This facilitates common functional composition used in quant
finance.
Ex:
prices.to_returns().dropna().calc_clusters()
(where prices would be a DataFrame)... |
Extends pandas' PandasObject (Series, Series,
DataFrame) with some functions defined in this file.
This facilitates common functional composition used in quant
finance.
Ex:
prices.to_returns().dropna().calc_clusters()
(where prices would be a DataFrame)
| extend_pandas | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def get(
tickers: Sequence[str],
provider=None,
common_dates=True,
forward_fill=False,
clean_tickers=True,
column_names=None,
ticker_field_sep=":",
mrefresh=False,
existing=None,
**kwargs,
) -> pd.DataFrame:
"""
Helper function for retrieving data as a DataFrame.
Arg... |
Helper function for retrieving data as a DataFrame.
Args:
* tickers (list, string, csv string): Tickers to download.
* provider (function): Provider to use for downloading data.
By default it will be ffn.DEFAULT_PROVIDER if not provided.
* common_dates (bool): Keep common d... | get | python | pmorissette/ffn | ffn/data.py | https://github.com/pmorissette/ffn/blob/master/ffn/data.py | MIT |
def web(ticker: str, field=None, start=None, end=None, mrefresh=False, source="yahoo"):
"""
Data provider wrapper around pandas.io.data provider. Provides
memoization.
"""
if source == "yahoo":
warnings.warn("web function is deprecated, as , use yf() instead")
return yf(ticker, field... |
Data provider wrapper around pandas.io.data provider. Provides
memoization.
| web | python | pmorissette/ffn | ffn/data.py | https://github.com/pmorissette/ffn/blob/master/ffn/data.py | MIT |
def csv(ticker: str, path="data.csv", field="", mrefresh=False, **kwargs) -> pd.Series:
"""
Data provider wrapper around pandas' read_csv. Provides memoization.
"""
# set defaults if not specified
if "index_col" not in kwargs:
kwargs["index_col"] = 0
if "parse_dates" not in kwargs:
... |
Data provider wrapper around pandas' read_csv. Provides memoization.
| csv | python | pmorissette/ffn | ffn/data.py | https://github.com/pmorissette/ffn/blob/master/ffn/data.py | MIT |
def memoize(f, refresh_keyword="mrefresh"):
"""
Memoize decorator. The refresh keyword is the keyword
used to bypass the cache (in the function call).
"""
f.mcache = {}
f.mrefresh_keyword = refresh_keyword
return decorator.decorator(_memoize, f) |
Memoize decorator. The refresh keyword is the keyword
used to bypass the cache (in the function call).
| memoize | python | pmorissette/ffn | ffn/utils.py | https://github.com/pmorissette/ffn/blob/master/ffn/utils.py | MIT |
def parse_arg(arg: Union[str, List[str], Tuple[str]]):
"""
Parses arguments for convenience. Argument can be a
csv list ('a,b,c'), a string, a list, a tuple.
Returns a list.
"""
# handle string input
if isinstance(arg, str):
arg = arg.strip()
# parse csv as tickers and creat... |
Parses arguments for convenience. Argument can be a
csv list ('a,b,c'), a string, a list, a tuple.
Returns a list.
| parse_arg | python | pmorissette/ffn | ffn/utils.py | https://github.com/pmorissette/ffn/blob/master/ffn/utils.py | MIT |
def clean_ticker(ticker: str) -> str:
"""
Cleans a ticker for easier use throughout MoneyTree
Splits by space and only keeps first bit. Also removes
any characters that are not letters. Returns as lowercase.
>>> clean_ticker('^VIX')
'vix'
>>> clean_ticker('SPX Index')
'spx'
"""
... |
Cleans a ticker for easier use throughout MoneyTree
Splits by space and only keeps first bit. Also removes
any characters that are not letters. Returns as lowercase.
>>> clean_ticker('^VIX')
'vix'
>>> clean_ticker('SPX Index')
'spx'
| clean_ticker | python | pmorissette/ffn | ffn/utils.py | https://github.com/pmorissette/ffn/blob/master/ffn/utils.py | MIT |
def scale(val: float, src: Sequence[float], dst: Sequence[float]) -> float:
"""
Scale value from src range to dst range.
If value outside bounds, it is clipped and set to
the low or high bound of dst.
Ex:
scale(0, (0.0, 99.0), (-1.0, 1.0)) == -1.0
scale(-5, (0.0, 99.0), (-1.0, 1.0))... |
Scale value from src range to dst range.
If value outside bounds, it is clipped and set to
the low or high bound of dst.
Ex:
scale(0, (0.0, 99.0), (-1.0, 1.0)) == -1.0
scale(-5, (0.0, 99.0), (-1.0, 1.0)) == -1.0
| scale | python | pmorissette/ffn | ffn/utils.py | https://github.com/pmorissette/ffn/blob/master/ffn/utils.py | MIT |
def as_format(item: Union[pd.DataFrame, pd.Series], format_str=".2f") -> Union[pd.DataFrame, pd.Series]:
"""
Map a format string over a pandas object.
"""
PANDAS_VERSION = Version(pd.__version__)
PANDAS_210 = PANDAS_VERSION >= Version("2.1.0")
select_map = "map"
if not PANDAS_210:
s... |
Map a format string over a pandas object.
| as_format | python | pmorissette/ffn | ffn/utils.py | https://github.com/pmorissette/ffn/blob/master/ffn/utils.py | MIT |
def extract_changelog(text, version, *, allow_unreleased=False):
"""Extract the changelog for a given version."""
start_re = rf'^Version {re.escape(version)}\n-+\n\n\*(Unreleased|Released on .+)\*\n$'
end_re = r'(^----$)|(^Version [0-9.abrc]+$)'
if not (match := re.search(start_re, text, re.MULTILINE))... | Extract the changelog for a given version. | extract_changelog | python | indico/indico | .github/utils/extract_changelog.py | https://github.com/indico/indico/blob/master/.github/utils/extract_changelog.py | MIT |
def convert_to_markdown(text):
"""Convert rst changelog to markdown.
This is a poor man's rst-to-markdown converter that just handles the stuff
we use in our CHANGES.rst file. Using it avoids having to install a tool
like pandoc and it also does some nice extra things such as adding emojis
to headi... | Convert rst changelog to markdown.
This is a poor man's rst-to-markdown converter that just handles the stuff
we use in our CHANGES.rst file. Using it avoids having to install a tool
like pandoc and it also does some nice extra things such as adding emojis
to headings (or failing if an unknonwn heading... | convert_to_markdown | python | indico/indico | .github/utils/extract_changelog.py | https://github.com/indico/indico/blob/master/.github/utils/extract_changelog.py | MIT |
def build_plugin(plugin_dir: Path, dev, clean, watch, url_root):
"""Run webpack to build plugin assets."""
clean = clean or (clean is None and not dev)
webpack_build_config_file = plugin_dir / 'webpack-build-config.json'
webpack_build_config = _get_plugin_webpack_build_config(plugin_dir, url_root)
w... | Run webpack to build plugin assets. | build_plugin | python | indico/indico | bin/maintenance/build-assets.py | https://github.com/indico/indico/blob/master/bin/maintenance/build-assets.py | MIT |
def build_plugin(obj, assets, plugin_dir, add_version_suffix, ignore_unclean, no_git):
"""Build a plugin wheel.
PLUGIN_DIR is the path to the folder containing the plugin's pyproject.toml
"""
target_dir = obj['target_dir']
with _chdir(plugin_dir):
if no_git:
clean, output = True... | Build a plugin wheel.
PLUGIN_DIR is the path to the folder containing the plugin's pyproject.toml
| build_plugin | python | indico/indico | bin/maintenance/build-wheel.py | https://github.com/indico/indico/blob/master/bin/maintenance/build-wheel.py | MIT |
def build_all_plugins(ctx, assets, plugins_dir, add_version_suffix, ignore_unclean, no_git):
"""Build all plugin wheels in a directory.
PLUGINS_DIR is the path to the folder containing the plugin directories
"""
plugins = sorted(d for d in os.listdir(plugins_dir)
if os.path.exists(... | Build all plugin wheels in a directory.
PLUGINS_DIR is the path to the folder containing the plugin directories
| build_all_plugins | python | indico/indico | bin/maintenance/build-wheel.py | https://github.com/indico/indico/blob/master/bin/maintenance/build-wheel.py | MIT |
def main(upgrade, upgrade_packages, no_plugins):
"""Compiles/upgrades the transitive Python dependencies.
This tool is a simple wrapper for `uv pip compile` that handles all the
separate requirements files automatically.
"""
if upgrade and upgrade_packages:
raise click.UsageError('When upgr... | Compiles/upgrades the transitive Python dependencies.
This tool is a simple wrapper for `uv pip compile` that handles all the
separate requirements files automatically.
| main | python | indico/indico | bin/maintenance/compile-python-deps.py | https://github.com/indico/indico/blob/master/bin/maintenance/compile-python-deps.py | MIT |
def main(force, output, plugins):
"""
Dump the URL routing map to JSON for use by the `babel-flask-url`
babel plugin.
"""
try:
with open(output) as f:
data = json.load(f)
except OSError:
data = {}
version = get_map_version()
if not force and data.get('version'... |
Dump the URL routing map to JSON for use by the `babel-flask-url`
babel plugin.
| main | python | indico/indico | bin/maintenance/dump_url_map.py | https://github.com/indico/indico/blob/master/bin/maintenance/dump_url_map.py | MIT |
def generate_icon_rules(selection_file):
"""Generate SCSS rules from the icomoon selection.json file."""
# Read the selection file and get the icon names
selection = json.loads(selection_file.read_text())
icons = sorted(
(
icon['properties']['name'].split(',', 1)[0].lower().replace('... | Generate SCSS rules from the icomoon selection.json file. | generate_icon_rules | python | indico/indico | bin/maintenance/generate_icons.py | https://github.com/indico/indico/blob/master/bin/maintenance/generate_icons.py | MIT |
def generate_locale_imports(locale_dir, locale_mapping):
"""Generate moment.js import statements for locales in 'indico/translations'.
'en_US' is skipped as it is not the default moment locale. 'en_GB' is skipped as
it is already included as the fallback locale in 'indico/web/client/js/jquery/index.js'.
... | Generate moment.js import statements for locales in 'indico/translations'.
'en_US' is skipped as it is not the default moment locale. 'en_GB' is skipped as
it is already included as the fallback locale in 'indico/web/client/js/jquery/index.js'.
| generate_locale_imports | python | indico/indico | bin/maintenance/update_moment_locales.py | https://github.com/indico/indico/blob/master/bin/maintenance/update_moment_locales.py | MIT |
def main(dbname, verbose, reverse):
"""
Compare the structure of the database against what's created from the
models during `indico db prepare`.
By default the current database is assumed to be named `indico`, but it
can be overridden. The database uses for comparison will be named
`indico_dbd... |
Compare the structure of the database against what's created from the
models during `indico db prepare`.
By default the current database is assumed to be named `indico`, but it
can be overridden. The database uses for comparison will be named
`indico_dbdiff` and may not exist. It will be created ... | main | python | indico/indico | bin/utils/db_diff.py | https://github.com/indico/indico/blob/master/bin/utils/db_diff.py | MIT |
def cli():
"""
This script lets you control various aspects of Indico from the
command line.
""" |
This script lets you control various aspects of Indico from the
command line.
| cli | python | indico/indico | indico/cli/core.py | https://github.com/indico/indico/blob/master/indico/cli/core.py | MIT |
def run(info, **kwargs):
"""Run the development webserver.
If no port is set, 8000 or 8443 will be used (depending on whether
SSL is enabled or not).
Enabling SSL without specifying key and certificate will use a
self-signed one.
Specifying a custom URL allows you to run the dev server e.g. b... | Run the development webserver.
If no port is set, 8000 or 8443 will be used (depending on whether
SSL is enabled or not).
Enabling SSL without specifying key and certificate will use a
self-signed one.
Specifying a custom URL allows you to run the dev server e.g. behind
nginx to access it on ... | run | python | indico/indico | indico/cli/core.py | https://github.com/indico/indico/blob/master/indico/cli/core.py | MIT |
def reset_alembic():
"""Reset the alembic state carried over from 1.9.x.
Only run this command right after upgrading from a 1.9.x version
so the references to old alembic revisions (which were removed in
2.0) are reset.
"""
tables = get_all_tables(db)['public']
if 'alembic_version' not in t... | Reset the alembic state carried over from 1.9.x.
Only run this command right after upgrading from a 1.9.x version
so the references to old alembic revisions (which were removed in
2.0) are reset.
| reset_alembic | python | indico/indico | indico/cli/database.py | https://github.com/indico/indico/blob/master/indico/cli/database.py | MIT |
def export(id, target_file, is_category, keep_uuids, use_pickle, dummy_files, external_files, identities):
"""Export all data associated with an event.
This exports the whole event as an archive which can be imported
on another other Indico instance. Importing an event is only
guaranteed to work if it... | Export all data associated with an event.
This exports the whole event as an archive which can be imported
on another other Indico instance. Importing an event is only
guaranteed to work if it was exported on the same Indico version.
It is also possible to export a whole category subtree, including a... | export | python | indico/indico | indico/cli/event.py | https://github.com/indico/indico/blob/master/indico/cli/event.py | MIT |
def import_(source_file, create_users, create_affiliations, force, verbose, yes, category_id,
id_map_path: Path | None = None, files_map_path: Path | None = None):
"""Import an event exported from another Indico instance."""
click.echo('Importing event/category...')
obj, id_map, files_map = impo... | Import an event exported from another Indico instance. | import_ | python | indico/indico | indico/cli/event.py | https://github.com/indico/indico/blob/master/indico/cli/event.py | MIT |
def create_series(show_sequence_in_title, show_links, event_ids):
"""Create a series from a list of events."""
events = Event.query.filter(Event.id.in_(event_ids), ~Event.is_deleted).all()
if missing := (set(event_ids) - {e.id for e in events}):
click.secho('Events not found:', fg='red', bold=True)... | Create a series from a list of events. | create_series | python | indico/indico | indico/cli/event.py | https://github.com/indico/indico/blob/master/indico/cli/event.py | MIT |
def remove_empty_pot_files(path: Path, python=False, javascript=False, react=False):
"""Remove empty .pot files with no msgid strings after extraction."""
if python and po_file_empty(_get_messages_pot(path)):
_get_messages_pot(path).unlink()
if javascript and po_file_empty(_get_messages_js_pot(path)... | Remove empty .pot files with no msgid strings after extraction. | remove_empty_pot_files | python | indico/indico | indico/cli/i18n.py | https://github.com/indico/indico/blob/master/indico/cli/i18n.py | MIT |
def merge_pot_files(output_file: Path, *input_files: list[Path]):
"""Merge multiple POT files into a single POT file."""
merged_catalog = Catalog(
project=DEFAULT_OPTIONS['ExtractMessages']['project'],
version=DEFAULT_OPTIONS['ExtractMessages']['version']
)
for input_file in input_files... | Merge multiple POT files into a single POT file. | merge_pot_files | python | indico/indico | indico/cli/i18n.py | https://github.com/indico/indico/blob/master/indico/cli/i18n.py | MIT |
def split_po_by_pot(merged_po_path: Path, pot_path: Path, output_po_path: Path):
"""Filter messages-all.po files by removing messages that are not in the given .pot file."""
with merged_po_path.open('rb') as f:
merged_catalog = read_po(f)
with pot_path.open('rb') as f:
pot_catalog = read_po... | Filter messages-all.po files by removing messages that are not in the given .pot file. | split_po_by_pot | python | indico/indico | indico/cli/i18n.py | https://github.com/indico/indico/blob/master/indico/cli/i18n.py | MIT |
def init_catalog():
"""Catalog initialization command for indico and indico plugin.
The sub commands take the new locale to be initialized as argument.
""" | Catalog initialization command for indico and indico plugin.
The sub commands take the new locale to be initialized as argument.
| init_catalog | python | indico/indico | indico/cli/i18n.py | https://github.com/indico/indico/blob/master/indico/cli/i18n.py | MIT |
def _pull(languages, translations_dir=TRANSLATIONS_DIR):
"""Pull translated .po files from Transifex.
Pulls only the language codes specified in `languages` if present.
If no `languages`, it pulls all the languages currently available in the translations folder.
To pull a new language available on Tran... | Pull translated .po files from Transifex.
Pulls only the language codes specified in `languages` if present.
If no `languages`, it pulls all the languages currently available in the translations folder.
To pull a new language available on Transifex, simply pass the new language code in the argument.
| _pull | python | indico/indico | indico/cli/i18n.py | https://github.com/indico/indico/blob/master/indico/cli/i18n.py | MIT |
def check_format_strings():
"""Check whether format strings match.
This helps finding cases where e.g. the original string uses
``{error}`` but the translation uses ``{erro}``, resulting
in errors when using the translated string.
"""
all_valid = _check_format_strings()
if all_valid:
... | Check whether format strings match.
This helps finding cases where e.g. the original string uses
``{error}`` but the translation uses ``{erro}``, resulting
in errors when using the translated string.
| check_format_strings | python | indico/indico | indico/cli/i18n.py | https://github.com/indico/indico/blob/master/indico/cli/i18n.py | MIT |
def check_html_tags():
"""Check whether the HTML tags in the source and the translated message match.
This helps find cases where e.g. the translated message does not properly
close the tags. Additionally, this ensures that no one sneaks in dangerous
HTML (like a <script> tag) into the translations.
... | Check whether the HTML tags in the source and the translated message match.
This helps find cases where e.g. the translated message does not properly
close the tags. Additionally, this ensures that no one sneaks in dangerous
HTML (like a <script> tag) into the translations.
| check_html_tags | python | indico/indico | indico/cli/i18n.py | https://github.com/indico/indico/blob/master/indico/cli/i18n.py | MIT |
def _iter_msg_pairs(catalog):
"""Iterate over all (original, translated) message pairs in the catalog.
For singular messages, this produces a single pair (original, translated).
For plural messages, this produces a pair for each plural form. For example,
for a language with 4 plural forms, this will ge... | Iterate over all (original, translated) message pairs in the catalog.
For singular messages, this produces a single pair (original, translated).
For plural messages, this produces a pair for each plural form. For example,
for a language with 4 plural forms, this will generate:
(orig_singular, tran... | _iter_msg_pairs | python | indico/indico | indico/cli/i18n.py | https://github.com/indico/indico/blob/master/indico/cli/i18n.py | MIT |
def fix_event_role_acls():
"""Fix ACLs referencing event roles from other events.
This happened due to a bug prior to 2.2.3 when cloning an event
which had event roles in its ACL.
"""
fixed_something = False
broken = (EventPrincipal.query
.join(EventRole, EventRole.id == EventPrin... | Fix ACLs referencing event roles from other events.
This happened due to a bug prior to 2.2.3 when cloning an event
which had event roles in its ACL.
| fix_event_role_acls | python | indico/indico | indico/cli/maintenance.py | https://github.com/indico/indico/blob/master/indico/cli/maintenance.py | MIT |
def create_symlinks(target_dir):
"""Create useful symlinks to run Indico from a webserver.
This lets you use static paths for the WSGI file and the htdocs
folder so you do not need to update your webserver config when
updating Indico.
"""
root_dir, target_dir = _get_dirs(target_dir)
_link(o... | Create useful symlinks to run Indico from a webserver.
This lets you use static paths for the WSGI file and the htdocs
folder so you do not need to update your webserver config when
updating Indico.
| create_symlinks | python | indico/indico | indico/cli/setup.py | https://github.com/indico/indico/blob/master/indico/cli/setup.py | MIT |
def create_logging_config(target_dir):
"""Create the default logging config file for Indico.
If a file already exists it is left untouched. This command is
usually only used when doing a fresh indico installation when
not using the setup wizard.
"""
root_dir, target_dir = _get_dirs(target_dir)
... | Create the default logging config file for Indico.
If a file already exists it is left untouched. This command is
usually only used when doing a fresh indico installation when
not using the setup wizard.
| create_logging_config | python | indico/indico | indico/cli/setup.py | https://github.com/indico/indico/blob/master/indico/cli/setup.py | MIT |
def upgrade_python(check, no_pyenv_update, local, force_version, venv):
"""Upgrade the Python version used in the Indico virtualenv.
When using `--check`, only Python versions currently available in pyenv will
be used; make sure to `pyenv update` first (this is done automatically when
you run this comm... | Upgrade the Python version used in the Indico virtualenv.
When using `--check`, only Python versions currently available in pyenv will
be used; make sure to `pyenv update` first (this is done automatically when
you run this command without `--check`).
Be careful when using `--force-version` with a cus... | upgrade_python | python | indico/indico | indico/cli/setup.py | https://github.com/indico/indico/blob/master/indico/cli/setup.py | MIT |
def grant_admin(user_id):
"""Grant administration rights to a given user."""
user = User.get(user_id)
if user is None:
click.secho('This user does not exist', fg='red')
return
_print_user_info(user)
if user.is_admin:
click.secho('This user already has administration rights', ... | Grant administration rights to a given user. | grant_admin | python | indico/indico | indico/cli/user.py | https://github.com/indico/indico/blob/master/indico/cli/user.py | MIT |
def revoke_admin(user_id):
"""Revoke administration rights from a given user."""
user = User.get(user_id)
if user is None:
click.secho('This user does not exist', fg='red')
return
_print_user_info(user)
if not user.is_admin:
click.secho('This user does not have administration... | Revoke administration rights from a given user. | revoke_admin | python | indico/indico | indico/cli/user.py | https://github.com/indico/indico/blob/master/indico/cli/user.py | MIT |
def anonymize(user_id):
"""Anonymize a given user.
This will remove all personal data about the given user including
their name, affiliation and emails. Note that any data tied to events
such as registrations or speaker roles will not be deleted.
"""
if (user := User.get(user_id)) is None:
... | Anonymize a given user.
This will remove all personal data about the given user including
their name, affiliation and emails. Note that any data tied to events
such as registrations or speaker roles will not be deleted.
| anonymize | python | indico/indico | indico/cli/user.py | https://github.com/indico/indico/blob/master/indico/cli/user.py | MIT |
def delete(user_id):
"""Delete a given user.
This will completely remove the user and everything
they are connected to. Use at your own risk.
"""
user = User.get(user_id)
if user is None:
click.secho('This user does not exist', fg='red')
return
_print_user_info(user)
if ... | Delete a given user.
This will completely remove the user and everything
they are connected to. Use at your own risk.
| delete | python | indico/indico | indico/cli/user.py | https://github.com/indico/indico/blob/master/indico/cli/user.py | MIT |
def token_list(user_id, verbose):
"""List the tokens of the user."""
user = User.get(user_id)
if user is None:
click.secho('This user does not exist', fg='red', bold=True)
return
_print_user_info(user)
query = (
user.query_personal_tokens(include_revoked=verbose)
.ord... | List the tokens of the user. | token_list | python | indico/indico | indico/cli/user.py | https://github.com/indico/indico/blob/master/indico/cli/user.py | MIT |
def synced_fields(self):
"""The keys to be synchronized.
This is the set of keys to be synced to user data.
The ``email`` can never be synchronized.
"""
provider = self.sync_provider
if provider is None:
return set()
synced_fields = set(provider.setti... | The keys to be synchronized.
This is the set of keys to be synced to user data.
The ``email`` can never be synchronized.
| synced_fields | python | indico/indico | indico/core/auth.py | https://github.com/indico/indico/blob/master/indico/core/auth.py | MIT |
def locked_fields(self):
"""The keys that cannot be desynchronized.
This is a subset of the keys listed in ``synced_fields`` that cannot be
desynchronized by a non-admin user.
"""
provider = self.sync_provider
if provider is None:
return set()
return ... | The keys that cannot be desynchronized.
This is a subset of the keys listed in ``synced_fields`` that cannot be
desynchronized by a non-admin user.
| locked_fields | python | indico/indico | indico/core/auth.py | https://github.com/indico/indico/blob/master/indico/core/auth.py | MIT |
def get_config_path():
"""Get the path of the indico config file.
This may return the location of a symlink. Resolving a link is up
to the caller if needed.
"""
# In certain environments (debian+uwsgi+no-systemd) Indico may run
# with an incorrect $HOME (such as /root), resulting in the config... | Get the path of the indico config file.
This may return the location of a symlink. Resolving a link is up
to the caller if needed.
| get_config_path | python | indico/indico | indico/core/config.py | https://github.com/indico/indico/blob/master/indico/core/config.py | MIT |
def load_config(only_defaults=False, override=None):
"""Load the configuration data.
:param only_defaults: Whether to load only the default options,
ignoring any user-specified config file
or environment-based overrides.
:param override: An optional dict ... | Load the configuration data.
:param only_defaults: Whether to load only the default options,
ignoring any user-specified config file
or environment-based overrides.
:param override: An optional dict with extra values to add to
the configu... | load_config | python | indico/indico | indico/core/config.py | https://github.com/indico/indico/blob/master/indico/core/config.py | MIT |
def do_send_email(email, log_entry=None, _from_task=False):
"""Send an email.
This function should not be called directly unless your
goal is to send an email *right now* without nice error
handling or retrying. For pretty much all cases where
you just want to send an email, use `send_email` inste... | Send an email.
This function should not be called directly unless your
goal is to send an email *right now* without nice error
handling or retrying. For pretty much all cases where
you just want to send an email, use `send_email` instead.
:param email: The data describign the email, as created by... | do_send_email | python | indico/indico | indico/core/emails.py | https://github.com/indico/indico/blob/master/indico/core/emails.py | MIT |
def resend_failed_email(path):
"""Try re-sending an email that previously failed."""
from indico.modules.logs import EventLogEntry
with open(path, 'rb') as f:
email, log_entry_id = pickle.load(f) # noqa: S301
log_entry = EventLogEntry.get(log_entry_id) if log_entry_id is not None else None
... | Try re-sending an email that previously failed. | resend_failed_email | python | indico/indico | indico/core/emails.py | https://github.com/indico/indico/blob/master/indico/core/emails.py | MIT |
def get_error_description(exception):
"""Get a user-friendy description for an exception.
This overrides some HTTPException messages to be more suitable
for end-users.
"""
try:
description = exception.description
except AttributeError:
return str(exception)
if isinstance(exc... | Get a user-friendy description for an exception.
This overrides some HTTPException messages to be more suitable
for end-users.
| get_error_description | python | indico/indico | indico/core/errors.py | https://github.com/indico/indico/blob/master/indico/core/errors.py | MIT |
def get(cls, name=None):
"""Get a logger with the given name.
This behaves pretty much like `logging.getLogger`, except for
prefixing any logger name with ``indico.`` (if not already
present).
"""
if name is None:
name = 'indico'
elif name != 'indico'... | Get a logger with the given name.
This behaves pretty much like `logging.getLogger`, except for
prefixing any logger name with ``indico.`` (if not already
present).
| get | python | indico/indico | indico/core/logger.py | https://github.com/indico/indico/blob/master/indico/core/logger.py | MIT |
def make_email(to_list=None, cc_list=None, bcc_list=None, *, sender_address=None, reply_address=None, attachments=None,
subject=None, body=None, template=None, html=False):
"""Create an email.
The preferred way to specify the email content is using the
`template` argument. To do so, use :fun... | Create an email.
The preferred way to specify the email content is using the
`template` argument. To do so, use :func:`.get_template_module` on
a template inheriting from ``emails/base.txt`` for text emails or
``emails/base.html`` for HTML emails.
:param to_list: The recipient email or a collectio... | make_email | python | indico/indico | indico/core/notifications.py | https://github.com/indico/indico/blob/master/indico/core/notifications.py | MIT |
def check_permissions(type_):
"""
Retrieve the permissions for an object type and ensure they are
defined properly.
This function should be executed from a function connected to the
`app_created` signal to avoid failures related to invalid permission
definitions later at runtime.
"""
pe... |
Retrieve the permissions for an object type and ensure they are
defined properly.
This function should be executed from a function connected to the
`app_created` signal to avoid failures related to invalid permission
definitions later at runtime.
| check_permissions | python | indico/indico | indico/core/permissions.py | https://github.com/indico/indico/blob/master/indico/core/permissions.py | MIT |
def get_permissions_info(_type):
"""
Retrieve the permissions that can be set in the protection page
and related information.
:param _type: The type of the permissions retrieved (e.g. Event, Category)
:return: A tuple containing a dict with the available permissions and a dict with the permissions ... |
Retrieve the permissions that can be set in the protection page
and related information.
:param _type: The type of the permissions retrieved (e.g. Event, Category)
:return: A tuple containing a dict with the available permissions and a dict with the permissions tree
| get_permissions_info | python | indico/indico | indico/core/permissions.py | https://github.com/indico/indico/blob/master/indico/core/permissions.py | MIT |
def get_principal_permissions(principal, _type):
"""Retrieve a set containing the valid permissions of a principal."""
permissions = set()
if principal.full_access:
permissions.add(FULL_ACCESS_PERMISSION)
if principal.read_access:
permissions.add(READ_ACCESS_PERMISSION)
available_per... | Retrieve a set containing the valid permissions of a principal. | get_principal_permissions | python | indico/indico | indico/core/permissions.py | https://github.com/indico/indico/blob/master/indico/core/permissions.py | MIT |
def get_unified_permissions(principal, all_permissions=False):
"""Convert principal's permissions into a list including read and full access.
:param principal: A `User`, `GroupProxy`, `EmailPrincipal` or `EventRole` instance
:param all_permissions: Whether to include all permissions, even if principal has ... | Convert principal's permissions into a list including read and full access.
:param principal: A `User`, `GroupProxy`, `EmailPrincipal` or `EventRole` instance
:param all_permissions: Whether to include all permissions, even if principal has full access
| get_unified_permissions | python | indico/indico | indico/core/permissions.py | https://github.com/indico/indico/blob/master/indico/core/permissions.py | MIT |
def get_split_permissions(permissions):
"""
Split a list of permissions into a `has_full_access, has_read_access,
list_with_others` tuple.
"""
full_access_permission = FULL_ACCESS_PERMISSION in permissions
read_access_permission = READ_ACCESS_PERMISSION in permissions
other_permissions = per... |
Split a list of permissions into a `has_full_access, has_read_access,
list_with_others` tuple.
| get_split_permissions | python | indico/indico | indico/core/permissions.py | https://github.com/indico/indico/blob/master/indico/core/permissions.py | MIT |
def update_permissions(obj, form):
"""Update the permissions of an object, based on the corresponding WTForm."""
from indico.modules.categories import Category
from indico.modules.events import Event
from indico.util.user import principal_from_identifier
event_id = category_id = None
if isinsta... | Update the permissions of an object, based on the corresponding WTForm. | update_permissions | python | indico/indico | indico/core/permissions.py | https://github.com/indico/indico/blob/master/indico/core/permissions.py | MIT |
def update_principals_permissions(obj, current, new):
"""
Handle the updates of permissions and creations/deletions of acl principals.
:param obj: The object to update. Must have ``acl_entries``
:param current: A dict mapping principals to a set with its current permissions
:param new: A dict mappi... |
Handle the updates of permissions and creations/deletions of acl principals.
:param obj: The object to update. Must have ``acl_entries``
:param current: A dict mapping principals to a set with its current permissions
:param new: A dict mapping principals to a set with its new permissions
| update_principals_permissions | python | indico/indico | indico/core/permissions.py | https://github.com/indico/indico/blob/master/indico/core/permissions.py | MIT |
def unlock(name):
"""Unlock a locked task.
Use this if your celery worker was e.g. killed by your kernel's
oom-killer and thus a task never got unlocked.
Example:
indico celery unlock event_reminders
"""
if unlock_task(name):
click.secho(f'Task {name} unlocked', fg='green', bo... | Unlock a locked task.
Use this if your celery worker was e.g. killed by your kernel's
oom-killer and thus a task never got unlocked.
Example:
indico celery unlock event_reminders
| unlock | python | indico/indico | indico/core/celery/cli.py | https://github.com/indico/indico/blob/master/indico/core/celery/cli.py | MIT |
def periodic_task(self, *args, **kwargs):
"""Decorator to register a periodic task.
This behaves like the :meth:`task` decorator, but automatically
schedules the task to execute periodically, using extra kwargs
as described in the Celery documentation:
http://celery.readthedocs.... | Decorator to register a periodic task.
This behaves like the :meth:`task` decorator, but automatically
schedules the task to execute periodically, using extra kwargs
as described in the Celery documentation:
http://celery.readthedocs.org/en/latest/userguide/periodic-tasks.html#available... | periodic_task | python | indico/indico | indico/core/celery/core.py | https://github.com/indico/indico/blob/master/indico/core/celery/core.py | MIT |
def _patch_task(self):
"""Patch the `task` decorator to run tasks inside the indico environment."""
class IndicoTask(self.Task):
abstract = True
def apply_async(s, args=None, kwargs=None, task_id=None, producer=None, # noqa: N805
link=None, link_erro... | Patch the `task` decorator to run tasks inside the indico environment. | _patch_task | python | indico/indico | indico/core/celery/core.py | https://github.com/indico/indico/blob/master/indico/core/celery/core.py | MIT |
def locked_task(f):
"""Decorator to prevent a task from running multiple times at once."""
@wraps(f)
def wrapper(*args, **kwargs):
name = current_task.name
if _lock_cache.get(name):
Logger.get('celery').warning('Task %s is locked; not executing it. '
... | Decorator to prevent a task from running multiple times at once. | locked_task | python | indico/indico | indico/core/celery/util.py | https://github.com/indico/indico/blob/master/indico/core/celery/util.py | MIT |
def unlock_task(name):
"""Unlock a locked task.
:return: ``True`` if the task has been unlocked; ``False`` if it was not locked.
"""
if not _lock_cache.get(name):
return False
_lock_cache.delete(name)
return True | Unlock a locked task.
:return: ``True`` if the task has been unlocked; ``False`` if it was not locked.
| unlock_task | python | indico/indico | indico/core/celery/util.py | https://github.com/indico/indico/blob/master/indico/core/celery/util.py | MIT |
def colors(self):
"""The current set of colors or None if no colors are set."""
colors = ColorTuple(self.text_color, self.background_color)
return colors or self.default_colors | The current set of colors or None if no colors are set. | colors | python | indico/indico | indico/core/db/sqlalchemy/colors.py | https://github.com/indico/indico/blob/master/indico/core/db/sqlalchemy/colors.py | MIT |
def handle_sqlalchemy_database_error():
"""Handle a SQLAlchemy DatabaseError exception nicely.
Currently this only takes care of custom INDX exception
raised from constraint triggers. It must be invoked from an
``except DatabaseError`` block.
:raise ConstraintViolated: if an exception with an SQL... | Handle a SQLAlchemy DatabaseError exception nicely.
Currently this only takes care of custom INDX exception
raised from constraint triggers. It must be invoked from an
``except DatabaseError`` block.
:raise ConstraintViolated: if an exception with an SQLSTATE of
``INDX*... | handle_sqlalchemy_database_error | python | indico/indico | indico/core/db/sqlalchemy/core.py | https://github.com/indico/indico/blob/master/indico/core/db/sqlalchemy/core.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.