Skip to content

Commit

Permalink
150 mypy (#151)
Browse files Browse the repository at this point in the history
* pandas stubs installed

* pre-commit with command

* month

* portfolio

* fixing the builder
  • Loading branch information
tschm authored Jul 27, 2023
1 parent cb8c483 commit d016a54
Show file tree
Hide file tree
Showing 7 changed files with 160 additions and 51 deletions.
7 changes: 7 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,10 @@ repos:
hooks:
- id: markdownlint-fix
args: ["--ignore", "book/**/*.md"]

# type checking with mypy
- repo: 'https://github.com/pre-commit/mirrors-mypy'
rev: v1.4.1
hooks:
- id: mypy
command: ".venv/bin/mypy --explicit-package-bases -p cvx.simulator"
9 changes: 5 additions & 4 deletions cvx/simulator/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional

import pandas as pd

Expand Down Expand Up @@ -194,10 +195,10 @@ class _Builder:
_state: _State = field(default_factory=_State)
market_cap: pd.DataFrame = None
trade_volume: pd.DataFrame = None
max_cap_fraction: float = None
min_cap_fraction: float = None
max_trade_fraction: float = None
min_trade_fraction: float = None
max_cap_fraction: Optional[float] = None
min_cap_fraction: Optional[float] = None
max_trade_fraction: Optional[float] = None
min_trade_fraction: Optional[float] = None

def __post_init__(self):
"""
Expand Down
13 changes: 8 additions & 5 deletions cvx/simulator/month.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from __future__ import annotations

import calendar
from datetime import datetime
from typing import Dict

import numpy as np
import pandas as pd
Expand All @@ -17,7 +19,7 @@ def _compound(rets):
return (1.0 + rets).prod() - 1.0


def monthlytable(returns: pd.Series):
def monthlytable(returns: Dict[datetime, float]) -> pd.DataFrame:
"""
Get a table of monthly returns.
Expand All @@ -30,12 +32,13 @@ def monthlytable(returns: pd.Series):

# Works better in the first month
# Compute all the intramonth-returns, instead of reapplying some monthly resampling of the NAV
returns = returns.dropna()
r = pd.Series(returns)

r = r.dropna()
r.index = pd.DatetimeIndex(r.index)

return_monthly = (
returns.groupby([returns.index.year, returns.index.month])
.apply(_compound)
.unstack(level=1)
r.groupby([r.index.year, r.index.month]).apply(_compound).unstack(level=1)
)

# make sure all months are in the table!
Expand Down
3 changes: 2 additions & 1 deletion cvx/simulator/portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from dataclasses import dataclass
from enum import Enum
from typing import Optional

import pandas as pd
import quantstats as qs
Expand Down Expand Up @@ -82,7 +83,7 @@ class EquityPortfolio:

prices: pd.DataFrame
stocks: pd.DataFrame
trading_cost_model: TradingCostModel = None
trading_cost_model: Optional[TradingCostModel] = None
initial_cash: float = 1e6

def __post_init__(self):
Expand Down
159 changes: 123 additions & 36 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 11 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ repository = "https://github.com/cvxgrp/simulator"
packages = [{include = "cvx"}]

[tool.poetry.dependencies]
python = ">=3.8,<4.0"
python = ">=3.8,<3.12"
numpy = "*"
pandas = "*"
quantstats = "*"
pandas-stubs = "*"

[tool.poetry.group.test.dependencies]
pytest = "7.2.0"
Expand All @@ -35,6 +36,15 @@ plotly = "*"
cvxpy = "*"
loguru = "*"

[tool.poetry.group.stubs.dependencies]
mypy = "*"
pandas-stubs = "*"
#pandera = {version="*", extras = ["mypy"]}

[tool.mypy]
files = ["cvx/simulator"]
explicit_package_bases = true

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
Expand Down
8 changes: 4 additions & 4 deletions tests/test_month.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def test_table_compounded(resource_dir, returns):
"""
series = returns.fillna(0.0)
pd.testing.assert_frame_equal(
monthlytable(series),
monthlytable(series.to_dict()),
pd.read_csv(resource_dir / "monthtable.csv", index_col=0),
check_index_type=False,
)
Expand All @@ -32,7 +32,7 @@ def test_table_compounded(resource_dir, returns):
ts1.index = [int(a) for a in ts1.index]

# use cvxsimulaor
ts2 = monthlytable(series)["YTD"]
ts2 = monthlytable(series.to_dict())["YTD"]

pd.testing.assert_series_equal(ts1, ts2, check_names=False, check_index_type=False)

Expand Down Expand Up @@ -102,7 +102,7 @@ def test_missing():
columns=[calendar.month_abbr[i] for i in range(1, 13)] + ["STDev", "YTD"],
)
pd.testing.assert_frame_equal(
monthlytable(returns),
monthlytable(returns.to_dict()),
expected_output,
check_names=False,
check_index_type=False,
Expand Down Expand Up @@ -141,7 +141,7 @@ def test_not_a_complete_year():
columns=[calendar.month_abbr[i] for i in range(1, 13)] + ["STDev", "YTD"],
)
pd.testing.assert_frame_equal(
monthlytable(returns),
monthlytable(returns.to_dict()),
expected_output,
check_names=False,
check_index_type=False,
Expand Down

0 comments on commit d016a54

Please sign in to comment.