squarequant 0.1.0__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.
- squarequant/__init__.py +41 -0
- squarequant/api.py +548 -0
- squarequant/constants.py +35 -0
- squarequant/core/__init__.py +6 -0
- squarequant/core/base.py +166 -0
- squarequant/core/data.py +106 -0
- squarequant/core/metrics.py +1633 -0
- squarequant/plot/__init__.py +7 -0
- squarequant/plot/plot.py +972 -0
- squarequant/utils/__init__.py +6 -0
- squarequant/utils/helpers.py +85 -0
- squarequant-0.1.0.dist-info/LICENSE +21 -0
- squarequant-0.1.0.dist-info/METADATA +217 -0
- squarequant-0.1.0.dist-info/RECORD +16 -0
- squarequant-0.1.0.dist-info/WHEEL +5 -0
- squarequant-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Helper functions for the SquareQuant package
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
import numpy as np
|
|
7
|
+
from datetime import datetime, timedelta
|
|
8
|
+
from typing import List, Optional, Union, Dict, Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def validate_date_format(date_str: str) -> bool:
|
|
12
|
+
"""
|
|
13
|
+
Validate that a date string is in the correct format.
|
|
14
|
+
|
|
15
|
+
Parameters:
|
|
16
|
+
date_str (str): Date string to validate
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
bool: True if the date is valid, False otherwise
|
|
20
|
+
"""
|
|
21
|
+
try:
|
|
22
|
+
datetime.strptime(date_str, '%Y-%m-%d')
|
|
23
|
+
return True
|
|
24
|
+
except ValueError:
|
|
25
|
+
return False
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def date_range_filter(df: pd.DataFrame,
|
|
29
|
+
start: Optional[str] = None,
|
|
30
|
+
end: Optional[str] = None) -> pd.DataFrame:
|
|
31
|
+
"""
|
|
32
|
+
Filter a DataFrame by date range.
|
|
33
|
+
|
|
34
|
+
Parameters:
|
|
35
|
+
df (DataFrame): DataFrame to filter
|
|
36
|
+
start (str, optional): Start date in format 'YYYY-MM-DD'
|
|
37
|
+
end (str, optional): End date in format 'YYYY-MM-DD'
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
DataFrame: Filtered DataFrame
|
|
41
|
+
"""
|
|
42
|
+
if start or end:
|
|
43
|
+
mask = pd.Series(True, index=df.index)
|
|
44
|
+
|
|
45
|
+
if start:
|
|
46
|
+
if not validate_date_format(start):
|
|
47
|
+
raise ValueError("Start date must be in YYYY-MM-DD format")
|
|
48
|
+
mask = mask & (df.index >= start)
|
|
49
|
+
|
|
50
|
+
if end:
|
|
51
|
+
if not validate_date_format(end):
|
|
52
|
+
raise ValueError("End date must be in YYYY-MM-DD format")
|
|
53
|
+
mask = mask & (df.index <= end)
|
|
54
|
+
|
|
55
|
+
return df[mask]
|
|
56
|
+
|
|
57
|
+
return df
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def annualize_returns(returns: pd.DataFrame, periods_per_year: int = 252) -> pd.DataFrame:
|
|
61
|
+
"""
|
|
62
|
+
Annualize returns based on the frequency of the data.
|
|
63
|
+
|
|
64
|
+
Parameters:
|
|
65
|
+
returns (DataFrame): DataFrame with returns data
|
|
66
|
+
periods_per_year (int): Number of periods per year (252 for daily, 12 for monthly, etc.)
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
DataFrame: DataFrame with annualized returns
|
|
70
|
+
"""
|
|
71
|
+
return returns.mean() * periods_per_year
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def annualize_volatility(returns: pd.DataFrame, periods_per_year: int = 252) -> pd.DataFrame:
|
|
75
|
+
"""
|
|
76
|
+
Annualize volatility based on the frequency of the data.
|
|
77
|
+
|
|
78
|
+
Parameters:
|
|
79
|
+
returns (DataFrame): DataFrame with returns data
|
|
80
|
+
periods_per_year (int): Number of periods per year (252 for daily, 12 for monthly, etc.)
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
DataFrame: DataFrame with annualized volatility
|
|
84
|
+
"""
|
|
85
|
+
return returns.std() * np.sqrt(periods_per_year)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Gabriel Bosch
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: squarequant
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A Python package for quantitative finance
|
|
5
|
+
Home-page: https://github.com/SquareQuant/squarequant-package
|
|
6
|
+
Author: Gabriel Bosch
|
|
7
|
+
Author-email: contact@suqarequant.org
|
|
8
|
+
Project-URL: Documentation, https://squarequant.readthedocs.io
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/SquareQuant/squarequant-package/issues
|
|
10
|
+
Keywords: finance,risk,portfolio,investment,stocks,analysis,visualization
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
19
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
20
|
+
Classifier: Intended Audience :: Science/Research
|
|
21
|
+
Classifier: Development Status :: 4 - Beta
|
|
22
|
+
Requires-Python: >=3.7
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: pandas>=1.0.0
|
|
26
|
+
Requires-Dist: numpy>=1.18.0
|
|
27
|
+
Requires-Dist: yfinance>=0.1.63
|
|
28
|
+
Requires-Dist: scipy>=1.5.0
|
|
29
|
+
Requires-Dist: matplotlib>=3.3.0
|
|
30
|
+
Provides-Extra: optimization
|
|
31
|
+
Requires-Dist: cvxpy>=1.0.0; extra == "optimization"
|
|
32
|
+
Provides-Extra: dev
|
|
33
|
+
Requires-Dist: pytest>=6.0.0; extra == "dev"
|
|
34
|
+
Requires-Dist: black>=21.5b2; extra == "dev"
|
|
35
|
+
Requires-Dist: flake8>=3.9.0; extra == "dev"
|
|
36
|
+
Requires-Dist: sphinx>=4.0.0; extra == "dev"
|
|
37
|
+
Requires-Dist: sphinx-rtd-theme>=0.5.0; extra == "dev"
|
|
38
|
+
Dynamic: author
|
|
39
|
+
Dynamic: author-email
|
|
40
|
+
Dynamic: classifier
|
|
41
|
+
Dynamic: description
|
|
42
|
+
Dynamic: description-content-type
|
|
43
|
+
Dynamic: home-page
|
|
44
|
+
Dynamic: keywords
|
|
45
|
+
Dynamic: project-url
|
|
46
|
+
Dynamic: provides-extra
|
|
47
|
+
Dynamic: requires-dist
|
|
48
|
+
Dynamic: requires-python
|
|
49
|
+
Dynamic: summary
|
|
50
|
+
|
|
51
|
+
# SquareQuant
|
|
52
|
+
|
|
53
|
+
A professional-grade Python package for financial risk analysis, advanced portfolio metrics, and investment visualization with a focus on performance and usability.
|
|
54
|
+
|
|
55
|
+
## Features
|
|
56
|
+
|
|
57
|
+
### Data Management
|
|
58
|
+
- Seamless download and integration with Yahoo Finance data
|
|
59
|
+
- Flexible data filtering and preprocessing utilities
|
|
60
|
+
- Configurable date ranges and interval selection
|
|
61
|
+
|
|
62
|
+
### Risk Metrics
|
|
63
|
+
- **Standard Metrics**:
|
|
64
|
+
- Sharpe & Sortino Ratios
|
|
65
|
+
- Volatility & Semi-Deviation
|
|
66
|
+
- Maximum Drawdown (MDD) & Average Drawdown
|
|
67
|
+
- Value at Risk (VaR) & Conditional Value at Risk (CVaR)
|
|
68
|
+
- **Advanced Metrics**:
|
|
69
|
+
- Mean Absolute Deviation (MAD)
|
|
70
|
+
- Ulcer Index
|
|
71
|
+
- Entropic Risk Measure (ERM)
|
|
72
|
+
- Entropic Value at Risk (EVaR)
|
|
73
|
+
- Conditional Drawdown at Risk (CDaR)
|
|
74
|
+
- Entropic Drawdown at Risk (EDaR)
|
|
75
|
+
|
|
76
|
+
### Visualization
|
|
77
|
+
- Interactive risk metrics dashboards
|
|
78
|
+
- Correlation matrix heatmaps
|
|
79
|
+
- Drawdown analysis charts
|
|
80
|
+
- Return distribution visualization
|
|
81
|
+
- Risk contribution analysis
|
|
82
|
+
- Portfolio weight allocation diagrams
|
|
83
|
+
|
|
84
|
+
### Implementation Advantages
|
|
85
|
+
- Memory-efficient vectorized calculations
|
|
86
|
+
- Dual API approaches: functional & object-oriented
|
|
87
|
+
- Configurable window sizes for all metrics
|
|
88
|
+
- Minimal external dependencies
|
|
89
|
+
|
|
90
|
+
## Installation
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
pip install squarequant
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Quick Start Guide
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
import squarequant as sq
|
|
100
|
+
import matplotlib.pyplot as plt
|
|
101
|
+
|
|
102
|
+
# Download stock data
|
|
103
|
+
tickers = ["AAPL", "MSFT", "GOOGL"]
|
|
104
|
+
config = sq.DownloadConfig(
|
|
105
|
+
start_date="2020-01-01",
|
|
106
|
+
end_date="2023-01-01",
|
|
107
|
+
interval="1d"
|
|
108
|
+
)
|
|
109
|
+
data = sq.download_tickers(tickers, config)
|
|
110
|
+
|
|
111
|
+
# Calculate risk metrics
|
|
112
|
+
assets = ["AAPL_Close", "MSFT_Close", "GOOGL_Close"]
|
|
113
|
+
|
|
114
|
+
# Sharpe ratio with a 1-year rolling window
|
|
115
|
+
sharpe_ratios = sq.sharpe(data, assets, window=252)
|
|
116
|
+
|
|
117
|
+
# Plot the results
|
|
118
|
+
plt.figure(figsize=(12, 8))
|
|
119
|
+
sharpe_ratios.plot()
|
|
120
|
+
plt.title("Rolling Sharpe Ratios")
|
|
121
|
+
plt.show()
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Advanced Usage Examples
|
|
125
|
+
|
|
126
|
+
### Multiple Risk Metrics Visualization
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
# Create a visualization of multiple risk metrics
|
|
130
|
+
sq.plot_rolling_metrics(
|
|
131
|
+
data=data,
|
|
132
|
+
assets=assets,
|
|
133
|
+
metrics=['sharpe', 'vol', 'mdd', 'var'],
|
|
134
|
+
windows={'vol': 20, 'mdd': 252}
|
|
135
|
+
)
|
|
136
|
+
plt.show()
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Risk Comparison Dashboard
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
# Create a risk comparison dashboard
|
|
143
|
+
sq.plot_risk_comparison(
|
|
144
|
+
data=data,
|
|
145
|
+
assets=assets,
|
|
146
|
+
risk_metrics=['vol', 'mdd', 'var', 'cvar', 'semidev', 'ulcer'],
|
|
147
|
+
)
|
|
148
|
+
plt.show()
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### Performance Metrics Table
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
# Generate a performance metrics table
|
|
155
|
+
sq.plot_performance_metrics(
|
|
156
|
+
data=data,
|
|
157
|
+
assets=assets,
|
|
158
|
+
risk_free=0.02, # 2% risk-free rate
|
|
159
|
+
)
|
|
160
|
+
plt.show()
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
### Object-Oriented Interface
|
|
164
|
+
|
|
165
|
+
SquareQuant provides an object-oriented interface for more advanced use cases:
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
from squarequant.core.metrics import EntropicValueAtRisk
|
|
169
|
+
|
|
170
|
+
# Create an EVaR calculator
|
|
171
|
+
calculator = EntropicValueAtRisk(
|
|
172
|
+
data=data,
|
|
173
|
+
assets=assets,
|
|
174
|
+
alpha=0.95, # 95% confidence level
|
|
175
|
+
window=252,
|
|
176
|
+
start="2021-01-01",
|
|
177
|
+
end="2022-01-01"
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
# Calculate EVaR
|
|
181
|
+
evar_values = calculator.calculate()
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
## Configuration Options
|
|
185
|
+
|
|
186
|
+
### Custom Risk-Free Rate
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
# Using a constant value
|
|
190
|
+
sharpe_ratios = sq.sharpe(data, assets, freerate_value=0.02)
|
|
191
|
+
|
|
192
|
+
# Using a column in your data
|
|
193
|
+
sharpe_ratios = sq.sharpe(data, assets, freerate="TREASURY_YIELD")
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### Custom Confidence Levels
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
# Calculate VaR with 99% confidence
|
|
200
|
+
var_values = sq.var(data, assets, confidence=0.99)
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
## Documentation
|
|
204
|
+
|
|
205
|
+
For full documentation, visit [https://squarequant.readthedocs.io](https://squarequant.readthedocs.io)
|
|
206
|
+
|
|
207
|
+
## Contributing
|
|
208
|
+
|
|
209
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
210
|
+
|
|
211
|
+
## License
|
|
212
|
+
|
|
213
|
+
MIT
|
|
214
|
+
|
|
215
|
+
## Author
|
|
216
|
+
|
|
217
|
+
Gabriel Bosch
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
squarequant/__init__.py,sha256=-27Q7D4mF_zMUIuIRC8_CFZUNmKqoPEbTdlk8uV7rxg,1119
|
|
2
|
+
squarequant/api.py,sha256=qCdZwsQRzT-RqegX2TU4N6HVfJZ0pW5U81dXQhqZdWg,18864
|
|
3
|
+
squarequant/constants.py,sha256=PDMajTd__maR4VV4zpkSHPzIO3-nqp_ksSGt9q2qUJE,1111
|
|
4
|
+
squarequant/core/__init__.py,sha256=G4Li6ujdFf0aPPkLc5avfPJwf25fagna7Q33b7kQ6xI,159
|
|
5
|
+
squarequant/core/base.py,sha256=4uul9wqhWtsAwwbxP-JgVv4RBYym3C29xPWO9cmVlME,5898
|
|
6
|
+
squarequant/core/data.py,sha256=fFrd5AuxLuIz-VCgRshdaEE6mF6wpEOaWueQ3tP7pWU,3817
|
|
7
|
+
squarequant/core/metrics.py,sha256=URO6EfqDoFgM8aa58IAn5iMZKw0fW2udRgW_CZ4waXM,59023
|
|
8
|
+
squarequant/plot/__init__.py,sha256=uyUyAmsA01Pp3Bhj_fhb30mBa4BAVGSYvbg5noNiU9M,255
|
|
9
|
+
squarequant/plot/plot.py,sha256=6_ahWvat-8NcVmageTI5By9wkorvTSofKH4eDq7TO2k,35879
|
|
10
|
+
squarequant/utils/__init__.py,sha256=omrBiivLaFGhjxaPIWYAbpHsVusqa-QX116nAfmfkbg,173
|
|
11
|
+
squarequant/utils/helpers.py,sha256=63IWoKgAKVlYUiGn6XisOxkq_RjxEltCY_HI-FyY9DQ,2450
|
|
12
|
+
squarequant-0.1.0.dist-info/LICENSE,sha256=S23qLSIZQYabXVhEHp9-9JPMVVI3zucYrSwZsIxudn4,1089
|
|
13
|
+
squarequant-0.1.0.dist-info/METADATA,sha256=6ujhXjkaZRKtl48fYJxPB-z9Cxo-0hDz28_5--16-oc,5742
|
|
14
|
+
squarequant-0.1.0.dist-info/WHEEL,sha256=52BFRY2Up02UkjOa29eZOS2VxUrpPORXg1pkohGGUS8,91
|
|
15
|
+
squarequant-0.1.0.dist-info/top_level.txt,sha256=di0xxA-ZWI-TpfQcA6CxZmIy-EyZI23N2DD0w9z-_hQ,12
|
|
16
|
+
squarequant-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
squarequant
|