code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self._check_estimated()
return self._rc.cov_YY(bessel=self.bessel) | def Ctt_(self) | Covariance matrix of the time shifted data | 53.507225 | 36.653122 | 1.459827 |
if self._default_chunksize is None:
try:
# TODO: if dimension is not yet fixed (eg tica var cutoff, use dim of data_producer.
self.dimension()
self.output_type()
except:
self._default_chunksize = Iterable._FALLBACK_... | def default_chunksize(self) | How much data will be processed at once, in case no chunksize has been provided.
Notes
-----
This variable respects your setting for maximum memory in pyemma.config.default_chunksize | 10.843932 | 11.03409 | 0.982766 |
if self.in_memory:
from pyemma.coordinates.data.data_in_memory import DataInMemory
return DataInMemory(self._Y).iterator(
lag=lag, chunk=chunk, stride=stride, return_trajindex=return_trajindex, skip=skip
)
chunk = chunk if chunk is not None el... | def iterator(self, stride=1, lag=0, chunk=None, return_trajindex=True, cols=None, skip=0) | creates an iterator to stream over the (transformed) data.
If your data is too large to fit into memory and you want to incrementally compute
some quantities on it, you can create an iterator on a reader or transformer (eg. TICA)
to avoid memory overflows.
Parameters
----------... | 2.442713 | 2.623856 | 0.930963 |
alpha = self.alpha
if alpha <= 0:
raise ValueError("alpha should be >0, got {0!r}".format(alpha))
X = atleast2d_or_csr(X)
classes, y = np.unique(y, return_inverse=True)
lengths = np.asarray(lengths)
Y = y.reshape(-1, 1) == np.arange(len(classes))
... | def fit(self, X, y, lengths) | Fit HMM model to data.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Feature matrix of individual samples.
y : array-like, shape (n_samples,)
Target labels.
lengths : array-like of integers, shape (n_sequences,)
... | 2.623523 | 2.77847 | 0.944233 |
for f, sha1 in files:
yield "100644 blob {}\t{}\0".format(sha1, f)
for d, sha1 in dirs:
yield "040000 tree {}\t{}\0".format(sha1, d) | def _lstree(files, dirs) | Make git ls-tree like output. | 3.276724 | 2.746157 | 1.193203 |
dir_hash = {}
for root, dirs, files in os.walk(path, topdown=False):
f_hash = ((f, hash_file(join(root, f))) for f in files)
d_hash = ((d, dir_hash[join(root, d)]) for d in dirs)
# split+join normalizes paths on Windows (note the imports)
dir_hash[join(*split(root))] = _mkt... | def hash_dir(path) | Write directory at path to Git index, return its SHA1 as a string. | 4.44608 | 4.265459 | 1.042345 |
word = sentence[i]
yield "word:{}" + word.lower()
if word[0].isupper():
yield "CAP"
if i > 0:
yield "word-1:{}" + sentence[i - 1].lower()
if i > 1:
yield "word-2:{}" + sentence[i - 2].lower()
if i + 1 < len(sentence):
yield "word+1:{}" + sentence[... | def features(sentence, i) | Features for i'th token in sentence.
Currently baseline named-entity recognition features, but these can
easily be changed to do POS tagging or chunking. | 2.199199 | 2.208223 | 0.995913 |
if len(y_true) != len(y_pred):
msg = "Sequences not of the same length ({} != {})."""
raise ValueError(msg.format(len(y_true), len(y_pred)))
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
is_b = partial(np.char.startswith, prefix="B")
where = np.where
t_starts =... | def bio_f_score(y_true, y_pred) | F-score for BIO-tagging scheme, as used by CoNLL.
This F-score variant is used for evaluating named-entity recognition and
related problems, where the goal is to predict segments of interest within
sequences and mark these as a "B" (begin) tag followed by zero or more "I"
(inside) tags. A true positive... | 2.489401 | 2.371407 | 1.049757 |
lengths = np.asarray(lengths)
end = np.cumsum(lengths)
start = end - lengths
bounds = np.vstack([start, end]).T
errors = sum(1. for i, j in bounds
if np.any(y_true[i:j] != y_pred[i:j]))
return 1 - errors / len(lengths) | def whole_sequence_accuracy(y_true, y_pred, lengths) | Average accuracy measured on whole sequences.
Returns the fraction of sequences in y_true that occur in y_pred without a
single error. | 3.261131 | 3.462526 | 0.941836 |
fh = FeatureHasher(n_features=n_features, input_type="string")
labels = []
lengths = []
with _open(f) as f:
raw_X = _conll_sequences(f, features, labels, lengths, split)
X = fh.transform(raw_X)
return X, np.asarray(labels), np.asarray(lengths, dtype=np.int32) | def load_conll(f, features, n_features=(2 ** 16), split=False) | Load CoNLL file, extract features on the tokens and vectorize them.
The ConLL file format is a line-oriented text format that describes
sequences in a space-separated format, separating the sequences with
blank lines. Typically, the last space-separated part is a label.
Since the tab-separated parts a... | 3.685288 | 4.016164 | 0.917614 |
X = atleast2d_or_csr(X)
scores = safe_sparse_dot(X, self.coef_.T)
if hasattr(self, "coef_trans_"):
n_classes = len(self.classes_)
coef_t = self.coef_trans_.T.reshape(-1, self.coef_trans_.shape[-1])
trans_scores = safe_sparse_dot(X, coef_t.T)
... | def predict(self, X, lengths=None) | Predict labels/tags for samples X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Feature matrix.
lengths : array-like of integer, shape (n_sequences,), optional
Lengths of sequences in X. If not given, X is assumed to be a
... | 2.594239 | 2.792237 | 0.92909 |
return accuracy_score(y, self.predict(X, lengths)) | def score(self, X, y, lengths=None) | Returns the mean accuracy on the given test data and labels.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test samples.
y : array-like, shape = (n_samples,)
True labels for X.
lengths : array-like of integer, shape (n_sequences,... | 4.527335 | 6.955513 | 0.650899 |
if sp.issparse(X):
raise TypeError('A sparse matrix was passed, but dense data '
'is required. Use X.toarray() to convert to dense.')
X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
_assert_all_finite(X_2d)
if X is X_2d and copy:
X_2d = safe_cop... | def array2d(X, dtype=None, order=None, copy=False) | Returns at least 2-d array with data from X | 2.676298 | 2.699408 | 0.991439 |
return _atleast2d_or_sparse(X, dtype, order, copy, sp.csr_matrix,
"tocsr", sp.isspmatrix_csr) | def atleast2d_or_csr(X, dtype=None, order=None, copy=False) | Like numpy.atleast_2d, but converts sparse matrices to CSR format
Also, converts np.matrix to np.ndarray. | 4.980998 | 6.199447 | 0.803458 |
if lengths is None:
lengths = [n_samples]
lengths = np.asarray(lengths, dtype=np.int32)
if lengths.sum() > n_samples:
msg = "More than {0:d} samples in lengths array {1!s}"
raise ValueError(msg.format(n_samples, lengths))
end = np.cumsum(lengths)
start = end - lengths
... | def validate_lengths(n_samples, lengths) | Validate lengths array against n_samples.
Parameters
----------
n_samples : integer
Total number of samples.
lengths : array-like of integers, shape (n_sequences,), optional
Lengths of individual sequences in the input.
Returns
-------
start : array of integers, shape (n_s... | 2.536014 | 2.772979 | 0.914545 |
indices = np.empty(len(y), dtype=np.int32)
for i in six.moves.xrange(len(y) - 1):
indices[i] = y[i] * i + y[i + 1]
indptr = np.arange(len(y) + 1)
indptr[-1] = indptr[-2]
return csr_matrix((np.ones(len(y), dtype=dtype), indices, indptr),
shape=(len(y), n_classes ... | def make_trans_matrix(y, n_classes, dtype=np.float64) | Make a sparse transition matrix for y.
Takes a label sequence y and returns an indicator matrix with n_classes²
columns of the label transitions in y: M[i, j, k] means y[i-1] == j and
y[i] == k. The first row will be empty. | 2.31154 | 2.18734 | 1.056782 |
connector = TCPConnector()
connector._resolve_host = partial(self._old_resolver_mock, connector)
new_is_ssl = ClientRequest.is_ssl
ClientRequest.is_ssl = self._old_is_ssl
try:
original_request = request.clone(scheme="https" if request.headers["AResponsesIsSS... | async def passthrough(self, request) | Make non-mocked network request | 3.502263 | 3.314948 | 1.056506 |
# kazoe hand
if han >= 13 and not is_yakuman:
# Hands over 26+ han don't count as double yakuman
if config.options.kazoe_limit == HandConfig.KAZOE_LIMITED:
han = 13
# Hands over 13+ is a sanbaiman
elif config.options.kazoe_limit =... | def calculate_scores(self, han, fu, config, is_yakuman=False) | Calculate how much scores cost a hand with given han and fu
:param han: int
:param fu: int
:param config: HandConfig object
:param is_yakuman: boolean
:return: a dictionary with main and additional cost
for ron additional cost is always = 0
for tsumo main cost is ... | 2.696469 | 2.60085 | 1.036765 |
# we will modify them later, so we need to use a copy
tiles_34 = copy.deepcopy(tiles_34)
self._init(tiles_34)
count_of_tiles = sum(tiles_34)
if count_of_tiles > 14:
return -2
# With open hand we need to remove open sets from hand and replace them ... | def calculate_shanten(self, tiles_34, open_sets_34=None, chiitoitsu=True, kokushi=True) | Return the count of tiles before tempai
:param tiles_34: 34 tiles format array
:param open_sets_34: array of array of 34 tiles format
:param chiitoitsu: bool
:param kokushi: bool
:return: int | 3.873463 | 4.028078 | 0.961616 |
win_tile //= 4
open_sets = [x.tiles_34 for x in melds if x.opened]
chi_sets = [x for x in hand if (is_chi(x) and win_tile in x and x not in open_sets)]
pon_sets = [x for x in hand if is_pon(x)]
closed_pon_sets = []
for item in pon_sets:
if item in ... | def is_condition_met(self, hand, win_tile, melds, is_tsumo) | Three closed pon sets, the other sets need not to be closed
:param hand: list of hand's sets
:param win_tile: 136 tiles format
:param melds: list Meld objects
:param is_tsumo:
:return: true|false | 5.856681 | 5.393304 | 1.085917 |
pon_sets = [x for x in hand if is_pon(x)]
if len(pon_sets) != 4:
return False
count_wind_sets = 0
winds = [EAST, SOUTH, WEST, NORTH]
for item in pon_sets:
if is_pon(item) and item[0] in winds:
count_wind_sets += 1
return ... | def is_condition_met(self, hand, *args) | The hand contains four sets of winds
:param hand: list of hand's sets
:return: boolean | 3.599446 | 3.305766 | 1.088839 |
if not aka_enabled:
return False
if tile in [FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU]:
return True
return False | def is_aka_dora(tile, aka_enabled) | :param tile: int 136 tiles format
:param aka_enabled: depends on table rules
:return: boolean | 4.522049 | 4.572447 | 0.988978 |
tile_index = tile // 4
dora_count = 0
for dora in dora_indicators:
dora //= 4
# sou, pin, man
if tile_index < EAST:
# with indicator 9, dora will be 1
if dora == 8:
dora = -1
elif dora == 17:
dora = 8
... | def plus_dora(tile, dora_indicators) | :param tile: int 136 tiles format
:param dora_indicators: array of 136 tiles format
:return: int count of dora | 3.575207 | 3.586679 | 0.996802 |
isolated_indices = []
for x in range(0, CHUN + 1):
# for honor tiles we don't need to check nearby tiles
if is_honor(x) and hand_34[x] == 0:
isolated_indices.append(x)
else:
simplified = simplify(x)
# 1 suit tile
if simplified == 0:
... | def find_isolated_tile_indices(hand_34) | Tiles that don't have -1, 0 and +1 neighbors
:param hand_34: array of tiles in 34 tile format
:return: array of isolated tiles indices | 2.458812 | 2.527533 | 0.972811 |
hand_34 = copy.copy(hand_34)
# we don't need to count target tile in the hand
hand_34[tile_34] -= 1
if hand_34[tile_34] < 0:
hand_34[tile_34] = 0
indices = []
if is_honor(tile_34):
return hand_34[tile_34] == 0
else:
simplified = simplify(tile_34)
# 1 su... | def is_tile_strictly_isolated(hand_34, tile_34) | Tile is strictly isolated if it doesn't have -2, -1, 0, +1, +2 neighbors
:param hand_34: array of tiles in 34 tile format
:param tile_34: int
:return: bool | 2.088203 | 2.105665 | 0.991707 |
suits = [
{'count': 0, 'name': 'sou', 'function': is_sou},
{'count': 0, 'name': 'man', 'function': is_man},
{'count': 0, 'name': 'pin', 'function': is_pin},
{'count': 0, 'name': 'honor', 'function': is_honor}
]
for x in range(0, 34):
tile = tiles_34[x]
... | def count_tiles_by_suits(tiles_34) | Separate tiles by suits and count them
:param tiles_34: array of tiles to count
:return: dict | 2.351076 | 2.517127 | 0.934032 |
indices = reduce(lambda z, y: z + y, hand)
return all(x in HONOR_INDICES for x in indices) | def is_condition_met(self, hand, *args) | Hand composed entirely of honour tiles.
:param hand: list of hand's sets
:return: boolean | 10.786852 | 8.309272 | 1.298171 |
if not melds:
melds = []
closed_hand_tiles_34 = tiles_34[:]
# small optimization, we can't have a pair in open part of the hand,
# so we don't need to try find pairs in open sets
open_tile_indices = melds and reduce(lambda x, y: x + y, [x.tiles_34 for x in ... | def divide_hand(self, tiles_34, melds=None) | Return a list of possible hands.
:param tiles_34:
:param melds: list of Meld objects
:return: | 2.548018 | 2.569809 | 0.99152 |
pair_indices = []
for x in range(first_index, second_index + 1):
# ignore pon of honor tiles, because it can't be a part of pair
if x in HONOR_INDICES and tiles_34[x] != 2:
continue
if tiles_34[x] >= 2:
pair_indices.append(x)
... | def find_pairs(self, tiles_34, first_index=0, second_index=33) | Find all possible pairs in the hand and return their indices
:return: array of pair indices | 3.888299 | 3.871389 | 1.004368 |
indices = []
for x in range(first_index, second_index + 1):
if tiles_34[x] > 0:
indices.extend([x] * tiles_34[x])
if not indices:
return []
all_possible_combinations = list(itertools.permutations(indices, 3))
def is_valid_combin... | def find_valid_combinations(self, tiles_34, first_index, second_index, hand_not_completed=False) | Find and return all valid set combinations in given suit
:param tiles_34:
:param first_index:
:param second_index:
:param hand_not_completed: in that mode we can return just possible shi\pon sets
:return: list of valid combinations | 2.39956 | 2.353692 | 1.019488 |
tiles = sorted(tiles)
man = [t for t in tiles if t < 36]
pin = [t for t in tiles if 36 <= t < 72]
pin = [t - 36 for t in pin]
sou = [t for t in tiles if 72 <= t < 108]
sou = [t - 72 for t in sou]
honors = [t for t in tiles if t >= 108]
honors ... | def to_one_line_string(tiles) | Convert 136 tiles array to the one line string
Example of output 123s123p123m33z | 1.931294 | 1.845759 | 1.046341 |
temp = []
results = []
for x in range(0, 34):
if tiles[x]:
temp_value = [x * 4] * tiles[x]
for tile in temp_value:
if tile in results:
count_of_tiles = len([x for x in temp if x == tile])
... | def to_136_array(tiles) | Convert 34 array to the 136 tiles array | 3.604491 | 3.247018 | 1.110093 |
def _split_string(string, offset, red=None):
data = []
temp = []
if not string:
return []
for i in string:
if i == 'r' and has_aka_dora:
temp.append(red)
data.append(red)
... | def string_to_136_array(sou=None, pin=None, man=None, honors=None, has_aka_dora=False) | Method to convert one line string tiles format to the 136 array.
You can pass r instead of 5 for it to become a red five from
that suit. To prevent old usage without red,
has_aka_dora has to be True for this to do that.
We need it to increase readability of our tests | 3.322347 | 3.085334 | 1.076819 |
results = TilesConverter.string_to_136_array(sou, pin, man, honors)
results = TilesConverter.to_34_array(results)
return results | def string_to_34_array(sou=None, pin=None, man=None, honors=None) | Method to convert one line string tiles format to the 34 array
We need it to increase readability of our tests | 3.738542 | 3.115901 | 1.199827 |
if tile34 is None or tile34 > 33:
return None
tile = tile34 * 4
possible_tiles = [tile] + [tile + i for i in range(1, 4)]
found_tile = None
for possible_tile in possible_tiles:
if possible_tile in tiles:
found_tile = possible_ti... | def find_34_tile_in_136_array(tile34, tiles) | Our shanten calculator will operate with 34 tiles format,
after calculations we need to find calculated 34 tile
in player's 136 tiles.
For example we had 0 tile from 34 array
in 136 array it can be present as 0, 1, 2, 3 | 2.656889 | 2.856431 | 0.930143 |
def value(self):
return self._sign[1] * self.S0 * norm.cdf(
self._sign[1] * self.d1, 0.0, 1.0
) - self._sign[1] * self.K * np.exp(-self.r * self.T) * norm.cdf(
self._sign[1] * self.d2, 0.0, 1.0
) | Compute option value according to BSM model. | null | null | null | |
def implied_vol(self, value, precision=1.0e-5, iters=100):
vol = np.sqrt(2.0 * np.pi / self.T) * (value / self.S0)
for _ in itertools.repeat(None, iters): # Faster than range
opt = BSM(
S0=self.S0,
K=self.K,
T=self.T,
... | Get implied vol at the specified price using an iterative approach.
There is no closed-form inverse of BSM-value as a function of sigma,
so start at an anchoring volatility level from Brenner & Subrahmanyam
(1988) and work iteratively from there.
Resources
---------
... | null | null | null | |
def add_option(self, K=None, price=None, St=None, kind="call", pos="long"):
kinds = {
"call": Call,
"Call": Call,
"c": Call,
"C": Call,
"put": Put,
"Put": Put,
"p": Put,
"P": Put,
}
... | Add an option to the object's `options` container. | null | null | null | |
def summary(self, St=None):
St = self.St if St is None else St
if self.options:
payoffs = [op.payoff(St=St) for op in self.options]
profits = [op.profit(St=St) for op in self.options]
strikes = [op.K for op in self.options]
prices = [op.p... | Tabular summary of strategy composition, broken out by option.
Returns
-------
pd.DataFrame
Columns: kind, position, strike, price, St, payoff, profit. | null | null | null | |
def grid(self, start=None, stop=None, St=None, **kwargs):
lb = 0.75
rb = 1.25
if not any((start, stop, St)) and self.St is None:
St = np.mean([op.K for op in self.options], axis=0)
start = St * lb
stop = St * rb
elif not any((start, ... | Grid-like representation of payoff & profit structure.
Returns
-------
tuple
Tuple of `St` (price at expiry), `payoffs`, `profits`. | null | null | null | |
def _rolling_lstsq(x, y):
if x.ndim == 2:
# Treat everything as 3d and avoid AxisError on .swapaxes(1, 2) below
# This means an original input of:
# array([0., 1., 2., 3., 4., 5., 6.])
# becomes:
# array([[[0.],
# [1.],
# [2.]... | Finds solution for the rolling case. Matrix formulation. | null | null | null | |
def _confirm_constant(a):
a = np.asanyarray(a)
return np.isclose(a, 1.0).all(axis=0).any() | Confirm `a` has volumn vector of 1s. | null | null | null | |
def _check_constant_params(
a, has_const=False, use_const=True, rtol=1e-05, atol=1e-08
):
if all((has_const, use_const)):
if not _confirm_constant(a):
raise ValueError(
"Data does not contain a constant; specify" " has_const=False"
)
k = a.... | Helper func to interaction between has_const and use_const params.
has_const use_const outcome
--------- --------- -------
True True Confirm that a has constant; return a
False False Confirm that a doesn't have constant; return a
False True Confi... | null | null | null | |
def condition_number(self):
# Mimic x = np.matrix(self.x) (deprecated)
x = np.atleast_2d(self.x)
ev = np.linalg.eig(x.T @ x)[0]
return np.sqrt(ev.max() / ev.min()) | Condition number of x; ratio of largest to smallest eigenvalue. | null | null | null | |
def fstat_sig(self):
return 1.0 - scs.f.cdf(self.fstat, self.df_reg, self.df_err) | p-value of the F-statistic. | null | null | null | |
def _pvalues_all(self):
return 2.0 * (1.0 - scs.t.cdf(np.abs(self._tstat_all), self.df_err)) | Two-tailed p values for t-stats of all parameters. | null | null | null | |
def rsq_adj(self):
n = self.n
k = self.k
return 1.0 - ((1.0 - self.rsq) * (n - 1.0) / (n - k - 1.0)) | Adjusted R-squared. | null | null | null | |
def _se_all(self):
x = np.atleast_2d(self.x)
err = np.atleast_1d(self.ms_err)
se = np.sqrt(np.diagonal(np.linalg.inv(x.T @ x)) * err[:, None])
return np.squeeze(se) | Standard errors (SE) for all parameters, including the intercept. | null | null | null | |
def ss_tot(self):
return np.sum(np.square(self.y - self.ybar), axis=0) | Total sum of squares. | null | null | null | |
def ss_reg(self):
return np.sum(np.square(self.predicted - self.ybar), axis=0) | Sum of squares of the regression. | null | null | null | |
def std_err(self):
return np.sqrt(np.sum(np.square(self.resids), axis=0) / self.df_err) | Standard error of the estimate (SEE). A scalar.
For standard errors of parameters, see _se_all, se_alpha, and se_beta. | null | null | null | |
def _std_err(self):
return np.sqrt(np.sum(np.square(self._resids), axis=1) / self._df_err) | Standard error of the estimate (SEE). A scalar.
For standard errors of parameters, see _se_all, se_alpha, and se_beta. | null | null | null | |
def _predicted(self):
return np.squeeze(
np.matmul(self.xwins, np.expand_dims(self.solution, axis=-1))
) | The predicted values of y ('yhat'). | null | null | null | |
def _ss_tot(self):
return np.sum(
np.square(self.ywins - np.expand_dims(self._ybar, axis=-1)), axis=1
) | Total sum of squares. | null | null | null | |
def _ss_reg(self):
return np.sum(
np.square(self._predicted - np.expand_dims(self._ybar, axis=1)),
axis=1,
) | Sum of squares of the regression. | null | null | null | |
def _rsq_adj(self):
n = self.n
k = self.k
return 1.0 - ((1.0 - self._rsq) * (n - 1.0) / (n - k - 1.0)) | Adjusted R-squared. | null | null | null | |
def _fstat_sig(self):
return 1.0 - scs.f.cdf(self._fstat, self._df_reg, self._df_err) | p-value of the F-statistic. | null | null | null | |
def _se_all(self):
err = np.expand_dims(self._ms_err, axis=1)
t1 = np.diagonal(
np.linalg.inv(np.matmul(self.xwins.swapaxes(1, 2), self.xwins)),
axis1=1,
axis2=2,
)
return np.squeeze(np.sqrt(t1 * err)) | Standard errors (SE) for all parameters, including the intercept. | null | null | null | |
def _condition_number(self):
ev = np.linalg.eig(np.matmul(self.xwins.swapaxes(1, 2), self.xwins))[0]
return np.sqrt(ev.max(axis=1) / ev.min(axis=1)) | Condition number of x; ratio of largest to smallest eigenvalue. | null | null | null | |
def activeshare(fund, idx, in_format="num"):
if not (fund.index.is_unique) and (idx.index.is_unique):
raise ValueError("Inputs must have unique indices.")
if isinstance(fund, pd.DataFrame):
cols = fund.columns
fund = fund * NUMTODEC[in_format]
idx = idx * NUMTODEC[in_format... | Compute the active ahare of a fund versus an index.
Formula is 0.5 * sum(abs(w_fund - w_idx)).
Parameters
----------
fund: {pd.Series, pd.DataFrame}
The fund's holdings, with tickers as the Index and weights as
values. If a DataFrame, each column is a ticker/portfolio.
id... | null | null | null | |
def amortize(rate, nper, pv, freq="M"):
freq = utils.get_anlz_factor(freq)
rate = rate / freq
nper = nper * freq
periods = np.arange(1, nper + 1, dtype=int)
principal = np.ppmt(rate, periods, nper, pv)
interest = np.ipmt(rate, periods, nper, pv)
pmt = np.pmt(rate, nper, pv... | Construct an amortization schedule for a fixed-rate loan.
Rate -> annualized input
Example
-------
# a 6.75% $200,000 loan, 30-year tenor, payments due monthly
# view the 5 final months
print(amortize(rate=.0675, nper=30, pv=200000).round(2).tail())
beg_bal prin interest... | null | null | null | |
def corr_heatmap(
x,
mask_half=True,
cmap="RdYlGn_r",
vmin=-1,
vmax=1,
linewidths=0.5,
square=True,
figsize=(10, 10),
**kwargs
):
if mask_half:
mask = np.zeros_like(x.corr().values)
mask[np.triu_indices_from(mask)] = True
else:
m... | Wrapper around seaborn.heatmap for visualizing correlation matrix.
Parameters
----------
x : DataFrame
Underlying data (not a correlation matrix)
mask_half : bool, default True
If True, mask (whiteout) the upper right triangle of the matrix
All other parameters passed to sea... | null | null | null | |
def ewm_params(param, param_value):
if param not in ["alpha", "com", "span", "halflife"]:
raise NameError("`param` must be one of {alpha, com, span, halflife}")
def input_alpha(a):
com = 1.0 / a - 1.0
span = 2.0 / a - 1.0
halflife = np.log(0.5) / np.log(1.0 - a)
... | Corresponding parameter values for exponentially weighted functions.
Parameters
----------
param : {'alpha', 'com', 'span', 'halflife'}
param_value : float or int
The parameter value.
Returns
-------
result : dict
Layout/index of corresponding parameters. | null | null | null | |
def ewm_weights(i, com=None, span=None, halflife=None, alpha=None):
if not any((com, span, halflife, alpha)):
raise ValueError("specify one of `com`, `span`, `halflife`, `alpha`")
params = [com, span, halflife, alpha]
pos = next(i for (i, x) in enumerate(params) if x)
param_value ... | Exponential weights as a function of position `i`.
Mimics pandas' methodology with adjust=True:
http://pandas.pydata.org/pandas-docs/stable/computation.html#exponentially-weighted-windows | null | null | null | |
def ewm_bootstrap(
a, size=None, com=None, span=None, halflife=None, alpha=None
):
if not any((com, span, halflife, alpha)):
raise ValueError("Specify one of `com`, `span`, `halflife`, `alpha`.")
p = ewm_weights(
i=len(a), com=com, span=span, halflife=halflife, alpha=alpha
... | Bootstrap a new distribution through exponential weighting.
Parameters
----------
a : 1-D array-like
Array from which to generate random sample of elements
size : int or tuple of ints, default None
Output shape. If None, a single value is returned
com : float, default None
... | null | null | null | |
def variance_inflation_factor(regressors, hasconst=False):
if not hasconst:
regressors = add_constant(regressors, prepend=False)
k = regressors.shape[1]
def vif_sub(x, regressors):
x_i = regressors.iloc[:, x]
mask = np.arange(k) != x
x_not_i = regressors.iloc... | Calculate variance inflation factor (VIF) for each all `regressors`.
A wrapper/modification of statsmodels:
statsmodels.stats.outliers_influence.variance_inflation_factor
One recommendation is that if VIF is greater than 5, then the explanatory
variable `x` is highly collinear with the other exp... | null | null | null | |
def fit(self):
# Defaults/anchors
best_sse = np.inf
best_param = (0.0, 1.0)
best_dist = scs.norm
# Compute the histogram of `x`. density=True gives a probability
# density function at each bin, normalized such that the integral over
# the ran... | Fit each distribution to `data` and calculate an SSE.
WARNING: significant runtime. (~1min) | null | null | null | |
def best(self):
return pd.Series(
{
"name": self.best_dist.name,
"params": self.best_param,
"sse": self.best_sse,
}
) | The resulting best-fit distribution, its parameters, and SSE. | null | null | null | |
def all(self, by="name", ascending=True):
res = pd.DataFrame(
{
"name": self.distributions,
"params": self.params,
"sse": self.sses,
}
)[["name", "sse", "params"]]
res.sort_values(by=by, ascending=ascending... | All tested distributions, their parameters, and SSEs. | null | null | null | |
def plot(self):
plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf) | Plot the empirical histogram versus best-fit distribution's PDF. | null | null | null | |
def fit(self):
self.n_samples, self.n_features = self.ms.shape
self.u, self.s, self.vt = np.linalg.svd(self.ms, full_matrices=False)
self.v = self.vt.T
# sklearn's implementation is to guarantee that the left and right
# singular vectors (U and V) are always th... | Fit the model by computing full SVD on m.
SVD factors the matrix m as u * np.diag(s) * v, where u and v are
unitary and s is a 1-d array of m‘s singular values. Note that the SVD
is commonly written as a = U S V.H, and the v returned by this function
is V.H (the Hermitian transpos... | null | null | null | |
def eigen_table(self):
idx = ["Eigenvalue", "Variability (%)", "Cumulative (%)"]
table = pd.DataFrame(
np.array(
[self.eigenvalues, self.inertia, self.cumulative_inertia]
),
columns=["F%s" % i for i in range(1, self.keep + 1)],
... | Eigenvalues, expl. variance, and cumulative expl. variance. | null | null | null | |
def loadings(self):
loadings = self.v[:, : self.keep] * np.sqrt(self.eigenvalues)
cols = ["PC%s" % i for i in range(1, self.keep + 1)]
loadings = pd.DataFrame(
loadings, columns=cols, index=self.feature_names
)
return loadings | Loadings = eigenvectors times sqrt(eigenvalues). | null | null | null | |
def optimize(self):
def te(weights, r, proxies):
if isinstance(weights, list):
weights = np.array(weights)
proxy = np.sum(proxies * weights, axis=1)
te = np.std(proxy - r) # not anlzd...
return te
ew = ut... | Analogous to `sklearn`'s fit. Returns `self` to enable chaining. | null | null | null | |
def opt_weights(self):
return pd.DataFrame(self._xs, index=self.newidx, columns=self.cols) | Optimal weights (period-end). | null | null | null | |
def replicate(self):
return np.sum(
self.proxies[self.window :] * self._xs[:-1], axis=1
).reindex(self.r.index) | Forward-month returns of the replicating portfolio. | null | null | null | |
if isinstance(obj, pd.Series):
return obj
elif isinstance(obj, pd.DataFrame) and obj.shape[-1] == 1:
return obj.squeeze()
else:
if raise_:
raise ValueError("Input cannot be squeezed.")
return obj | def _try_to_squeeze(obj, raise_=False) | Attempt to squeeze to 1d Series.
Parameters
----------
obj : {pd.Series, pd.DataFrame}
raise_ : bool, default False | 2.876479 | 2.727552 | 1.054601 |
if self.index.is_all_dates:
# TODO: Could be more granular here,
# for cases with < day frequency.
td = self.index[-1] - self.index[0]
n = td.total_seconds() / SECS_PER_CAL_YEAR
else:
# We don't have a datetime-like Index, so as... | def anlzd_ret(self, freq=None) | Annualized (geometric) return.
Parameters
----------
freq : str or None, default None
A frequency string used to create an annualization factor.
If None, `self.freq` will be used. If that is also None,
a frequency will be inferred. If none can be inferred,
... | 7.507804 | 7.105745 | 1.056582 |
if freq is None:
freq = self._try_get_freq()
if freq is None:
raise FrequencyError(msg)
return nanstd(self, ddof=ddof) * freq ** 0.5 | def anlzd_stdev(self, ddof=0, freq=None, **kwargs) | Annualized standard deviation with `ddof` degrees of freedom.
Parameters
----------
ddof : int, default 0
Degrees of freedom, passed to pd.Series.std().
freq : str or None, default None
A frequency string used to create an annualization factor.
If Non... | 5.176009 | 5.791708 | 0.893693 |
diff = self.excess_ret(benchmark)
return np.count_nonzero(diff > 0.0) / diff.count() | def batting_avg(self, benchmark) | Percentage of periods when `self` outperformed `benchmark`.
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarray}
The benchmark security to which `self` is compared.
Returns
-------
float | 9.027723 | 9.065283 | 0.995857 |
beta = self.beta(benchmark=benchmark, **kwargs)
return adj_factor * beta + (1 - adj_factor) | def beta_adj(self, benchmark, adj_factor=2 / 3, **kwargs) | Adjusted beta.
Beta that is adjusted to reflect the tendency of beta to
be mean reverting.
[Source: CFA Institute]
Formula:
adj_factor * raw_beta + (1 - adj_factor)
Parameters
----------
benchmark : {pd.Series, TSeries, pd.DataFrame, np.ndarray}
... | 3.532933 | 5.62323 | 0.628275 |
if isinstance(compare_op(tuple, list)):
op1, op2 = compare_op
else:
op1, op2 = compare_op, compare_op
uc = self.up_capture(
benchmark=benchmark, threshold=threshold, compare_op=op1
)
dc = self.down_capture(
benchmark=bench... | def capture_ratio(self, benchmark, threshold=0.0, compare_op=("ge", "lt")) | Capture ratio--ratio of upside to downside capture.
Upside capture ratio divided by the downside capture ratio.
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarray}
The benchmark security to which `self` is compared.
threshold : float, default 0.
... | 3.409187 | 2.596943 | 1.312769 |
slf, bm = self.downmarket_filter(
benchmark=benchmark,
threshold=threshold,
compare_op=compare_op,
include_benchmark=True,
)
return slf.geomean() / bm.geomean() | def down_capture(self, benchmark, threshold=0.0, compare_op="lt") | Downside capture ratio.
Measures the performance of `self` relative to benchmark
conditioned on periods where `benchmark` is lt or le to
`threshold`.
Downside capture ratios are calculated by taking the fund's
monthly return during the periods of negative benchmark
perf... | 6.963277 | 5.941056 | 1.172061 |
return self._mkt_filter(
benchmark=benchmark,
threshold=threshold,
compare_op=compare_op,
include_benchmark=include_benchmark,
) | def downmarket_filter(
self,
benchmark,
threshold=0.0,
compare_op="lt",
include_benchmark=False,
) | Drop elementwise samples where `benchmark` > `threshold`.
Filters `self` (and optionally, `benchmark`) to periods
where `benchmark` < `threshold`. (Or <= `threshold`.)
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarray}
The benchmark security to w... | 2.459722 | 3.311522 | 0.742777 |
end = self.drawdown_idx().idxmin()
if return_date:
return end.date()
return end | def drawdown_end(self, return_date=False) | The date of the drawdown trough.
Date at which the drawdown was most negative.
Parameters
----------
return_date : bool, default False
If True, return a `datetime.date` object.
If False, return a Pandas Timestamp object.
Returns
-------
... | 7.264731 | 8.47022 | 0.857679 |
ri = self.ret_idx()
return ri / np.maximum(ri.cummax(), 1.0) - 1.0 | def drawdown_idx(self) | Drawdown index; TSeries of drawdown from running HWM.
Returns
-------
TSeries | 9.786596 | 8.152183 | 1.200488 |
td = self.drawdown_end() - self.drawdown_start()
if return_int:
return td.days
return td | def drawdown_length(self, return_int=False) | Length of drawdown in days.
This is the duration from peak to trough.
Parameters
----------
return_int : bool, default False
If True, return the number of days as an int.
If False, return a Pandas Timedelta object.
Returns
-------
int or... | 4.199407 | 4.805116 | 0.873945 |
td = self.recov_date() - self.drawdown_end()
if return_int:
return td.days
return td | def drawdown_recov(self, return_int=False) | Length of drawdown recovery in days.
This is the duration from trough to recovery date.
Parameters
----------
return_int : bool, default False
If True, return the number of days as an int.
If False, return a Pandas Timedelta object.
Returns
----... | 6.718613 | 6.951442 | 0.966506 |
# Thank you @cᴏʟᴅsᴘᴇᴇᴅ
# https://stackoverflow.com/a/47892766/7954504
dd = self.drawdown_idx()
mask = nancumsum(dd == nanmin(dd.min)).astype(bool)
start = dd.mask(mask)[::-1].idxmax()
if return_date:
return start.date()
return start | def drawdown_start(self, return_date=False) | The date of the peak at which most severe drawdown began.
Parameters
----------
return_date : bool, default False
If True, return a `datetime.date` object.
If False, return a Pandas Timestamp object.
Returns
-------
datetime.date or pandas._libs.... | 9.307024 | 9.717454 | 0.957764 |
# TODO: plot these (compared) in docs.
if isinstance(method, (int, float)):
method = ["caer", "cger", "ecr", "ecrr"][method]
method = method.lower()
if method == "caer":
er = self.excess_ret(benchmark=benchmark, method="arithmetic")
return e... | def excess_drawdown_idx(self, benchmark, method="caer") | Excess drawdown index; TSeries of excess drawdowns.
There are several ways of computing this metric. For highly
volatile returns, the `method` specified will have a
non-negligible effect on the result.
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarra... | 4.305018 | 3.881899 | 1.108998 |
if method.startswith("arith"):
return self - _try_to_squeeze(benchmark)
elif method.startswith("geo"):
# Geometric excess return,
# (1 + `self`) / (1 + `benchmark`) - 1.
return (
self.ret_rels() / _try_to_squeeze(benchmark).ret_re... | def excess_ret(self, benchmark, method="arithmetic") | Excess return.
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarray}
The benchmark security to which `self` is compared.
method : {{'arith', 'arithmetic'}, {'geo', 'geometric'}}
The methodology used. An arithmetic excess return is a
s... | 7.761766 | 5.046643 | 1.538006 |
gt = self > 0
lt = self < 0
return (nansum(gt) / nansum(lt)) * (self[gt].mean() / self[lt].mean()) | def gain_to_loss_ratio(self) | Gain-to-loss ratio, ratio of positive to negative returns.
Formula:
(n pos. / n neg.) * (avg. up-month return / avg. down-month return)
[Source: CFA Institute]
Returns
-------
float | 6.010458 | 6.42087 | 0.936082 |
diff = self.excess_ret(benchmark).anlzd_ret()
return diff / self.tracking_error(benchmark, ddof=ddof) | def info_ratio(self, benchmark, ddof=0) | Information ratio--return per unit of active risk.
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarray}
The benchmark security to which `self` is compared.
ddof : int, default 0
Degrees of freedom, passed to pd.Series.std().
Returns
... | 14.183802 | 15.794175 | 0.89804 |
rf = self._validate_rf(rf)
scaling = benchmark.anlzd_stdev(ddof) / self.anlzd_stdev(ddof)
diff = self.anlzd_ret() - rf
return rf + diff * scaling | def msquared(self, benchmark, rf=0.02, ddof=0) | M-squared, return scaled by relative total risk.
A measure of what a portfolio would have returned if it had
taken on the same *total* risk as the market index.
[Source: CFA Institute]
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarray}
The... | 7.690842 | 10.128151 | 0.759353 |
return np.count_nonzero(self[self < threshold]) / self.count() | def pct_negative(self, threshold=0.0) | Pct. of periods in which `self` is less than `threshold.`
Parameters
----------
threshold : {float, TSeries, pd.Series}, default 0.
Returns
-------
float | 8.926801 | 9.916154 | 0.900228 |
return np.count_nonzero(self[self > threshold]) / self.count() | def pct_positive(self, threshold=0.0) | Pct. of periods in which `self` is greater than `threshold.`
Parameters
----------
threshold : {float, TSeries, pd.Series}, default 0.
Returns
-------
float | 8.891481 | 10.109255 | 0.879539 |
dd = self.drawdown_idx()
# False beginning on trough date and all later dates.
mask = nancumprod(dd != nanmin(dd)).astype(bool)
res = dd.mask(mask) == 0
# If `res` is all False (recovery has not occured),
# .idxmax() will return `res.index[0]`.
if not r... | def recov_date(self, return_date=False) | Drawdown recovery date.
Date at which `self` recovered to previous high-water mark.
Parameters
----------
return_date : bool, default False
If True, return a `datetime.date` object.
If False, return a Pandas Timestamp object.
Returns
-------
... | 10.048148 | 8.445644 | 1.189743 |
return self.ret_rels().resample(freq, **kwargs).prod() - 1.0 | def rollup(self, freq, **kwargs) | Downsample `self` through geometric linking.
Parameters
----------
freq : {'D', 'W', 'M', 'Q', 'A'}
The frequency of the result.
**kwargs
Passed to `self.resample()`.
Returns
-------
TSeries
Example
-------
# Deri... | 24.899424 | 30.544909 | 0.815174 |
if freq is None:
freq = self._try_get_freq()
if freq is None:
raise FrequencyError(msg)
n = self.count() - ddof
ss = (nansum(np.minimum(self - threshold, 0.0) ** 2) ** 0.5) / n
return ss * freq ** 0.5 | def semi_stdev(self, threshold=0.0, ddof=0, freq=None) | Semi-standard deviation; stdev of downside returns.
It is designed to address that fact that plain standard
deviation penalizes "upside volatility.""
Formula: `sqrt( sum([min(self - thresh, 0] **2 ) / (n - ddof) )`
Also known as: downside deviation.
Parameters
-------... | 4.918073 | 4.880328 | 1.007734 |
rf = self._validate_rf(rf)
stdev = self.anlzd_stdev(ddof=ddof)
return (self.anlzd_ret() - rf) / stdev | def sharpe_ratio(self, rf=0.02, ddof=0) | Return over `rf` per unit of total risk.
The average return in excess of the risk-free rate divided
by the standard deviation of return; a measure of the average
excess return earned per unit of standard deviation of return.
[Source: CFA Institute]
Parameters
----------... | 6.097524 | 7.912508 | 0.770618 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.