Skip to content

Commit

Permalink
Merge branch 'dev' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
chilango74 committed Aug 17, 2021
2 parents d8e363d + 4adcff7 commit b89cbc8
Show file tree
Hide file tree
Showing 11 changed files with 34 additions and 34 deletions.
6 changes: 3 additions & 3 deletions okama/asset_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ def get_cagr(self, period: Optional[int] = None, real: bool = False) -> pd.Serie
cagr = Frame.get_cagr(df[dt:])
if real:
if not hasattr(self, "inflation"):
raise Exception(
raise ValueError(
"Real CAGR is not defined. Set inflation=True in AssetList to calculate it."
)
mean_inflation = Frame.get_cagr(self.inflation_ts[dt:])
Expand Down Expand Up @@ -389,7 +389,7 @@ def get_cumulative_return(
cr = Frame.get_cumulative_return(df[dt:])
if real:
if not hasattr(self, "inflation"):
raise Exception(
raise ValueError(
"Real cumulative return is not defined (no inflation information is available)."
"Set inflation=True in AssetList to calculate it."
)
Expand Down Expand Up @@ -613,7 +613,7 @@ def real_mean_return(self) -> pd.Series:
dtype: float64
"""
if not hasattr(self, "inflation"):
raise Exception(
raise ValueError(
"Real Return is not defined. Set inflation=True to calculate."
)
df = pd.concat(
Expand Down
2 changes: 1 addition & 1 deletion okama/common/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def get_okid_index(rates: pd.Series, symbol: str) -> pd.Series:
)
start_period += 1
if index_total is None:
raise Exception("`index_total` should not be `None`")
raise ValueError("`index_total` should not be `None`")
result = index_total
result = (np.diff(result) / result[:-1] + 1.0).cumprod() - 1.0
result = [0] + result
Expand Down
2 changes: 1 addition & 1 deletion okama/common/make_asset_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ def _make_real_return_time_series(self, df: pd.DataFrame) -> pd.DataFrame:
Rate of return monthly data is adjusted for inflation.
"""
if not hasattr(self, "inflation"):
raise Exception(
raise ValueError(
"Real return is not defined. Set inflation=True when initiating the class."
)
df = (1.0 + df).divide(1.0 + self.inflation_ts, axis=0) - 1.0
Expand Down
10 changes: 5 additions & 5 deletions okama/frontier/multi_period.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def _get_cagr(self, weights):
acc_return = (ts + 1.).prod() - 1.
return (1. + acc_return) ** (_MONTHS_PER_YEAR / ts.shape[0]) - 1.

def minimize_risk(self, target_return: float) -> Dict[str, float]:
def minimize_risk(self, target_value: float) -> Dict[str, float]:
"""
Returns the optimal weights and risk / cagr values for a min risk at the target cagr.
"""
Expand All @@ -253,7 +253,7 @@ def objective_function(w):
'fun': lambda weights: np.sum(weights) - 1
}
cagr_is_target = {'type': 'eq',
'fun': lambda weights: target_return - self._get_cagr(weights)
'fun': lambda weights: target_value - self._get_cagr(weights)
}

weights = minimize(objective_function,
Expand All @@ -270,10 +270,10 @@ def objective_function(w):
if weights.success:
asset_labels = self.symbols if self.ticker_names else list(self.names.values())
point = {x: y for x, y in zip(asset_labels, weights.x)}
point['CAGR'] = target_return
point['CAGR'] = target_value
point['Risk'] = weights.fun
else:
raise Exception(f'There is no solution for target cagr {target_return}.')
raise RecursionError(f'No solution found for target risk value: {target_value}.')
return point

def maximize_risk(self, target_return: float) -> Dict[str, float]:
Expand Down Expand Up @@ -319,7 +319,7 @@ def objective_function(w):
point['CAGR'] = target_return
point['Risk'] = - weights.fun
else:
raise Exception(f'There is no solution for target cagr {target_return}.')
raise RecursionError(f'No solution found for target risk value: {target_return}.')
return point

@property
Expand Down
6 changes: 3 additions & 3 deletions okama/frontier/single_period.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def gmv_weights(self) -> np.ndarray:
if weights.success:
return weights.x
else:
raise Exception("No solutions where found")
raise RecursionError("No solutions where found")

@property
def gmv_monthly(self) -> Tuple[float, float]:
Expand Down Expand Up @@ -169,7 +169,7 @@ def objective_function(w, ror):
}
return point
else:
raise Exception("No solutions where found")
raise RecursionError("No solutions where found")

def minimize_risk(
self,
Expand Down Expand Up @@ -233,7 +233,7 @@ def objective_function(w):
# point['CAGR (approx)'] = r_gmean
point["Risk"] = a_risk
else:
raise Exception("No solutions were found")
raise RecursionError("No solutions were found")
return point

@property
Expand Down
6 changes: 3 additions & 3 deletions okama/macro.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def _check_namespace(self):
namespace = self.symbol.split(".", 1)[-1]
allowed_namespaces = get_macro_namespaces()
if namespace not in allowed_namespaces:
raise Exception(
raise ValueError(
f"{namespace} is not in allowed namespaces: {allowed_namespaces}"
)

Expand Down Expand Up @@ -76,7 +76,7 @@ def cumulative_inflation(self) -> pd.Series:
Return cumulative inflation rate time series for a period from first_date to last_date.
"""
if self.symbol.split(".", 1)[-1] != "INFL":
raise Exception("cumulative_inflation is defined for inflation only")
raise ValueError("cumulative_inflation is defined for inflation only")
return (self.values_ts + 1.0).cumprod() - 1.0

@property
Expand All @@ -96,7 +96,7 @@ def rolling_inflation(self) -> pd.Series:
Return 12 months rolling inflation time series.
"""
if self.symbol.split(".", 1)[-1] != "INFL":
raise Exception("cumulative_inflation is defined for inflation only")
raise ValueError("cumulative_inflation is defined for inflation only")
x = (self.values_ts + 1.0).rolling(_MONTHS_PER_YEAR).apply(
np.prod, raw=True
) - 1.0
Expand Down
6 changes: 3 additions & 3 deletions okama/portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ def get_cagr(self, period: Optional[int] = None, real: bool = False) -> pd.Serie
cagr = Frame.get_cagr(df[dt:])
if real:
if not hasattr(self, "inflation"):
raise Exception(
raise ValueError(
"Real CAGR is not defined. Set inflation=True in Portfolio to calculate it."
)
mean_inflation = Frame.get_cagr(self.inflation_ts[dt:])
Expand Down Expand Up @@ -557,7 +557,7 @@ def get_cumulative_return(self, period: Union[str, int, None] = None, real: bool
cr = Frame.get_cumulative_return(df[dt:])
if real:
if not hasattr(self, "inflation"):
raise Exception(
raise ValueError(
"Real cumulative return is not defined (no inflation information is available)."
"Set inflation=True in Portfolio to calculate it."
)
Expand Down Expand Up @@ -723,7 +723,7 @@ def real_mean_return(self) -> float:
0.3088967455111862
"""
if not hasattr(self, "inflation"):
raise Exception(
raise ValueError(
"Real Return is not defined. Set inflation=True to calculate."
)
infl_mean = Float.annualize_return(self.inflation_ts.mean())
Expand Down
12 changes: 6 additions & 6 deletions tests/test_asset_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

@mark.asset_list
def test_asset_list_init_failing():
with pytest.raises(Exception, match=r"Assets must be a list."):
with pytest.raises(ValueError, match=r"Assets must be a list."):
ok.AssetList(assets=("RUB.FX", "MCFTR.INDX"))


Expand Down Expand Up @@ -153,7 +153,7 @@ def test_get_cagr_value_error(self):
self.asset_list.get_cagr(period=3, real=True)

def test_get_cagr_real_no_inflation_exception(self):
with pytest.raises(Exception):
with pytest.raises(ValueError):
self.asset_list_no_infl.get_cagr(period=1, real=True)

@pytest.mark.parametrize(
Expand All @@ -171,7 +171,7 @@ def test_get_rolling_cagr(self, real, expected1, expected2):
(0, False, ValueError), # window should be at least 12 months for CAGR
(12.5, False, ValueError), # not an integer
(10 * 12, False, ValueError), # window size should be in the history period
(12, True, Exception), # real CAGR is defined when AssetList(inflation=True) only
(12, True, ValueError), # real CAGR is defined when AssetList(inflation=True) only
]

@pytest.mark.parametrize("window, real, exception", get_rolling_cagr_error_data)
Expand Down Expand Up @@ -221,7 +221,7 @@ def test_get_cumulative_return_value_error(self):
self.asset_list.get_cumulative_return(period=3, real=True)

def test_get_cumulative_return_real_no_inflation_exception(self):
with pytest.raises(Exception):
with pytest.raises(ValueError):
self.asset_list_no_infl.get_cumulative_return(period=1, real=True)

def test_get_rolling_cumulative_return(self):
Expand Down Expand Up @@ -286,7 +286,7 @@ def test_get_dividend_mean_growth_rate_value_err(self):

def test_tracking_difference_failing(self):
with pytest.raises(
Exception,
ValueError,
match="At least 2 symbols should be provided to calculate Tracking Difference.",
):
self.spy.tracking_difference
Expand Down Expand Up @@ -318,7 +318,7 @@ def test_skewness(self):

def test_rolling_skewness_failing(self):
with pytest.raises(
Exception, match=r"window size is more than data history depth"
ValueError, match=r"window size is more than data history depth"
):
self.asset_list.skewness_rolling(window=24)

Expand Down
4 changes: 2 additions & 2 deletions tests/test_frontier.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@

@mark.frontier
def test_init_efficient_frontier_failing():
with pytest.raises(Exception, match=r'The number of symbols cannot be less than two'):
with pytest.raises(ValueError, match=r'The number of symbols cannot be less than two'):
ok.EfficientFrontier(assets=['MCFTR.INDX'])


@mark.frontier
def test_bounds_setter_failing(init_efficient_frontier):
with pytest.raises(Exception, match=r'The number of symbols \(2\) and the length of bounds \(3\) should be equal.'):
with pytest.raises(ValueError, match=r'The number of symbols \(2\) and the length of bounds \(3\) should be equal.'):
init_efficient_frontier.bounds = ((0, 1.), (0.5, 1.), (0, 0.5))


Expand Down
2 changes: 1 addition & 1 deletion tests/test_frontier_reb.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
@mark.rebalance
@mark.frontier
def test_init_efficient_frontier_reb():
with pytest.raises(Exception, match=r'The number of symbols cannot be less than two'):
with pytest.raises(ValueError, match=r'The number of symbols cannot be less than two'):
ok.EfficientFrontierReb(assets=['MCFTR.INDX'])


Expand Down
12 changes: 6 additions & 6 deletions tests/test_portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def test_get_cagr_real(portfolio_rebalanced_month, input_data, expected):


def test_get_cagr_real_no_inflation_exception(portfolio_no_inflation):
with pytest.raises(Exception):
with pytest.raises(ValueError):
portfolio_no_inflation.get_cagr(period=1, real=True)


Expand All @@ -185,7 +185,7 @@ def test_cumulative_return(portfolio_rebalanced_month, period, real, expected):
cumulative_return_fail = [
(1.5, False, TypeError),
(-1, False, ValueError),
(1, True, Exception),
(1, True, ValueError),
]


Expand All @@ -210,7 +210,7 @@ def test_describe_no_inflation(portfolio_no_inflation):
def test_percentile_from_history(portfolio_rebalanced_month, portfolio_short_history):
assert portfolio_rebalanced_month.percentile_from_history(years=1).iloc[0, 1] == approx(0.12456, rel=1e-2)
with pytest.raises(
Exception,
ValueError,
match="Time series does not have enough history to forecast. "
"Period length is 0.90 years. At least 2 years are required.",
):
Expand All @@ -235,23 +235,23 @@ def test_get_rolling_cagr(portfolio_rebalanced_month, window, real, expected):

def test_get_rolling_cagr_failing_short_window(portfolio_not_rebalanced):
with pytest.raises(
Exception,
ValueError,
match="window size should be at least 1 year"
):
portfolio_not_rebalanced.get_rolling_cagr(window=1)


def test_get_rolling_cagr_failing_long_window(portfolio_not_rebalanced):
with pytest.raises(
Exception,
ValueError,
match="window size is more than data history depth"
):
portfolio_not_rebalanced.get_rolling_cagr(window=100)


def test_get_rolling_cagr_failing_no_inflation(portfolio_no_inflation):
with pytest.raises(
Exception,
ValueError,
match="Real return is not defined. Set inflation=True when initiating the class."
):
portfolio_no_inflation.get_rolling_cagr(real=True)
Expand Down

0 comments on commit b89cbc8

Please sign in to comment.