Skip to content

Commit

Permalink
fixing a few mypy ignores
Browse files Browse the repository at this point in the history
  • Loading branch information
karrmagadgeteer2 committed Oct 26, 2023
1 parent fd0d030 commit a378701
Show file tree
Hide file tree
Showing 7 changed files with 129 additions and 104 deletions.
76 changes: 46 additions & 30 deletions openseries/common_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from json import dump
from math import ceil
from pathlib import Path
from random import choices
from secrets import choice
from string import ascii_letters
from typing import Any, Optional, Union, cast

Expand Down Expand Up @@ -35,7 +35,7 @@
)


class CommonModel(BaseModel): # type: ignore[misc]
class CommonModel(BaseModel):

"""Declare CommonModel."""

Expand Down Expand Up @@ -616,7 +616,7 @@ def plot_bars(
dirpath = Path(stack()[1].filename).parent

if not filename:
filename = "".join(choices(ascii_letters, k=6)) + ".html" # noqa: S311
filename = "".join(choice(ascii_letters) for _ in range(6)) + ".html"
plotfile = dirpath.joinpath(filename)

fig, logo = load_plotly_dict()
Expand Down Expand Up @@ -717,7 +717,7 @@ def plot_series(
dirpath = Path(stack()[1].filename).parent

if not filename:
filename = "".join(choices(ascii_letters, k=6)) + ".html" # noqa: S311
filename = "".join(choice(ascii_letters) for _ in range(6)) + ".html"
plotfile = dirpath.joinpath(filename)

fig, logo = load_plotly_dict()
Expand Down Expand Up @@ -1120,10 +1120,14 @@ def downside_deviation_func(
.count(numeric_only=True)
)
if periods_in_a_year_fixed:
time_factor = periods_in_a_year_fixed
time_factor = Series(
data=[float(periods_in_a_year_fixed)] * how_many.shape[0],
index=self.tsdf.columns,
dtype="float64",
)
else:
fraction = (later - earlier).days / 365.25
time_factor = how_many / fraction # type: ignore[assignment]
time_factor = how_many.div(fraction)

dddf = (
self.tsdf.loc[cast(int, earlier) : cast(int, later)]
Expand Down Expand Up @@ -1424,12 +1428,15 @@ def positive_share_func(
.pct_change()[1:]
.count()
)
result = pos / tot
result.name = "Positive Share"
result = result.astype("float64")
share = pos / tot
if self.tsdf.shape[1] == 1:
return float(result.iloc[0])
return result # type: ignore[return-value]
return float(share.iloc[0])
return Series(
data=share,
index=self.tsdf.columns,
name="Positive Share",
dtype="float64",
)

def ret_vol_ratio_func(
self: CommonModel,
Expand Down Expand Up @@ -1469,26 +1476,29 @@ def ret_vol_ratio_func(
Ratio of the annualized arithmetic mean of returns and annualized
volatility or, if risk-free return provided, Sharpe ratio
"""
ratio = (
ratio = Series(
self.arithmetic_ret_func(
months_from_last=months_from_last,
from_date=from_date,
to_date=to_date,
periods_in_a_year_fixed=periods_in_a_year_fixed,
)
- riskfree_rate
- riskfree_rate,
) / self.vol_func(
months_from_last=months_from_last,
from_date=from_date,
to_date=to_date,
periods_in_a_year_fixed=periods_in_a_year_fixed,
)
result = Series(ratio)
result = result.astype("float64")
result.name = "Return vol ratio"

if self.tsdf.shape[1] == 1:
return float(result.iloc[0])
return result # type: ignore[return-value]
return float(ratio.iloc[0])
return Series(
data=ratio,
index=self.tsdf.columns,
name="Return vol ratio",
dtype="float64",
)

def sortino_ratio_func(
self: CommonModel,
Expand Down Expand Up @@ -1531,27 +1541,30 @@ def sortino_ratio_func(
Sortino ratio calculated as ( return - riskfree return ) /
downside deviation (std dev of returns below MAR)
"""
ratio = (
ratio = Series(
self.arithmetic_ret_func(
months_from_last=months_from_last,
from_date=from_date,
to_date=to_date,
periods_in_a_year_fixed=periods_in_a_year_fixed,
)
- riskfree_rate
- riskfree_rate,
) / self.downside_deviation_func(
min_accepted_return=min_accepted_return,
months_from_last=months_from_last,
from_date=from_date,
to_date=to_date,
periods_in_a_year_fixed=periods_in_a_year_fixed,
)
result = Series(ratio)
result = result.astype("float64")
result.name = "Sortino ratio"

if self.tsdf.shape[1] == 1:
return float(result.iloc[0])
return result # type: ignore[return-value]
return float(ratio.iloc[0])
return Series(
data=ratio,
index=self.tsdf.columns,
name="Sortino ratio",
dtype="float64",
)

def value_ret_func(
self: CommonModel,
Expand Down Expand Up @@ -1632,12 +1645,15 @@ def value_ret_calendar_period(
vrdf.index = DatetimeIndex(vrdf.index)
resultdf = DataFrame(vrdf.ffill().pct_change())
result = resultdf.loc[period] + 1
result = result.cumprod(axis="index").iloc[-1] - 1
result.name = period
result = result.astype("float64")
cal_period = result.cumprod(axis="index").iloc[-1] - 1
if self.tsdf.shape[1] == 1:
return float(result.iloc[0])
return result # type: ignore[return-value]
return float(cal_period.iloc[0])
return Series(
data=cal_period,
index=self.tsdf.columns,
name=period,
dtype="float64",
)

def var_down_func(
self: CommonModel,
Expand Down
14 changes: 10 additions & 4 deletions openseries/datefixer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,15 @@
list_supported_countries,
)
from numpy import array, busdaycalendar, datetime64, is_busday, where
from pandas import DataFrame, DatetimeIndex, Series, Timestamp, concat, date_range
from pandas import (
DataFrame,
DatetimeIndex,
Index,
Series,
Timestamp,
concat,
date_range,
)
from pandas.tseries.offsets import CustomBusinessDay
from pydantic import PositiveInt

Expand Down Expand Up @@ -435,9 +443,7 @@ def do_resample_to_business_period_ends(
data.index = DatetimeIndex(data.index)
data = data.resample(rule=freq, convention=convention).last()
data = data.drop(index=data.index[-1])
data.index = [ # type: ignore[assignment,unused-ignore]
d.date() for d in DatetimeIndex(data.index)
]
data.index = Index(d.date() for d in DatetimeIndex(data.index))

if newhead.index[0] not in data.index:
data = concat([data, newhead])
Expand Down
2 changes: 1 addition & 1 deletion openseries/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
)


class OpenFrame(CommonModel): # type: ignore[misc]
class OpenFrame(CommonModel):

"""
OpenFrame objects hold OpenTimeSeries in the list constituents.
Expand Down
43 changes: 23 additions & 20 deletions openseries/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from pandas import (
DataFrame,
DatetimeIndex,
Index,
MultiIndex,
Series,
date_range,
Expand Down Expand Up @@ -56,7 +57,7 @@
TypeOpenTimeSeries = TypeVar("TypeOpenTimeSeries", bound="OpenTimeSeries")


class OpenTimeSeries(CommonModel): # type: ignore[misc]
class OpenTimeSeries(CommonModel):

"""
OpenTimeSeries objects are at the core of the openseries package.
Expand Down Expand Up @@ -535,10 +536,12 @@ def value_to_diff(
self.tsdf = self.tsdf.diff(periods=periods)
self.tsdf.iloc[0] = 0
self.valuetype = ValueType.RTRN
self.tsdf.columns = [ # type: ignore[assignment]
[self.label],
[self.valuetype],
]
self.tsdf.columns = MultiIndex.from_arrays(
[
[self.label],
[self.valuetype],
],
)
return self

def to_cumret(self: OpenTimeSeries) -> OpenTimeSeries:
Expand All @@ -559,10 +562,12 @@ def to_cumret(self: OpenTimeSeries) -> OpenTimeSeries:
self.tsdf = self.tsdf.add(1.0)
self.tsdf = self.tsdf.cumprod(axis=0) / self.tsdf.iloc[0]
self.valuetype = ValueType.PRICE
self.tsdf.columns = [ # type: ignore[assignment]
[self.label],
[self.valuetype],
]
self.tsdf.columns = MultiIndex.from_arrays(
[
[self.label],
[self.valuetype],
],
)
return self

def from_1d_rate_to_cumret(
Expand Down Expand Up @@ -622,9 +627,7 @@ def resample(
"""
self.tsdf.index = DatetimeIndex(self.tsdf.index)
self.tsdf = self.tsdf.resample(freq).last()
self.tsdf.index = [ # type: ignore[assignment]
d.date() for d in DatetimeIndex(self.tsdf.index)
]
self.tsdf.index = Index(d.date() for d in DatetimeIndex(self.tsdf.index))
return self

def resample_to_business_period_ends(
Expand Down Expand Up @@ -806,13 +809,13 @@ def running_adjustment(
prev = idx
self.tsdf = DataFrame(data=values, index=dates)
self.valuetype = ValueType.PRICE
self.tsdf.columns = [ # type: ignore[assignment]
[self.label],
[self.valuetype],
]
self.tsdf.index = [ # type: ignore[assignment]
d.date() for d in DatetimeIndex(self.tsdf.index)
]
self.tsdf.columns = MultiIndex.from_arrays(
[
[self.label],
[self.valuetype],
],
)
self.tsdf.index = Index(d.date() for d in DatetimeIndex(self.tsdf.index))
if returns_input:
self.value_to_ret()
return self
Expand Down Expand Up @@ -904,7 +907,7 @@ def timeseries_chain(
values = values.mul(
new.tsdf.iloc[:, 0].loc[first] / old.tsdf.iloc[:, 0].loc[first],
)
values = append(values, new.tsdf.iloc[:, 0]) # type: ignore[assignment]
values = Series(append(values, new.tsdf.iloc[:, 0]))

dates.extend([x.strftime("%Y-%m-%d") for x in new.tsdf.index])

Expand Down
Loading

0 comments on commit a378701

Please sign in to comment.