jquantstats 0.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jquantstats/__init__.py +0 -0
- jquantstats/_plots.py +308 -0
- jquantstats/_stats.py +450 -0
- jquantstats/api.py +222 -0
- jquantstats-0.0.2.dist-info/METADATA +150 -0
- jquantstats-0.0.2.dist-info/RECORD +8 -0
- jquantstats-0.0.2.dist-info/WHEEL +4 -0
- jquantstats-0.0.2.dist-info/licenses/LICENSE.txt +175 -0
jquantstats/__init__.py
ADDED
File without changes
|
jquantstats/_plots.py
ADDED
@@ -0,0 +1,308 @@
|
|
1
|
+
import calendar
|
2
|
+
import dataclasses
|
3
|
+
|
4
|
+
import numpy as np
|
5
|
+
import plotly.graph_objects as go
|
6
|
+
import polars as pl
|
7
|
+
from plotly.subplots import make_subplots
|
8
|
+
|
9
|
+
|
10
|
+
@dataclasses.dataclass(frozen=True)
|
11
|
+
class Plots:
|
12
|
+
data: "_Data" # type: ignore
|
13
|
+
|
14
|
+
_FLATUI_COLORS = [
|
15
|
+
"#FEDD78", # Yellow
|
16
|
+
"#348DC1", # Blue
|
17
|
+
"#BA516B", # Rose
|
18
|
+
"#4FA487", # Green
|
19
|
+
"#9B59B6", # Purple
|
20
|
+
"#613F66", # Dark Purple
|
21
|
+
"#84B082", # Light Green
|
22
|
+
"#DC136C", # Pink
|
23
|
+
"#559CAD", # Light Blue
|
24
|
+
"#4A5899", # Navy Blue
|
25
|
+
]
|
26
|
+
|
27
|
+
@staticmethod
|
28
|
+
def _get_colors():
|
29
|
+
"""
|
30
|
+
Returns the default color palette and styling parameters for plots.
|
31
|
+
|
32
|
+
Returns:
|
33
|
+
tuple: A tuple containing:
|
34
|
+
- colors (list): List of hex color codes
|
35
|
+
- ls (str): Line style ("-" for solid)
|
36
|
+
- alpha (float): Opacity value (0.8)
|
37
|
+
"""
|
38
|
+
colors = Plots._FLATUI_COLORS
|
39
|
+
ls = "-" # Line style
|
40
|
+
alpha = 0.8 # Opacity
|
41
|
+
return colors, ls, alpha
|
42
|
+
|
43
|
+
@staticmethod
|
44
|
+
def _compsum(returns):
|
45
|
+
"""Calculates rolling compounded returns"""
|
46
|
+
return returns.add(1).cumprod(axis=0) - 1
|
47
|
+
|
48
|
+
def plot_returns_bars(self):
|
49
|
+
"""
|
50
|
+
Creates a bar chart of returns for each asset in the data.
|
51
|
+
|
52
|
+
This function visualizes the returns of each asset as bars, making it easy
|
53
|
+
to compare performance across different time periods.
|
54
|
+
|
55
|
+
Args:
|
56
|
+
data (_Data): A Data object containing returns data to plot.
|
57
|
+
|
58
|
+
Returns:
|
59
|
+
plotly.graph_objects.Figure: A Plotly figure object containing the bar chart.
|
60
|
+
The figure shows returns for each asset with a horizontal line at y=0.
|
61
|
+
|
62
|
+
Example:
|
63
|
+
>>> from jquantstats.api import _Data
|
64
|
+
>>> import pandas as pd
|
65
|
+
>>> returns = pd.DataFrame(...)
|
66
|
+
>>> data = _Data(returns=returns)
|
67
|
+
>>> fig = data.plots.plot_returns_bars()
|
68
|
+
>>> fig.show()
|
69
|
+
"""
|
70
|
+
# Get color palette
|
71
|
+
colors, _, _ = Plots._get_colors()
|
72
|
+
|
73
|
+
# Create figure
|
74
|
+
fig = go.Figure()
|
75
|
+
|
76
|
+
# Add a bar trace for each asset
|
77
|
+
for idx, col in enumerate(self.data.returns.columns):
|
78
|
+
fig.add_trace(
|
79
|
+
go.Bar(
|
80
|
+
x=self.data.index,
|
81
|
+
y=self.data.returns[col],
|
82
|
+
name=col,
|
83
|
+
marker_color=colors[idx % len(colors)], # Cycle through colors if more assets than colors
|
84
|
+
)
|
85
|
+
)
|
86
|
+
|
87
|
+
# Update layout for better readability
|
88
|
+
fig.update_layout(
|
89
|
+
plot_bgcolor="white",
|
90
|
+
paper_bgcolor="white",
|
91
|
+
xaxis=dict(
|
92
|
+
tickformat="%Y", # Format x-axis as years
|
93
|
+
showgrid=False,
|
94
|
+
),
|
95
|
+
yaxis=dict(
|
96
|
+
tickformat=".0%", # Format y-axis as percentages
|
97
|
+
showgrid=True,
|
98
|
+
gridcolor="lightgray",
|
99
|
+
),
|
100
|
+
)
|
101
|
+
|
102
|
+
# Add horizontal line at y=0 to distinguish positive and negative returns
|
103
|
+
fig.add_hline(y=0, line=dict(color="black", width=1, dash="dash"))
|
104
|
+
|
105
|
+
return fig
|
106
|
+
|
107
|
+
def plot_snapshot(self, title="Portfolio Summary", compounded=True, log_scale=False):
|
108
|
+
"""
|
109
|
+
Creates a comprehensive dashboard with multiple plots for portfolio analysis.
|
110
|
+
|
111
|
+
This function generates a three-panel plot showing:
|
112
|
+
1. Cumulative returns over time
|
113
|
+
2. Drawdowns over time
|
114
|
+
3. Daily returns over time
|
115
|
+
|
116
|
+
This provides a complete visual summary of portfolio performance.
|
117
|
+
|
118
|
+
Args:
|
119
|
+
data (_Data): A Data object containing returns data.
|
120
|
+
title (str, optional): Title of the plot. Defaults to "Portfolio Summary".
|
121
|
+
compounded (bool, optional): Whether to use compounded returns. Defaults to True.
|
122
|
+
log_scale (bool, optional): Whether to use logarithmic scale for cumulative returns.
|
123
|
+
Defaults to False.
|
124
|
+
|
125
|
+
Returns:
|
126
|
+
plotly.graph_objects.Figure: A Plotly figure object containing the dashboard.
|
127
|
+
|
128
|
+
Example:
|
129
|
+
>>> from jquantstats.api import _Data
|
130
|
+
>>> import pandas as pd
|
131
|
+
>>> returns = pd.DataFrame(...)
|
132
|
+
>>> data = _Data(returns=returns)
|
133
|
+
>>> fig = snapshot_plotly(data, title="My Portfolio Performance")
|
134
|
+
>>> fig.show()
|
135
|
+
"""
|
136
|
+
# Calculate drawdowns
|
137
|
+
dd = self.data.stats.drawdown(compounded=compounded, initial=100)
|
138
|
+
|
139
|
+
# Create subplot structure
|
140
|
+
fig = make_subplots(
|
141
|
+
rows=3,
|
142
|
+
cols=1,
|
143
|
+
shared_xaxes=True, # Share x-axis across all subplots
|
144
|
+
row_heights=[0.5, 0.25, 0.25], # Allocate more space to cumulative returns
|
145
|
+
vertical_spacing=0.03,
|
146
|
+
subplot_titles=["Cumulative Return", "Drawdown", "Daily Return"],
|
147
|
+
)
|
148
|
+
|
149
|
+
# Plot cumulative returns for each asset
|
150
|
+
for col in self.data.returns.columns:
|
151
|
+
cum_returns = 100 * ((1 + self.data.returns[col]).cum_prod()) # Convert to percentage
|
152
|
+
fig.add_trace(
|
153
|
+
go.Scatter(
|
154
|
+
x=self.data.index[self.data.index.columns[0]],
|
155
|
+
y=cum_returns,
|
156
|
+
name=col,
|
157
|
+
mode="lines",
|
158
|
+
),
|
159
|
+
row=1,
|
160
|
+
col=1,
|
161
|
+
)
|
162
|
+
|
163
|
+
# Plot drawdowns for each asset
|
164
|
+
for col in self.data.returns.columns:
|
165
|
+
fig.add_trace(
|
166
|
+
go.Scatter(
|
167
|
+
x=self.data.index[self.data.index.columns[0]],
|
168
|
+
y=dd[col],
|
169
|
+
name=f"DD: {col}",
|
170
|
+
mode="lines",
|
171
|
+
),
|
172
|
+
row=2,
|
173
|
+
col=1,
|
174
|
+
)
|
175
|
+
|
176
|
+
# Plot daily returns for each asset
|
177
|
+
for col in self.data.assets:
|
178
|
+
fig.add_trace(
|
179
|
+
go.Scatter(
|
180
|
+
x=self.data.index[self.data.index.columns[0]],
|
181
|
+
y=self.data.all[col] * 100, # Convert to percentage
|
182
|
+
name=f"{col} Return",
|
183
|
+
mode="lines",
|
184
|
+
),
|
185
|
+
row=3,
|
186
|
+
col=1,
|
187
|
+
)
|
188
|
+
|
189
|
+
# Configure layout
|
190
|
+
fig.update_layout(
|
191
|
+
height=800, # Taller figure for better visibility
|
192
|
+
title_text=title,
|
193
|
+
showlegend=True,
|
194
|
+
template="plotly_white", # Clean white template
|
195
|
+
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
|
196
|
+
)
|
197
|
+
|
198
|
+
# Apply log scale to cumulative returns if requested
|
199
|
+
if log_scale:
|
200
|
+
fig.update_yaxes(type="log", row=1, col=1)
|
201
|
+
|
202
|
+
# Format y-axes
|
203
|
+
fig.update_yaxes(title="Cumulative Return (%)", row=1, col=1)
|
204
|
+
fig.update_yaxes(title="Drawdown", tickformat=".1%", row=2, col=1)
|
205
|
+
fig.update_yaxes(title="Daily Return (%)", row=3, col=1)
|
206
|
+
|
207
|
+
return fig
|
208
|
+
|
209
|
+
def monthly_heatmap(
|
210
|
+
self,
|
211
|
+
col,
|
212
|
+
annot_size=13,
|
213
|
+
cbar=True,
|
214
|
+
returns_label="Strategy",
|
215
|
+
compounded=False,
|
216
|
+
fontname="Arial",
|
217
|
+
ylabel=True,
|
218
|
+
):
|
219
|
+
"""
|
220
|
+
Creates a heatmap of monthly returns by year using Polars only.
|
221
|
+
"""
|
222
|
+
|
223
|
+
cmap = "RdYlGn"
|
224
|
+
date_col = self.data.index.columns[0]
|
225
|
+
|
226
|
+
# Resample monthly
|
227
|
+
data = self.data.resample(every="1mo", compounded=compounded)
|
228
|
+
|
229
|
+
# Prepare DataFrame with Year, Month, Return (%)
|
230
|
+
result = data.all.with_columns(
|
231
|
+
pl.col(date_col).dt.year().alias("Year"),
|
232
|
+
pl.col(date_col).dt.month().alias("Month"),
|
233
|
+
(pl.col(col) * 100).alias("Return"),
|
234
|
+
)
|
235
|
+
|
236
|
+
# Pivot table (Year x Month)
|
237
|
+
pivot = result.pivot(
|
238
|
+
values="Return",
|
239
|
+
index="Year",
|
240
|
+
columns="Month",
|
241
|
+
aggregate_function="first", # Should be fine with monthly data
|
242
|
+
).sort("Year", descending=True)
|
243
|
+
|
244
|
+
# Sort columns by calendar month
|
245
|
+
month_cols = [str(m) for m in range(1, 13)]
|
246
|
+
pivot = pivot.select("Year", *month_cols)
|
247
|
+
|
248
|
+
# Rename columns to month abbreviations
|
249
|
+
new_col_names = ["Year"] + [calendar.month_abbr[int(m)] for m in month_cols]
|
250
|
+
pivot.columns = new_col_names
|
251
|
+
|
252
|
+
# Extract z-matrix for heatmap
|
253
|
+
z = np.round(pivot.drop("Year").to_numpy(), 2)
|
254
|
+
y = pivot["Year"].to_numpy().astype(str)
|
255
|
+
x = new_col_names[1:]
|
256
|
+
|
257
|
+
zmin = -np.nanmax(np.abs(z))
|
258
|
+
zmax = np.nanmax(np.abs(z))
|
259
|
+
|
260
|
+
fig = go.Figure(
|
261
|
+
data=go.Heatmap(
|
262
|
+
z=z,
|
263
|
+
x=x,
|
264
|
+
y=y,
|
265
|
+
text=z,
|
266
|
+
texttemplate="%{text:.2f}%",
|
267
|
+
colorscale=cmap,
|
268
|
+
zmid=0,
|
269
|
+
zmin=zmin,
|
270
|
+
zmax=zmax,
|
271
|
+
colorbar=dict(
|
272
|
+
title="Return (%)",
|
273
|
+
ticksuffix="%",
|
274
|
+
tickfont=dict(size=annot_size),
|
275
|
+
)
|
276
|
+
if cbar
|
277
|
+
else None,
|
278
|
+
hovertemplate="Year: %{y}<br>Month: %{x}<br>Return: %{z:.2f}%",
|
279
|
+
)
|
280
|
+
)
|
281
|
+
|
282
|
+
fig.update_layout(
|
283
|
+
title={
|
284
|
+
"text": f"{returns_label} - Monthly Returns (%)",
|
285
|
+
"y": 0.95,
|
286
|
+
"x": 0.5,
|
287
|
+
"xanchor": "center",
|
288
|
+
"yanchor": "top",
|
289
|
+
"font": dict(family=fontname, size=16, color="black"),
|
290
|
+
},
|
291
|
+
xaxis=dict(
|
292
|
+
title="",
|
293
|
+
side="top",
|
294
|
+
showgrid=False,
|
295
|
+
tickfont=dict(family=fontname, size=annot_size),
|
296
|
+
),
|
297
|
+
yaxis=dict(
|
298
|
+
title="Years" if ylabel else "",
|
299
|
+
autorange="reversed",
|
300
|
+
showgrid=False,
|
301
|
+
tickfont=dict(family=fontname, size=annot_size),
|
302
|
+
),
|
303
|
+
plot_bgcolor="white",
|
304
|
+
paper_bgcolor="white",
|
305
|
+
margin=dict(l=0, r=0, t=80, b=0),
|
306
|
+
)
|
307
|
+
|
308
|
+
return fig
|
jquantstats/_stats.py
ADDED
@@ -0,0 +1,450 @@
|
|
1
|
+
import dataclasses
|
2
|
+
from collections.abc import Callable
|
3
|
+
from functools import wraps
|
4
|
+
|
5
|
+
import numpy as np
|
6
|
+
import polars as pl
|
7
|
+
|
8
|
+
|
9
|
+
@dataclasses.dataclass(frozen=True)
|
10
|
+
class Stats:
|
11
|
+
data: "_Data" # type: ignore
|
12
|
+
all: pl.DataFrame = None # Default is None; will be set in __post_init__
|
13
|
+
|
14
|
+
def __post_init__(self):
|
15
|
+
object.__setattr__(self, "all", self.data.all)
|
16
|
+
|
17
|
+
@staticmethod
|
18
|
+
def _quantile_expr(series, q):
|
19
|
+
return series.quantile(q)
|
20
|
+
|
21
|
+
@staticmethod
|
22
|
+
def _mean_positive_expr(series):
|
23
|
+
return series.filter(series >= 0).mean()
|
24
|
+
|
25
|
+
@staticmethod
|
26
|
+
def _mean_negative_expr(series):
|
27
|
+
return series.filter(series < 0).mean()
|
28
|
+
|
29
|
+
@staticmethod
|
30
|
+
def _quantile_expr(series, cutoff):
|
31
|
+
return series.quantile(cutoff)
|
32
|
+
|
33
|
+
@staticmethod
|
34
|
+
def columnwise_stat(func):
|
35
|
+
"""
|
36
|
+
Decorator that applies a column-wise statistical function to all numeric columns
|
37
|
+
of `self.data` and returns a dictionary with keys named appropriately.
|
38
|
+
"""
|
39
|
+
|
40
|
+
@wraps(func)
|
41
|
+
def wrapper(self, *args, **kwargs):
|
42
|
+
return {col: func(self, self.all[col], *args, **kwargs) for col in self.data.assets}
|
43
|
+
|
44
|
+
return wrapper
|
45
|
+
|
46
|
+
@staticmethod
|
47
|
+
def to_frame(func: Callable) -> Callable:
|
48
|
+
"""Decorator: Applies per-column expressions and evaluates with .with_columns(...)"""
|
49
|
+
|
50
|
+
@wraps(func)
|
51
|
+
def wrapper(self, *args, **kwargs):
|
52
|
+
return self.all.select(
|
53
|
+
[pl.col(name) for name in self.data.date_col]
|
54
|
+
+ [func(self, pl.col(name), *args, **kwargs).alias(name) for name in self.data.assets]
|
55
|
+
)
|
56
|
+
|
57
|
+
return wrapper
|
58
|
+
|
59
|
+
@columnwise_stat
|
60
|
+
def skew(self, series):
|
61
|
+
"""
|
62
|
+
Calculates skewness (asymmetry) for each numeric column.
|
63
|
+
"""
|
64
|
+
return series.skew(bias=False)
|
65
|
+
|
66
|
+
@columnwise_stat
|
67
|
+
def kurtosis(self, series):
|
68
|
+
"""
|
69
|
+
Calculates returns' kurtosis
|
70
|
+
(the degree to which a distribution peak compared to a normal distribution)
|
71
|
+
"""
|
72
|
+
return series.kurtosis(bias=False)
|
73
|
+
|
74
|
+
@columnwise_stat
|
75
|
+
def avg_return(self, series):
|
76
|
+
"""Average return per non-zero, non-null value."""
|
77
|
+
return series.filter(series.is_not_null() & (series != 0)).mean()
|
78
|
+
|
79
|
+
@columnwise_stat
|
80
|
+
def avg_win(self, series):
|
81
|
+
"""
|
82
|
+
Calculates the average winning
|
83
|
+
return/trade for an asset
|
84
|
+
"""
|
85
|
+
return self._mean_positive_expr(series)
|
86
|
+
|
87
|
+
@columnwise_stat
|
88
|
+
def avg_loss(self, series):
|
89
|
+
"""
|
90
|
+
Calculates the average low if
|
91
|
+
return/trade return for a period
|
92
|
+
"""
|
93
|
+
return self._mean_negative_expr(series)
|
94
|
+
|
95
|
+
@columnwise_stat
|
96
|
+
def volatility(self, series, periods=252, annualize=True):
|
97
|
+
"""
|
98
|
+
Calculates the volatility of returns:
|
99
|
+
- Std dev of returns
|
100
|
+
- Annualized by sqrt(periods) if `annualize` is True
|
101
|
+
"""
|
102
|
+
factor = np.sqrt(periods) if annualize else 1
|
103
|
+
return series.std() * factor
|
104
|
+
|
105
|
+
@to_frame
|
106
|
+
def rolling_volatility(self, series: pl.Expr, rolling_period=126, periods_per_year=252) -> pl.Expr:
|
107
|
+
return series.rolling_std(window_size=rolling_period) * np.sqrt(periods_per_year)
|
108
|
+
|
109
|
+
@to_frame
|
110
|
+
def price(self, series: pl.Expr, compounded=False, initial=1.0) -> pl.Expr:
|
111
|
+
if compounded:
|
112
|
+
# First compute cumulative compounded returns
|
113
|
+
cum = initial * (1 + series).cum_prod()
|
114
|
+
else:
|
115
|
+
# Simple cumulative sum of returns
|
116
|
+
cum = initial + series.cum_sum()
|
117
|
+
|
118
|
+
return cum
|
119
|
+
|
120
|
+
@to_frame
|
121
|
+
def drawdown(self, series: pl.Expr, compounded=False, initial=1.0) -> pl.Expr:
|
122
|
+
"""
|
123
|
+
Computes drawdown from the high-water mark.
|
124
|
+
|
125
|
+
Args:
|
126
|
+
series (pl.Expr): Polars expression for the return series.
|
127
|
+
compounded (bool): Whether to use compounded returns.
|
128
|
+
initial (float): Initial portfolio value (default is 1).
|
129
|
+
|
130
|
+
Returns:
|
131
|
+
pl.Expr: A Polars expression representing the drawdown.
|
132
|
+
"""
|
133
|
+
if compounded:
|
134
|
+
# First compute cumulative compounded returns
|
135
|
+
equity = initial * (1 + series).cum_prod()
|
136
|
+
else:
|
137
|
+
# Simple cumulative sum of returns
|
138
|
+
equity = initial + series.cum_sum()
|
139
|
+
|
140
|
+
# equity = self.price(series, compounded, initial=initial)
|
141
|
+
return -100 * ((equity / equity.cum_max()) - 1)
|
142
|
+
|
143
|
+
@columnwise_stat
|
144
|
+
def autocorr(self, series: pl.Series):
|
145
|
+
"""
|
146
|
+
Metric to account for autocorrelation.
|
147
|
+
Applies autocorrelation penalty to each numeric series (column).
|
148
|
+
"""
|
149
|
+
corr = pl.corr(series, series.shift(1)).cast(pl.Float64)
|
150
|
+
return corr
|
151
|
+
|
152
|
+
@columnwise_stat
|
153
|
+
def payoff_ratio(self, series):
|
154
|
+
"""
|
155
|
+
Measures the payoff ratio: average win / abs(average loss).
|
156
|
+
"""
|
157
|
+
avg_win = series.filter(series > 0).mean()
|
158
|
+
# avg_win = self.avg_win(series)
|
159
|
+
avg_loss = np.abs(series.filter(series < 0).mean())
|
160
|
+
return avg_win / avg_loss
|
161
|
+
|
162
|
+
def win_loss_ratio(self):
|
163
|
+
"""Shorthand for payoff_ratio()"""
|
164
|
+
return self.payoff_ratio()
|
165
|
+
|
166
|
+
@columnwise_stat
|
167
|
+
def profit_ratio(self, series):
|
168
|
+
"""Measures the profit ratio (win ratio / loss ratio)"""
|
169
|
+
wins = series.filter(series > 0)
|
170
|
+
losses = series.filter(series < 0)
|
171
|
+
|
172
|
+
try:
|
173
|
+
win_ratio = np.abs(wins.mean() / wins.count())
|
174
|
+
loss_ratio = np.abs(losses.mean() / losses.count())
|
175
|
+
|
176
|
+
return win_ratio / loss_ratio
|
177
|
+
|
178
|
+
except TypeError:
|
179
|
+
return np.nan
|
180
|
+
|
181
|
+
@columnwise_stat
|
182
|
+
def profit_factor(self, series):
|
183
|
+
"""Measures the profit ratio (wins / loss)"""
|
184
|
+
wins = series.filter(series > 0)
|
185
|
+
losses = series.filter(series < 0)
|
186
|
+
|
187
|
+
return np.abs(wins.sum() / losses.sum())
|
188
|
+
|
189
|
+
def common_sense_ratio(self):
|
190
|
+
"""Measures the common sense ratio (profit factor * tail ratio)"""
|
191
|
+
profit_factor = self.profit_factor()
|
192
|
+
tail_ratio = self.tail_ratio()
|
193
|
+
|
194
|
+
return {name: profit_factor[name] * tail_ratio[name] for name in profit_factor.keys()}
|
195
|
+
|
196
|
+
@columnwise_stat
|
197
|
+
def value_at_risk(self, series: pl.Series, alpha: float = 0.05):
|
198
|
+
"""
|
199
|
+
Calculates the daily value-at-risk
|
200
|
+
(variance-covariance calculation with confidence level)
|
201
|
+
"""
|
202
|
+
# Ensure returns are sorted and drop nulls
|
203
|
+
cleaned_returns = series.drop_nulls()
|
204
|
+
|
205
|
+
# Compute VaR using quantile; note that VaR is typically a negative number (i.e. loss)
|
206
|
+
return cleaned_returns.quantile(alpha, interpolation="nearest")
|
207
|
+
|
208
|
+
def var(self, alpha: float = 0.05):
|
209
|
+
"""Shorthand for value_at_risk()"""
|
210
|
+
return self.value_at_risk(alpha)
|
211
|
+
|
212
|
+
@columnwise_stat
|
213
|
+
def conditional_value_at_risk(self, series, alpha=0.05):
|
214
|
+
"""
|
215
|
+
Calculates the conditional value-at-risk (CVaR / expected shortfall)
|
216
|
+
for each numeric column.
|
217
|
+
"""
|
218
|
+
# Ensure returns are sorted and drop nulls
|
219
|
+
cleaned_returns = series.drop_nulls()
|
220
|
+
|
221
|
+
# Compute VaR using quantile; note that VaR is typically a negative number (i.e. loss)
|
222
|
+
var = cleaned_returns.quantile(alpha, interpolation="nearest")
|
223
|
+
|
224
|
+
# Compute mean of returns less than or equal to VaR
|
225
|
+
cvar = cleaned_returns.filter(cleaned_returns <= var).mean()
|
226
|
+
|
227
|
+
return cvar
|
228
|
+
|
229
|
+
# Compute CVaR: mean of values less than the VaR threshold
|
230
|
+
# return pl.when(series < var_expr).then(series).otherwise(None).mean()
|
231
|
+
|
232
|
+
def cvar(self, alpha=0.05):
|
233
|
+
"""Shorthand for conditional_value_at_risk()"""
|
234
|
+
return self.conditional_value_at_risk(alpha)
|
235
|
+
|
236
|
+
def expected_shortfall(self, alpha=0.05):
|
237
|
+
"""Shorthand for conditional_value_at_risk()"""
|
238
|
+
return self.conditional_value_at_risk(alpha)
|
239
|
+
|
240
|
+
@columnwise_stat
|
241
|
+
def tail_ratio(self, series, cutoff=0.95):
|
242
|
+
"""Calculates the ratio of the right (95%) and left (5%) tails."""
|
243
|
+
left_tail = self._quantile_expr(series, 1 - cutoff)
|
244
|
+
right_tail = self._quantile_expr(series, cutoff)
|
245
|
+
return abs(right_tail / left_tail) # .alias(series.meta.output_name)
|
246
|
+
|
247
|
+
@columnwise_stat
|
248
|
+
def win_rate(self, series):
|
249
|
+
"""Calculates the win ratio for a period."""
|
250
|
+
num_pos = series.filter(series > 0).count()
|
251
|
+
num_nonzero = series.filter(series != 0).count()
|
252
|
+
return num_pos / num_nonzero
|
253
|
+
|
254
|
+
@columnwise_stat
|
255
|
+
def gain_to_pain_ratio(self, series):
|
256
|
+
"""
|
257
|
+
Jack Schwager's Gain-to-Pain Ratio:
|
258
|
+
total return / sum of losses (in absolute value).
|
259
|
+
"""
|
260
|
+
total_gain = series.sum()
|
261
|
+
total_pain = series.filter(series < 0).abs().sum()
|
262
|
+
try:
|
263
|
+
return total_gain / total_pain
|
264
|
+
except ZeroDivisionError:
|
265
|
+
return np.nan
|
266
|
+
|
267
|
+
@columnwise_stat
|
268
|
+
def outlier_win_ratio(self, series: pl.Series, quantile: float = 0.99):
|
269
|
+
"""
|
270
|
+
Calculates the outlier winners ratio:
|
271
|
+
99th percentile of returns / mean positive return
|
272
|
+
"""
|
273
|
+
q = series.quantile(quantile, interpolation="nearest")
|
274
|
+
mean_positive = series.filter(series > 0).mean()
|
275
|
+
return q / mean_positive
|
276
|
+
|
277
|
+
@columnwise_stat
|
278
|
+
def outlier_loss_ratio(self, series: pl.Series, quantile: float = 0.01):
|
279
|
+
"""
|
280
|
+
Calculates the outlier losers ratio
|
281
|
+
1st percentile of returns / mean negative return
|
282
|
+
"""
|
283
|
+
q = series.quantile(quantile, interpolation="nearest")
|
284
|
+
mean_negative = series.filter(series < 0).mean()
|
285
|
+
return q / mean_negative
|
286
|
+
|
287
|
+
@columnwise_stat
|
288
|
+
def risk_return_ratio(self, series):
|
289
|
+
"""
|
290
|
+
Calculates the return/risk ratio (Sharpe ratio w/o risk-free rate).
|
291
|
+
"""
|
292
|
+
return series.mean() / series.std()
|
293
|
+
|
294
|
+
def kelly_criterion(self):
|
295
|
+
"""
|
296
|
+
Calculates the optimal capital allocation (Kelly Criterion) per column:
|
297
|
+
f* = [(b * p) - q] / b
|
298
|
+
where:
|
299
|
+
- b = payoff ratio
|
300
|
+
- p = win rate
|
301
|
+
- q = 1 - p
|
302
|
+
"""
|
303
|
+
b = self.payoff_ratio()
|
304
|
+
p = self.win_rate()
|
305
|
+
|
306
|
+
return {
|
307
|
+
col: ((b[col] * p[col]) - (1 - p[col])) / b[col]
|
308
|
+
# if b[col] not in (None, 0) and p[col] is not None else None
|
309
|
+
for col in b
|
310
|
+
}
|
311
|
+
|
312
|
+
@columnwise_stat
|
313
|
+
def best(self, series):
|
314
|
+
"""Returns the maximum return per column (best period)."""
|
315
|
+
return series.max() # .alias(series.meta.output_name)
|
316
|
+
|
317
|
+
@columnwise_stat
|
318
|
+
def worst(self, series):
|
319
|
+
"""Returns the minimum return per column (worst period)."""
|
320
|
+
return series.min() # .alias(series.meta.output_name)
|
321
|
+
|
322
|
+
@columnwise_stat
|
323
|
+
def exposure(self, series):
|
324
|
+
"""Returns the market exposure time (returns != 0)"""
|
325
|
+
return np.round((series.filter(series != 0).count() / self.all.height), decimals=2)
|
326
|
+
|
327
|
+
@columnwise_stat
|
328
|
+
def sharpe(self, series, periods=252):
|
329
|
+
"""
|
330
|
+
Calculates the Sharpe ratio of asset returns.
|
331
|
+
"""
|
332
|
+
divisor = series.std(ddof=1)
|
333
|
+
|
334
|
+
res = series.mean() / divisor
|
335
|
+
factor = periods or 1
|
336
|
+
return res * np.sqrt(factor)
|
337
|
+
|
338
|
+
@to_frame
|
339
|
+
def rolling_sharpe(self, series: pl.Expr, rolling_period=126, periods_per_year=252) -> pl.Expr:
|
340
|
+
res = series.rolling_mean(window_size=rolling_period) / series.rolling_std(window_size=rolling_period)
|
341
|
+
factor = periods_per_year or 1
|
342
|
+
return res * np.sqrt(factor)
|
343
|
+
|
344
|
+
@columnwise_stat
|
345
|
+
def sortino(self, series: pl.Series, periods=252):
|
346
|
+
"""
|
347
|
+
Calculates the Sortino ratio: mean return divided by downside deviation.
|
348
|
+
Based on Red Rock Capital's Sortino ratio paper.
|
349
|
+
"""
|
350
|
+
|
351
|
+
downside_deviation = np.sqrt(((series.filter(series < 0)) ** 2).mean())
|
352
|
+
|
353
|
+
ratio = series.mean() / downside_deviation
|
354
|
+
return ratio * np.sqrt(periods)
|
355
|
+
|
356
|
+
@to_frame
|
357
|
+
def rolling_sortino(self, series, rolling_period=126, periods_per_year=252):
|
358
|
+
mean_ret = series.rolling_mean(window_size=rolling_period)
|
359
|
+
|
360
|
+
# Rolling downside deviation (squared negative returns averaged over window)
|
361
|
+
downside = series.map_elements(lambda x: x**2 if x < 0 else 0.0).rolling_mean(window_size=rolling_period)
|
362
|
+
|
363
|
+
# Avoid division by zero
|
364
|
+
sortino = mean_ret / downside.sqrt().fill_nan(0).fill_null(0)
|
365
|
+
return sortino * (periods_per_year**0.5)
|
366
|
+
|
367
|
+
def adjusted_sortino(self, periods=252):
|
368
|
+
"""
|
369
|
+
Jack Schwager's adjusted Sortino ratio for direct comparison to Sharpe.
|
370
|
+
See: https://archive.is/wip/2rwFW
|
371
|
+
"""
|
372
|
+
sortino_data = self.sortino(periods=periods)
|
373
|
+
return {k: v / np.sqrt(2) for k, v in sortino_data.items()}
|
374
|
+
|
375
|
+
@columnwise_stat
|
376
|
+
def r_squared(self, series, benchmark=None):
|
377
|
+
"""Measures the straight line fit of the equity curve"""
|
378
|
+
if self.data.benchmark is None:
|
379
|
+
raise AttributeError("No benchmark data available")
|
380
|
+
|
381
|
+
benchmark_col = benchmark or self.data.benchmark.columns[0]
|
382
|
+
|
383
|
+
# if self.data.benchmark is None:
|
384
|
+
# raise AttributeError("No benchmark data available")
|
385
|
+
# Evaluate both series and benchmark as Series
|
386
|
+
df = self.all.select([series, pl.col(benchmark_col).alias("benchmark")])
|
387
|
+
|
388
|
+
# Drop nulls
|
389
|
+
df = df.drop_nulls()
|
390
|
+
print(df)
|
391
|
+
|
392
|
+
matrix = df.to_numpy()
|
393
|
+
# Get actual Series
|
394
|
+
|
395
|
+
strategy_np = matrix[:, 0]
|
396
|
+
benchmark_np = matrix[:, 1]
|
397
|
+
|
398
|
+
corr_matrix = np.corrcoef(strategy_np, benchmark_np)
|
399
|
+
r = corr_matrix[0, 1]
|
400
|
+
return r**2
|
401
|
+
|
402
|
+
def r2(self):
|
403
|
+
"""Shorthand for r_squared()"""
|
404
|
+
return self.r_squared()
|
405
|
+
|
406
|
+
@columnwise_stat
|
407
|
+
def information_ratio(self, series, periods_per_year=252, benchmark=None):
|
408
|
+
"""
|
409
|
+
Calculates the information ratio
|
410
|
+
(basically the risk return ratio of the net profits)
|
411
|
+
"""
|
412
|
+
benchmark_col = benchmark or self.data.benchmark.columns[0]
|
413
|
+
|
414
|
+
active = series - self.data.benchmark[benchmark_col]
|
415
|
+
|
416
|
+
mean = active.mean()
|
417
|
+
std = active.std()
|
418
|
+
|
419
|
+
try:
|
420
|
+
return (mean / std) * (periods_per_year**0.5)
|
421
|
+
except ZeroDivisionError:
|
422
|
+
return 0.0
|
423
|
+
|
424
|
+
@columnwise_stat
|
425
|
+
def greeks(self, series, periods_per_year=252, benchmark=None):
|
426
|
+
"""Calculates alpha and beta of the portfolio"""
|
427
|
+
# find covariance
|
428
|
+
benchmark_col = benchmark or self.data.benchmark.columns[0]
|
429
|
+
|
430
|
+
# Evaluate both series and benchmark as Series
|
431
|
+
df = self.all.select([series, pl.col(benchmark_col).alias("benchmark")])
|
432
|
+
|
433
|
+
# Drop nulls
|
434
|
+
df = df.drop_nulls()
|
435
|
+
matrix = df.to_numpy()
|
436
|
+
|
437
|
+
# Get actual Series
|
438
|
+
strategy_np = matrix[:, 0]
|
439
|
+
benchmark_np = matrix[:, 1]
|
440
|
+
|
441
|
+
# 2x2 covariance matrix: [[var_strategy, cov], [cov, var_benchmark]]
|
442
|
+
cov_matrix = np.cov(strategy_np, benchmark_np)
|
443
|
+
|
444
|
+
cov = cov_matrix[0, 1]
|
445
|
+
var_benchmark = cov_matrix[1, 1]
|
446
|
+
|
447
|
+
beta = cov / var_benchmark if var_benchmark != 0 else float("nan")
|
448
|
+
alpha = np.mean(strategy_np) - beta * np.mean(benchmark_np)
|
449
|
+
|
450
|
+
return {"alpha": alpha * periods_per_year, "beta": beta}
|
jquantstats/api.py
ADDED
@@ -0,0 +1,222 @@
|
|
1
|
+
# QuantStats: Portfolio analytics for quants
|
2
|
+
# https://github.com/tschm/jquantstats
|
3
|
+
#
|
4
|
+
# Copyright 2019-2024 Ran Aroussi
|
5
|
+
# Copyright 2025 Thomas Schmelzer
|
6
|
+
#
|
7
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
8
|
+
# you may not use this file except in compliance with the License.
|
9
|
+
# You may obtain a copy of the License at
|
10
|
+
#
|
11
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
12
|
+
#
|
13
|
+
# Unless required by applicable law or agreed to in writing, software
|
14
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
15
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
16
|
+
# See the License for the specific language governing permissions and
|
17
|
+
# limitations under the License.
|
18
|
+
|
19
|
+
"""
|
20
|
+
QuantStats API module.
|
21
|
+
|
22
|
+
This module provides the core API for the QuantStats library,
|
23
|
+
including the Data class
|
24
|
+
for handling financial returns data and benchmarks.
|
25
|
+
"""
|
26
|
+
|
27
|
+
import dataclasses
|
28
|
+
|
29
|
+
import polars as pl
|
30
|
+
|
31
|
+
from ._plots import Plots
|
32
|
+
from ._stats import Stats
|
33
|
+
|
34
|
+
|
35
|
+
def build_data(
|
36
|
+
returns: pl.DataFrame, rf: float | pl.DataFrame = 0.0, benchmark: pl.DataFrame = None, date_col: str = "Date"
|
37
|
+
) -> "_Data":
|
38
|
+
"""
|
39
|
+
Build a _Data object from returns and optional benchmark using Polars.
|
40
|
+
|
41
|
+
Parameters:
|
42
|
+
returns (pl.DataFrame): Financial returns.
|
43
|
+
rf (float | pl.DataFrame): Risk-free rate (scalar or time series).
|
44
|
+
benchmark (pl.DataFrame, optional): Benchmark returns.
|
45
|
+
date_col (str): Name of the date column.
|
46
|
+
|
47
|
+
Returns:
|
48
|
+
_Data: Object containing excess returns and benchmark (if any).
|
49
|
+
"""
|
50
|
+
|
51
|
+
def subtract_risk_free(df: pl.DataFrame, rf: float | pl.DataFrame, date_col: str) -> pl.DataFrame:
|
52
|
+
if df is None:
|
53
|
+
return None
|
54
|
+
|
55
|
+
# Handle scalar rf case
|
56
|
+
if isinstance(rf, float):
|
57
|
+
rf_df = df.select([pl.col(date_col), pl.lit(rf).alias("rf")])
|
58
|
+
else:
|
59
|
+
rf_df = rf.rename({rf.columns[1]: "rf"}) if rf.columns[1] != "rf" else rf
|
60
|
+
|
61
|
+
# Join and subtract
|
62
|
+
df = df.join(rf_df, on=date_col, how="inner")
|
63
|
+
return df.select(
|
64
|
+
[pl.col(date_col)]
|
65
|
+
+ [
|
66
|
+
(pl.col(col) - pl.col("rf")).alias(col)
|
67
|
+
for col in df.columns
|
68
|
+
if col not in {date_col, "rf"} and df.schema[col] in pl.NUMERIC_DTYPES
|
69
|
+
]
|
70
|
+
)
|
71
|
+
|
72
|
+
# Align returns and benchmark if both provided
|
73
|
+
if benchmark is not None:
|
74
|
+
joined_dates = returns.join(benchmark, on=date_col, how="inner").select(date_col)
|
75
|
+
if joined_dates.is_empty():
|
76
|
+
raise ValueError("No overlapping dates between returns and benchmark.")
|
77
|
+
returns = returns.join(joined_dates, on=date_col, how="inner")
|
78
|
+
benchmark = benchmark.join(joined_dates, on=date_col, how="inner")
|
79
|
+
|
80
|
+
# Subtract risk-free rate
|
81
|
+
index = returns.select(date_col)
|
82
|
+
excess_returns = subtract_risk_free(returns, rf, date_col).drop(date_col)
|
83
|
+
excess_benchmark = subtract_risk_free(benchmark, rf, date_col).drop(date_col) if benchmark is not None else None
|
84
|
+
|
85
|
+
return _Data(returns=excess_returns, benchmark=excess_benchmark, index=index)
|
86
|
+
|
87
|
+
|
88
|
+
@dataclasses.dataclass(frozen=True)
|
89
|
+
class _Data:
|
90
|
+
"""
|
91
|
+
A container for financial returns data and an optional benchmark.
|
92
|
+
|
93
|
+
This class provides methods for analyzing and manipulating financial returns data,
|
94
|
+
including converting returns to prices, calculating drawdowns, and resampling data
|
95
|
+
to different time periods.
|
96
|
+
|
97
|
+
Attributes:
|
98
|
+
returns (pd.DataFrame): DataFrame containing returns data, typically with dates as index
|
99
|
+
and assets as columns.
|
100
|
+
#benchmark (pd.Series, optional): Series containing benchmark returns data with the same
|
101
|
+
# index as returns. Defaults to None.
|
102
|
+
"""
|
103
|
+
|
104
|
+
returns: pl.DataFrame
|
105
|
+
benchmark: pl.DataFrame | None = None
|
106
|
+
index: pl.DataFrame | None = None
|
107
|
+
|
108
|
+
@property
|
109
|
+
def plots(self):
|
110
|
+
return Plots(self)
|
111
|
+
|
112
|
+
@property
|
113
|
+
def stats(self):
|
114
|
+
return Stats(self)
|
115
|
+
|
116
|
+
@property
|
117
|
+
def date_col(self):
|
118
|
+
return self.index.columns
|
119
|
+
|
120
|
+
@property
|
121
|
+
def assets(self):
|
122
|
+
try:
|
123
|
+
return self.returns.columns + self.benchmark.columns
|
124
|
+
except AttributeError:
|
125
|
+
return self.returns.columns
|
126
|
+
|
127
|
+
def __post_init__(self) -> None:
|
128
|
+
"""
|
129
|
+
Validates that the benchmark index matches the returns index if benchmark is provided.
|
130
|
+
|
131
|
+
Raises:
|
132
|
+
AssertionError: If benchmark is provided and its index doesn't match returns index.
|
133
|
+
"""
|
134
|
+
|
135
|
+
@property
|
136
|
+
def all(self) -> pl.DataFrame:
|
137
|
+
"""
|
138
|
+
Combines returns and benchmark data into a single DataFrame.
|
139
|
+
|
140
|
+
Returns:
|
141
|
+
pd.DataFrame: A DataFrame containing all returns data and benchmark (if available),
|
142
|
+
with NaN values filled with 0.0.
|
143
|
+
"""
|
144
|
+
if self.benchmark is None:
|
145
|
+
return pl.concat([self.index, self.returns], how="horizontal")
|
146
|
+
else:
|
147
|
+
return pl.concat([self.index, self.returns, self.benchmark], how="horizontal")
|
148
|
+
|
149
|
+
def resample(self, every: str = "1mo", compounded: bool = False) -> "_Data":
|
150
|
+
"""
|
151
|
+
Resamples returns and benchmark to a different frequency using Polars.
|
152
|
+
|
153
|
+
Args:
|
154
|
+
every (str, optional): Resampling frequency (e.g., '1mo', '1y'). Defaults to '1mo'.
|
155
|
+
compounded (bool, optional): Whether to compound returns. Defaults to False.
|
156
|
+
|
157
|
+
Returns:
|
158
|
+
_Data: Resampled data.
|
159
|
+
"""
|
160
|
+
|
161
|
+
def resample_frame(df: pl.DataFrame) -> pl.DataFrame:
|
162
|
+
if df is None:
|
163
|
+
return None
|
164
|
+
|
165
|
+
df = self.index.hstack(df) # Add the date column for resampling
|
166
|
+
|
167
|
+
return df.group_by_dynamic(
|
168
|
+
index_column=self.index.columns[0], every=every, period=every, closed="right", label="right"
|
169
|
+
).agg(
|
170
|
+
[
|
171
|
+
pl.col(col).sum().alias(col) if not compounded else ((pl.col(col) + 1.0).product() - 1.0).alias(col)
|
172
|
+
for col in df.columns
|
173
|
+
if col != self.index.columns[0]
|
174
|
+
]
|
175
|
+
)
|
176
|
+
|
177
|
+
resampled_returns = resample_frame(self.returns)
|
178
|
+
resampled_benchmark = resample_frame(self.benchmark) if self.benchmark is not None else None
|
179
|
+
resampled_index = resampled_returns.select(self.index.columns[0])
|
180
|
+
|
181
|
+
return _Data(
|
182
|
+
returns=resampled_returns.drop(self.index.columns[0]),
|
183
|
+
benchmark=resampled_benchmark.drop(self.index.columns[0]) if resampled_benchmark is not None else None,
|
184
|
+
index=resampled_index,
|
185
|
+
)
|
186
|
+
|
187
|
+
def copy(self) -> "_Data":
|
188
|
+
"""
|
189
|
+
Creates a deep copy of the Data object.
|
190
|
+
|
191
|
+
Returns:
|
192
|
+
_Data: A new Data object with copies of the returns and benchmark.
|
193
|
+
"""
|
194
|
+
try:
|
195
|
+
return _Data(returns=self.returns.clone(), benchmark=self.benchmark.clone(), index=self.index.clone())
|
196
|
+
except AttributeError:
|
197
|
+
# Handle case where benchmark is None
|
198
|
+
return _Data(returns=self.returns.clone(), index=self.index.clone())
|
199
|
+
|
200
|
+
def head(self, n: int = 5) -> "_Data":
|
201
|
+
"""
|
202
|
+
Returns the first n rows of the combined returns and benchmark data.
|
203
|
+
|
204
|
+
Args:
|
205
|
+
n (int, optional): Number of rows to return. Defaults to 5.
|
206
|
+
|
207
|
+
Returns:
|
208
|
+
_Data: A new Data object containing the first n rows of the combined data.
|
209
|
+
"""
|
210
|
+
return _Data(returns=self.returns.head(n), benchmark=self.benchmark.head(n), index=self.index.head(n))
|
211
|
+
|
212
|
+
def tail(self, n: int = 5) -> "_Data":
|
213
|
+
"""
|
214
|
+
Returns the last n rows of the combined returns and benchmark data.
|
215
|
+
|
216
|
+
Args:
|
217
|
+
n (int, optional): Number of rows to return. Defaults to 5.
|
218
|
+
|
219
|
+
Returns:
|
220
|
+
_Data: A new Data object containing the last n rows of the combined data.
|
221
|
+
"""
|
222
|
+
return _Data(returns=self.returns.tail(n), benchmark=self.benchmark.tail(n), index=self.index.tail(n))
|
@@ -0,0 +1,150 @@
|
|
1
|
+
Metadata-Version: 2.4
|
2
|
+
Name: jquantstats
|
3
|
+
Version: 0.0.2
|
4
|
+
Summary: Toying with quantstats
|
5
|
+
Project-URL: repository, https://github.com/tschm/jquantstats
|
6
|
+
Author-email: tschm <thomas.schmelzer@gmail.com>
|
7
|
+
License-File: LICENSE.txt
|
8
|
+
Requires-Python: >=3.10
|
9
|
+
Requires-Dist: kaleido==0.2.1
|
10
|
+
Requires-Dist: numpy>=2.2.3
|
11
|
+
Requires-Dist: plotly>=6.0.0
|
12
|
+
Requires-Dist: polars==1.29.0
|
13
|
+
Provides-Extra: dev
|
14
|
+
Requires-Dist: pre-commit==4.2.0; extra == 'dev'
|
15
|
+
Requires-Dist: pytest-cov==6.1.1; extra == 'dev'
|
16
|
+
Requires-Dist: pytest==8.3.5; extra == 'dev'
|
17
|
+
Requires-Dist: yfinance==0.2.58; extra == 'dev'
|
18
|
+
Description-Content-Type: text/markdown
|
19
|
+
|
20
|
+
# [jQuantStats](https://tschm.github.io/jquantstats/book): Portfolio analytics for quants
|
21
|
+
|
22
|
+
[](https://badge.fury.io/py/jquantstats)
|
23
|
+
[](LICENSE.txt)
|
24
|
+
[](https://github.com/tschm/jquantstats/actions/workflows/ci.yml)
|
25
|
+
[](https://coveralls.io/github/tschm/jquantstats?branch=main)
|
26
|
+
[](https://www.codefactor.io/repository/github/tschm/quantstats)
|
27
|
+
[](https://github.com/renovatebot/renovate)
|
28
|
+
|
29
|
+
[](https://codespaces.new/tschm/jquantstats)
|
30
|
+
|
31
|
+
## Overview
|
32
|
+
|
33
|
+
**jQuantStats** is a Python library for portfolio analytics
|
34
|
+
that helps quants and portfolio managers understand
|
35
|
+
their performance through in-depth analytics and risk metrics.
|
36
|
+
It provides tools for calculating various performance metrics
|
37
|
+
and visualizing portfolio performance.
|
38
|
+
|
39
|
+
The library is inspired by and currently exposes a subset of the
|
40
|
+
functionality of [QuantStats](https://github.com/ranaroussi/quantstats),
|
41
|
+
focusing on providing a clean, modern API with enhanced
|
42
|
+
visualization capabilities using Plotly.
|
43
|
+
|
44
|
+
We have made the following changes when compared to quantstats:
|
45
|
+
|
46
|
+
- added tests (based on pytest), pre-commit hooks and
|
47
|
+
github ci/cd workflows
|
48
|
+
- removed a direct dependency on yfinance to inject data
|
49
|
+
- moved all graphical output to plotly and removed the matplotlib dependency
|
50
|
+
- removed some statistical metrics but intend to bring them back
|
51
|
+
- moved to Marimo for demos
|
52
|
+
- gave up on the very tight coupling with pandas
|
53
|
+
|
54
|
+
Along the way we broke downwards compatibility with quantstats but the
|
55
|
+
underlying usage pattern is too different. Users familiar with
|
56
|
+
Dataclasses may find the chosen path appealing.
|
57
|
+
A data class is
|
58
|
+
constructed using the `build_data` function.
|
59
|
+
This function is essentially
|
60
|
+
the only viable entry point into jquantstats.
|
61
|
+
It constructs and returns
|
62
|
+
a `_Data` object which exposes plots and stats via its member attributes.
|
63
|
+
|
64
|
+
At this early stage the user would have to define a benchmark
|
65
|
+
and set the underlying risk-free rate.
|
66
|
+
|
67
|
+
## Features
|
68
|
+
|
69
|
+
- **Performance Metrics**: Calculate key metrics like Sharpe ratio, Sortino ratio,
|
70
|
+
drawdowns, volatility, and many more
|
71
|
+
- **Risk Analysis**: Analyze risk through metrics like Value at Risk (VaR),
|
72
|
+
Conditional VaR, and drawdown analysis
|
73
|
+
- **Visualization**: Create interactive plots for portfolio performance, drawdowns,
|
74
|
+
return distributions, and monthly heatmaps
|
75
|
+
- **Benchmark Comparison**: Compare your portfolio performance against benchmarks
|
76
|
+
|
77
|
+
## Installation
|
78
|
+
|
79
|
+
```bash
|
80
|
+
pip install jquantstats
|
81
|
+
```
|
82
|
+
|
83
|
+
For development:
|
84
|
+
|
85
|
+
```bash
|
86
|
+
pip install jquantstats[dev]
|
87
|
+
```
|
88
|
+
|
89
|
+
## Quick Start
|
90
|
+
|
91
|
+
```python
|
92
|
+
import pandas as pd
|
93
|
+
from jquantstats.api import build_data
|
94
|
+
|
95
|
+
# Create a Data object from returns
|
96
|
+
returns = pd.DataFrame(...) # Your returns data
|
97
|
+
|
98
|
+
# Basic usage
|
99
|
+
data = build_data(returns=returns)
|
100
|
+
|
101
|
+
# With benchmark and risk-free rate
|
102
|
+
benchmark = pd.Series(...) # Your benchmark returns
|
103
|
+
data = build_data(
|
104
|
+
returns=returns,
|
105
|
+
benchmark=benchmark,
|
106
|
+
rf=0.02, # risk-free rate (e.g., 2% annual rate)
|
107
|
+
nperiods=252 # number of trading days per year
|
108
|
+
)
|
109
|
+
|
110
|
+
# Calculate statistics
|
111
|
+
sharpe = data.stats.sharpe()
|
112
|
+
volatility = data.stats.volatility()
|
113
|
+
|
114
|
+
# Create visualizations
|
115
|
+
fig = data.plots.plot_snapshot(title="Portfolio Performance")
|
116
|
+
fig.show()
|
117
|
+
|
118
|
+
# Monthly returns heatmap
|
119
|
+
fig = data.plots.monthly_heatmap()
|
120
|
+
fig.show()
|
121
|
+
```
|
122
|
+
|
123
|
+
## Documentation
|
124
|
+
|
125
|
+
For detailed documentation,
|
126
|
+
visit [jQuantStats Documentation](https://tschm.github.io/jquantstats/book).
|
127
|
+
|
128
|
+
## Requirements
|
129
|
+
|
130
|
+
- Python 3.10+
|
131
|
+
- numpy
|
132
|
+
- pandas
|
133
|
+
- scipy
|
134
|
+
- plotly
|
135
|
+
- kaleido (for static image export)
|
136
|
+
|
137
|
+
## Contributing
|
138
|
+
|
139
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
140
|
+
|
141
|
+
1. Fork the repository
|
142
|
+
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
|
143
|
+
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
|
144
|
+
4. Push to the branch (`git push origin feature/amazing-feature`)
|
145
|
+
5. Open a Pull Request
|
146
|
+
|
147
|
+
## License
|
148
|
+
|
149
|
+
This project is licensed under the
|
150
|
+
Apache License 2.0 - see the [LICENSE.txt](LICENSE.txt) file for details.
|
@@ -0,0 +1,8 @@
|
|
1
|
+
jquantstats/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
2
|
+
jquantstats/_plots.py,sha256=y3hGRvw-2X9EJaCRoI2zQ7G4Ghm5rlXiORlr2h9BrkA,10077
|
3
|
+
jquantstats/_stats.py,sha256=ftROfeBH_3AIpp-ZLAGSLEHE2XUYfdbTIWk7pGD4lOQ,15163
|
4
|
+
jquantstats/api.py,sha256=OZ9znbQFx4qwA1oh3mEBsrXDtRpcNEHzaJ9u5N9fikA,7995
|
5
|
+
jquantstats-0.0.2.dist-info/METADATA,sha256=eBXVpTwtADqDl97x35oD-xJAk-TPT63PCv_yjnjiEWg,5081
|
6
|
+
jquantstats-0.0.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
7
|
+
jquantstats-0.0.2.dist-info/licenses/LICENSE.txt,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142
|
8
|
+
jquantstats-0.0.2.dist-info/RECORD,,
|
@@ -0,0 +1,175 @@
|
|
1
|
+
|
2
|
+
Apache License
|
3
|
+
Version 2.0, January 2004
|
4
|
+
http://www.apache.org/licenses/
|
5
|
+
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
7
|
+
|
8
|
+
1. Definitions.
|
9
|
+
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
12
|
+
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
14
|
+
the copyright owner that is granting the License.
|
15
|
+
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
17
|
+
other entities that control, are controlled by, or are under common
|
18
|
+
control with that entity. For the purposes of this definition,
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
20
|
+
direction or management of such entity, whether by contract or
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
23
|
+
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
25
|
+
exercising permissions granted by this License.
|
26
|
+
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
28
|
+
including but not limited to software source code, documentation
|
29
|
+
source, and configuration files.
|
30
|
+
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
32
|
+
transformation or translation of a Source form, including but
|
33
|
+
not limited to compiled object code, generated documentation,
|
34
|
+
and conversions to other media types.
|
35
|
+
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
37
|
+
Object form, made available under the License, as indicated by a
|
38
|
+
copyright notice that is included in or attached to the work
|
39
|
+
(an example is provided in the Appendix below).
|
40
|
+
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
47
|
+
the Work and Derivative Works thereof.
|
48
|
+
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
50
|
+
the original version of the Work and any modifications or additions
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
62
|
+
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
65
|
+
subsequently incorporated within the Work.
|
66
|
+
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
73
|
+
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
79
|
+
where such license applies only to those patent claims licensable
|
80
|
+
by such Contributor that are necessarily infringed by their
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
83
|
+
institute patent litigation against any entity (including a
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
86
|
+
or contributory patent infringement, then any patent licenses
|
87
|
+
granted to You under this License for that Work shall terminate
|
88
|
+
as of the date such litigation is filed.
|
89
|
+
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
92
|
+
modifications, and in Source or Object form, provided that You
|
93
|
+
meet the following conditions:
|
94
|
+
|
95
|
+
(a) You must give any other recipients of the Work or
|
96
|
+
Derivative Works a copy of this License; and
|
97
|
+
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
99
|
+
stating that You changed the files; and
|
100
|
+
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
103
|
+
attribution notices from the Source form of the Work,
|
104
|
+
excluding those notices that do not pertain to any part of
|
105
|
+
the Derivative Works; and
|
106
|
+
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
109
|
+
include a readable copy of the attribution notices contained
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
112
|
+
of the following places: within a NOTICE text file distributed
|
113
|
+
as part of the Derivative Works; within the Source form or
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
115
|
+
within a display generated by the Derivative Works, if and
|
116
|
+
wherever such third-party notices normally appear. The contents
|
117
|
+
of the NOTICE file are for informational purposes only and
|
118
|
+
do not modify the License. You may add Your own attribution
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
121
|
+
that such additional attribution notices cannot be construed
|
122
|
+
as modifying the License.
|
123
|
+
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
125
|
+
may provide additional or different license terms and conditions
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
129
|
+
the conditions stated in this License.
|
130
|
+
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
134
|
+
this License, without any additional terms or conditions.
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
136
|
+
the terms of any separate license agreement you may have executed
|
137
|
+
with Licensor regarding such Contributions.
|
138
|
+
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
141
|
+
except as required for reasonable and customary use in describing the
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
143
|
+
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
153
|
+
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
159
|
+
incidental, or consequential damages of any character arising as a
|
160
|
+
result of this License or out of the use or inability to use the
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
163
|
+
other commercial damages or losses), even if such Contributor
|
164
|
+
has been advised of the possibility of such damages.
|
165
|
+
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
169
|
+
or other liability obligations and/or rights consistent with this
|
170
|
+
License. However, in accepting such obligations, You may act only
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
175
|
+
of your accepting any such warranty or additional liability.
|