squarequant 0.1.0__tar.gz → 0.1.1__tar.gz
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-0.1.1/PKG-INFO +221 -0
- squarequant-0.1.1/README.md +162 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/setup.py +12 -5
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant/__init__.py +1 -1
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant/api.py +51 -36
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant/constants.py +1 -1
- squarequant-0.1.1/squarequant/core/__init__.py +6 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant/core/metrics.py +329 -334
- squarequant-0.1.1/squarequant.egg-info/PKG-INFO +221 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant.egg-info/requires.txt +7 -0
- squarequant-0.1.0/PKG-INFO +0 -217
- squarequant-0.1.0/README.md +0 -167
- squarequant-0.1.0/squarequant/core/__init__.py +0 -6
- squarequant-0.1.0/squarequant.egg-info/PKG-INFO +0 -217
- {squarequant-0.1.0 → squarequant-0.1.1}/LICENSE +0 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/setup.cfg +0 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant/core/base.py +0 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant/core/data.py +0 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant/plot/__init__.py +0 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant/plot/plot.py +0 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant/utils/__init__.py +0 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant/utils/helpers.py +0 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant.egg-info/SOURCES.txt +0 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant.egg-info/dependency_links.txt +0 -0
- {squarequant-0.1.0 → squarequant-0.1.1}/squarequant.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: squarequant
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: A Python package for financial risk metrics and stock data analysis
|
|
5
|
+
Home-page: https://github.com/SquareQuant/squarequant-package
|
|
6
|
+
Author: Gabriel Bosch
|
|
7
|
+
Author-email: contact@squarequant.org
|
|
8
|
+
Project-URL: Documentation, https://www.squarequant.org
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/SquareQuant/squarequant-package/issues
|
|
10
|
+
Keywords: finance,risk,portfolio,investment,stocks,analysis,visualization,drawdown,var,cvar,entropic,ulcer index
|
|
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: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
21
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
22
|
+
Classifier: Intended Audience :: Science/Research
|
|
23
|
+
Classifier: Development Status :: 4 - Beta
|
|
24
|
+
Requires-Python: >=3.7
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: pandas>=1.0.0
|
|
28
|
+
Requires-Dist: numpy>=1.18.0
|
|
29
|
+
Requires-Dist: yfinance>=0.1.63
|
|
30
|
+
Requires-Dist: scipy>=1.5.0
|
|
31
|
+
Requires-Dist: matplotlib>=3.3.0
|
|
32
|
+
Requires-Dist: statsmodels>=0.12.0
|
|
33
|
+
Provides-Extra: optimization
|
|
34
|
+
Requires-Dist: cvxpy>=1.0.0; extra == "optimization"
|
|
35
|
+
Provides-Extra: advanced
|
|
36
|
+
Requires-Dist: scikit-learn>=1.0.0; extra == "advanced"
|
|
37
|
+
Provides-Extra: dev
|
|
38
|
+
Requires-Dist: pytest>=6.0.0; extra == "dev"
|
|
39
|
+
Requires-Dist: black>=21.5b2; extra == "dev"
|
|
40
|
+
Requires-Dist: flake8>=3.9.0; extra == "dev"
|
|
41
|
+
Requires-Dist: sphinx>=4.0.0; extra == "dev"
|
|
42
|
+
Requires-Dist: sphinx-rtd-theme>=0.5.0; extra == "dev"
|
|
43
|
+
Requires-Dist: sphinx-autodoc-typehints>=1.22.0; extra == "dev"
|
|
44
|
+
Requires-Dist: myst-parser>=1.0.0; extra == "dev"
|
|
45
|
+
Requires-Dist: pytest-cov>=2.12.0; extra == "dev"
|
|
46
|
+
Dynamic: author
|
|
47
|
+
Dynamic: author-email
|
|
48
|
+
Dynamic: classifier
|
|
49
|
+
Dynamic: description
|
|
50
|
+
Dynamic: description-content-type
|
|
51
|
+
Dynamic: home-page
|
|
52
|
+
Dynamic: keywords
|
|
53
|
+
Dynamic: license-file
|
|
54
|
+
Dynamic: project-url
|
|
55
|
+
Dynamic: provides-extra
|
|
56
|
+
Dynamic: requires-dist
|
|
57
|
+
Dynamic: requires-python
|
|
58
|
+
Dynamic: summary
|
|
59
|
+
|
|
60
|
+
# SquareQuant
|
|
61
|
+
|
|
62
|
+
SquareQuant is a comprehensive Python package for financial risk metrics and stock data analysis. It provides a suite of tools for quantitative finance, including risk metrics calculation, data retrieval, and visualization.
|
|
63
|
+
|
|
64
|
+
## Features
|
|
65
|
+
|
|
66
|
+
- **Financial Data Access**: Easy-to-use interface for downloading historical price data
|
|
67
|
+
- **Extensive Risk Metrics**: Comprehensive set of traditional and advanced risk measures
|
|
68
|
+
- **Performance Analysis**: Tools for evaluating investment performance
|
|
69
|
+
- **Visualization**: Built-in plotting functions for visual analysis
|
|
70
|
+
- **Flexible API**: Consistent function-based and object-oriented interfaces
|
|
71
|
+
|
|
72
|
+
## Installation
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pip install squarequant
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Quick Start
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
import squarequant as sq
|
|
82
|
+
import matplotlib.pyplot as plt
|
|
83
|
+
|
|
84
|
+
# Configure data download
|
|
85
|
+
config = sq.DownloadConfig(
|
|
86
|
+
start_date="2020-01-01",
|
|
87
|
+
end_date="2023-12-31",
|
|
88
|
+
interval='1d',
|
|
89
|
+
columns=['Close']
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
# Download data
|
|
93
|
+
data = sq.download_tickers(['AAPL', 'MSFT', 'GOOGL'], config)
|
|
94
|
+
|
|
95
|
+
# Calculate volatility
|
|
96
|
+
vol = sq.vol(data=data, assets=['AAPL', 'MSFT', 'GOOGL'], window=21)
|
|
97
|
+
|
|
98
|
+
# Calculate Sharpe ratio
|
|
99
|
+
sharpe = sq.sharpe(data=data, assets=['AAPL', 'MSFT', 'GOOGL'], window=252)
|
|
100
|
+
|
|
101
|
+
# Visualize results
|
|
102
|
+
plt.figure(figsize=(12, 6))
|
|
103
|
+
plt.plot(vol)
|
|
104
|
+
plt.title('21-Day Rolling Volatility')
|
|
105
|
+
plt.legend(vol.columns)
|
|
106
|
+
plt.show()
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Available Risk Metrics
|
|
110
|
+
|
|
111
|
+
SquareQuant provides a comprehensive set of risk metrics, including:
|
|
112
|
+
|
|
113
|
+
| Metric | Function | Description |
|
|
114
|
+
|--------|----------|-------------|
|
|
115
|
+
| Sharpe Ratio | `sq.sharpe()` | Risk-adjusted return using standard deviation |
|
|
116
|
+
| Sortino Ratio | `sq.sortino()` | Risk-adjusted return using downside deviation |
|
|
117
|
+
| Volatility | `sq.vol()` | Standard deviation of returns |
|
|
118
|
+
| Maximum Drawdown | `sq.mdd()` | Largest peak-to-trough decline |
|
|
119
|
+
| Value at Risk | `sq.var()` | Maximum expected loss at given confidence level |
|
|
120
|
+
| Conditional Value at Risk | `sq.cvar()` | Expected loss beyond the VaR threshold |
|
|
121
|
+
| Semi-Deviation | `sq.semidev()` | Downside volatility below target return |
|
|
122
|
+
| Average Drawdown | `sq.avgdd()` | Mean of all drawdowns in a period |
|
|
123
|
+
| Ulcer Index | `sq.ulcer()` | Square root of mean squared drawdown percentage |
|
|
124
|
+
| Mean Absolute Deviation | `sq.mad()` | Average absolute deviation from mean |
|
|
125
|
+
| Entropic Risk Measure | `sq.erm()` | Risk measure based on information theory |
|
|
126
|
+
| Entropic Value at Risk | `sq.evar()` | VAR using entropy concepts |
|
|
127
|
+
| Conditional Drawdown at Risk | `sq.cdar()` | Expected drawdown beyond threshold |
|
|
128
|
+
| Entropic Drawdown at Risk | `sq.edar()` | Drawdown risk using entropy concepts |
|
|
129
|
+
|
|
130
|
+
## Advanced Usage Examples
|
|
131
|
+
|
|
132
|
+
### Analyzing Multiple Risk Metrics
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
import squarequant as sq
|
|
136
|
+
import matplotlib.pyplot as plt
|
|
137
|
+
|
|
138
|
+
# Download data
|
|
139
|
+
config = sq.DownloadConfig(
|
|
140
|
+
start_date="2018-01-01",
|
|
141
|
+
end_date="2023-12-31",
|
|
142
|
+
interval='1d'
|
|
143
|
+
)
|
|
144
|
+
data = sq.download_tickers(['SPY', 'QQQ'], config)
|
|
145
|
+
|
|
146
|
+
# Calculate multiple risk metrics
|
|
147
|
+
vol = sq.vol(data=data, assets=['SPY', 'QQQ'], window=21)
|
|
148
|
+
mad = sq.mad(data=data, assets=['SPY', 'QQQ'], window=252)
|
|
149
|
+
mdd = sq.mdd(data=data, assets=['SPY', 'QQQ'], window=252)
|
|
150
|
+
ulcer = sq.ulcer(data=data, assets=['SPY', 'QQQ'], window=252)
|
|
151
|
+
|
|
152
|
+
# Visualize comparison
|
|
153
|
+
sq.plot_risk_comparison(
|
|
154
|
+
metrics=[vol, mdd, ulcer],
|
|
155
|
+
labels=['Volatility', 'Max Drawdown', 'Ulcer Index'],
|
|
156
|
+
asset='SPY'
|
|
157
|
+
)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Portfolio Risk Analysis
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
import squarequant as sq
|
|
164
|
+
import pandas as pd
|
|
165
|
+
|
|
166
|
+
# Example portfolio weights
|
|
167
|
+
weights = pd.Series({'AAPL': 0.3, 'MSFT': 0.3, 'AMZN': 0.2, 'GOOGL': 0.2})
|
|
168
|
+
|
|
169
|
+
# Download data
|
|
170
|
+
config = sq.DownloadConfig(start_date="2020-01-01", end_date="2023-12-31")
|
|
171
|
+
data = sq.download_tickers(weights.index.tolist(), config)
|
|
172
|
+
|
|
173
|
+
# Calculate portfolio risk measures
|
|
174
|
+
portfolio_var = sq.var(
|
|
175
|
+
data=data,
|
|
176
|
+
assets=weights.index.tolist(),
|
|
177
|
+
confidence=0.95,
|
|
178
|
+
window=252,
|
|
179
|
+
holding_period=10
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
# Visualize weight allocation
|
|
183
|
+
sq.plot_weight_allocation(weights)
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### Using Advanced Risk Measures
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
import squarequant as sq
|
|
190
|
+
|
|
191
|
+
# Download data
|
|
192
|
+
config = sq.DownloadConfig(start_date="2018-01-01", end_date="2023-12-31")
|
|
193
|
+
data = sq.download_tickers(['SPY'], config)
|
|
194
|
+
|
|
195
|
+
# Calculate Entropic Risk Measure with different risk aversion parameters
|
|
196
|
+
erm1 = sq.erm(data=data, assets=['SPY'], z=0.5, confidence=0.95)
|
|
197
|
+
erm2 = sq.erm(data=data, assets=['SPY'], z=1.0, confidence=0.95)
|
|
198
|
+
erm3 = sq.erm(data=data, assets=['SPY'], z=2.0, confidence=0.95)
|
|
199
|
+
|
|
200
|
+
# Compare with traditional VaR and CVaR
|
|
201
|
+
var = sq.var(data=data, assets=['SPY'], confidence=0.95)
|
|
202
|
+
cvar = sq.cvar(data=data, assets=['SPY'], confidence=0.95)
|
|
203
|
+
|
|
204
|
+
print(f"Latest ERM (z=0.5): {erm1.iloc[-1, 0]:.4f}")
|
|
205
|
+
print(f"Latest ERM (z=1.0): {erm2.iloc[-1, 0]:.4f}")
|
|
206
|
+
print(f"Latest ERM (z=2.0): {erm3.iloc[-1, 0]:.4f}")
|
|
207
|
+
print(f"Latest VaR (95%): {var.iloc[-1, 0]:.4f}")
|
|
208
|
+
print(f"Latest CVaR (95%): {cvar.iloc[-1, 0]:.4f}")
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## Documentation
|
|
212
|
+
|
|
213
|
+
For detailed documentation on each function and class, please see the [official documentation](https://www.squarequant.org).
|
|
214
|
+
|
|
215
|
+
## License
|
|
216
|
+
|
|
217
|
+
MIT License
|
|
218
|
+
|
|
219
|
+
## Credits
|
|
220
|
+
|
|
221
|
+
SquareQuant was developed to provide financial analysts, quantitative researchers, and portfolio managers with a comprehensive toolkit for risk assessment and performance analysis.
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# SquareQuant
|
|
2
|
+
|
|
3
|
+
SquareQuant is a comprehensive Python package for financial risk metrics and stock data analysis. It provides a suite of tools for quantitative finance, including risk metrics calculation, data retrieval, and visualization.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Financial Data Access**: Easy-to-use interface for downloading historical price data
|
|
8
|
+
- **Extensive Risk Metrics**: Comprehensive set of traditional and advanced risk measures
|
|
9
|
+
- **Performance Analysis**: Tools for evaluating investment performance
|
|
10
|
+
- **Visualization**: Built-in plotting functions for visual analysis
|
|
11
|
+
- **Flexible API**: Consistent function-based and object-oriented interfaces
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install squarequant
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick Start
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
import squarequant as sq
|
|
23
|
+
import matplotlib.pyplot as plt
|
|
24
|
+
|
|
25
|
+
# Configure data download
|
|
26
|
+
config = sq.DownloadConfig(
|
|
27
|
+
start_date="2020-01-01",
|
|
28
|
+
end_date="2023-12-31",
|
|
29
|
+
interval='1d',
|
|
30
|
+
columns=['Close']
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
# Download data
|
|
34
|
+
data = sq.download_tickers(['AAPL', 'MSFT', 'GOOGL'], config)
|
|
35
|
+
|
|
36
|
+
# Calculate volatility
|
|
37
|
+
vol = sq.vol(data=data, assets=['AAPL', 'MSFT', 'GOOGL'], window=21)
|
|
38
|
+
|
|
39
|
+
# Calculate Sharpe ratio
|
|
40
|
+
sharpe = sq.sharpe(data=data, assets=['AAPL', 'MSFT', 'GOOGL'], window=252)
|
|
41
|
+
|
|
42
|
+
# Visualize results
|
|
43
|
+
plt.figure(figsize=(12, 6))
|
|
44
|
+
plt.plot(vol)
|
|
45
|
+
plt.title('21-Day Rolling Volatility')
|
|
46
|
+
plt.legend(vol.columns)
|
|
47
|
+
plt.show()
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Available Risk Metrics
|
|
51
|
+
|
|
52
|
+
SquareQuant provides a comprehensive set of risk metrics, including:
|
|
53
|
+
|
|
54
|
+
| Metric | Function | Description |
|
|
55
|
+
|--------|----------|-------------|
|
|
56
|
+
| Sharpe Ratio | `sq.sharpe()` | Risk-adjusted return using standard deviation |
|
|
57
|
+
| Sortino Ratio | `sq.sortino()` | Risk-adjusted return using downside deviation |
|
|
58
|
+
| Volatility | `sq.vol()` | Standard deviation of returns |
|
|
59
|
+
| Maximum Drawdown | `sq.mdd()` | Largest peak-to-trough decline |
|
|
60
|
+
| Value at Risk | `sq.var()` | Maximum expected loss at given confidence level |
|
|
61
|
+
| Conditional Value at Risk | `sq.cvar()` | Expected loss beyond the VaR threshold |
|
|
62
|
+
| Semi-Deviation | `sq.semidev()` | Downside volatility below target return |
|
|
63
|
+
| Average Drawdown | `sq.avgdd()` | Mean of all drawdowns in a period |
|
|
64
|
+
| Ulcer Index | `sq.ulcer()` | Square root of mean squared drawdown percentage |
|
|
65
|
+
| Mean Absolute Deviation | `sq.mad()` | Average absolute deviation from mean |
|
|
66
|
+
| Entropic Risk Measure | `sq.erm()` | Risk measure based on information theory |
|
|
67
|
+
| Entropic Value at Risk | `sq.evar()` | VAR using entropy concepts |
|
|
68
|
+
| Conditional Drawdown at Risk | `sq.cdar()` | Expected drawdown beyond threshold |
|
|
69
|
+
| Entropic Drawdown at Risk | `sq.edar()` | Drawdown risk using entropy concepts |
|
|
70
|
+
|
|
71
|
+
## Advanced Usage Examples
|
|
72
|
+
|
|
73
|
+
### Analyzing Multiple Risk Metrics
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
import squarequant as sq
|
|
77
|
+
import matplotlib.pyplot as plt
|
|
78
|
+
|
|
79
|
+
# Download data
|
|
80
|
+
config = sq.DownloadConfig(
|
|
81
|
+
start_date="2018-01-01",
|
|
82
|
+
end_date="2023-12-31",
|
|
83
|
+
interval='1d'
|
|
84
|
+
)
|
|
85
|
+
data = sq.download_tickers(['SPY', 'QQQ'], config)
|
|
86
|
+
|
|
87
|
+
# Calculate multiple risk metrics
|
|
88
|
+
vol = sq.vol(data=data, assets=['SPY', 'QQQ'], window=21)
|
|
89
|
+
mad = sq.mad(data=data, assets=['SPY', 'QQQ'], window=252)
|
|
90
|
+
mdd = sq.mdd(data=data, assets=['SPY', 'QQQ'], window=252)
|
|
91
|
+
ulcer = sq.ulcer(data=data, assets=['SPY', 'QQQ'], window=252)
|
|
92
|
+
|
|
93
|
+
# Visualize comparison
|
|
94
|
+
sq.plot_risk_comparison(
|
|
95
|
+
metrics=[vol, mdd, ulcer],
|
|
96
|
+
labels=['Volatility', 'Max Drawdown', 'Ulcer Index'],
|
|
97
|
+
asset='SPY'
|
|
98
|
+
)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Portfolio Risk Analysis
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
import squarequant as sq
|
|
105
|
+
import pandas as pd
|
|
106
|
+
|
|
107
|
+
# Example portfolio weights
|
|
108
|
+
weights = pd.Series({'AAPL': 0.3, 'MSFT': 0.3, 'AMZN': 0.2, 'GOOGL': 0.2})
|
|
109
|
+
|
|
110
|
+
# Download data
|
|
111
|
+
config = sq.DownloadConfig(start_date="2020-01-01", end_date="2023-12-31")
|
|
112
|
+
data = sq.download_tickers(weights.index.tolist(), config)
|
|
113
|
+
|
|
114
|
+
# Calculate portfolio risk measures
|
|
115
|
+
portfolio_var = sq.var(
|
|
116
|
+
data=data,
|
|
117
|
+
assets=weights.index.tolist(),
|
|
118
|
+
confidence=0.95,
|
|
119
|
+
window=252,
|
|
120
|
+
holding_period=10
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# Visualize weight allocation
|
|
124
|
+
sq.plot_weight_allocation(weights)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### Using Advanced Risk Measures
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
import squarequant as sq
|
|
131
|
+
|
|
132
|
+
# Download data
|
|
133
|
+
config = sq.DownloadConfig(start_date="2018-01-01", end_date="2023-12-31")
|
|
134
|
+
data = sq.download_tickers(['SPY'], config)
|
|
135
|
+
|
|
136
|
+
# Calculate Entropic Risk Measure with different risk aversion parameters
|
|
137
|
+
erm1 = sq.erm(data=data, assets=['SPY'], z=0.5, confidence=0.95)
|
|
138
|
+
erm2 = sq.erm(data=data, assets=['SPY'], z=1.0, confidence=0.95)
|
|
139
|
+
erm3 = sq.erm(data=data, assets=['SPY'], z=2.0, confidence=0.95)
|
|
140
|
+
|
|
141
|
+
# Compare with traditional VaR and CVaR
|
|
142
|
+
var = sq.var(data=data, assets=['SPY'], confidence=0.95)
|
|
143
|
+
cvar = sq.cvar(data=data, assets=['SPY'], confidence=0.95)
|
|
144
|
+
|
|
145
|
+
print(f"Latest ERM (z=0.5): {erm1.iloc[-1, 0]:.4f}")
|
|
146
|
+
print(f"Latest ERM (z=1.0): {erm2.iloc[-1, 0]:.4f}")
|
|
147
|
+
print(f"Latest ERM (z=2.0): {erm3.iloc[-1, 0]:.4f}")
|
|
148
|
+
print(f"Latest VaR (95%): {var.iloc[-1, 0]:.4f}")
|
|
149
|
+
print(f"Latest CVaR (95%): {cvar.iloc[-1, 0]:.4f}")
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## Documentation
|
|
153
|
+
|
|
154
|
+
For detailed documentation on each function and class, please see the [official documentation](https://www.squarequant.org).
|
|
155
|
+
|
|
156
|
+
## License
|
|
157
|
+
|
|
158
|
+
MIT License
|
|
159
|
+
|
|
160
|
+
## Credits
|
|
161
|
+
|
|
162
|
+
SquareQuant was developed to provide financial analysts, quantitative researchers, and portfolio managers with a comprehensive toolkit for risk assessment and performance analysis.
|
|
@@ -5,15 +5,15 @@ with open("README.md", "r", encoding="utf-8") as fh:
|
|
|
5
5
|
|
|
6
6
|
setup(
|
|
7
7
|
name="squarequant",
|
|
8
|
-
version="0.1.
|
|
8
|
+
version="0.1.1",
|
|
9
9
|
author="Gabriel Bosch",
|
|
10
|
-
author_email="contact@
|
|
11
|
-
description="A Python package for
|
|
10
|
+
author_email="contact@squarequant.org",
|
|
11
|
+
description="A Python package for financial risk metrics and stock data analysis",
|
|
12
12
|
long_description=long_description,
|
|
13
13
|
long_description_content_type="text/markdown",
|
|
14
14
|
url="https://github.com/SquareQuant/squarequant-package",
|
|
15
15
|
project_urls={
|
|
16
|
-
"Documentation": "https://squarequant.
|
|
16
|
+
"Documentation": "https://www.squarequant.org",
|
|
17
17
|
"Bug Tracker": "https://github.com/SquareQuant/squarequant-package/issues",
|
|
18
18
|
},
|
|
19
19
|
packages=find_packages(),
|
|
@@ -22,6 +22,8 @@ setup(
|
|
|
22
22
|
"Programming Language :: Python :: 3.7",
|
|
23
23
|
"Programming Language :: Python :: 3.8",
|
|
24
24
|
"Programming Language :: Python :: 3.9",
|
|
25
|
+
"Programming Language :: Python :: 3.10",
|
|
26
|
+
"Programming Language :: Python :: 3.11",
|
|
25
27
|
"License :: OSI Approved :: MIT License",
|
|
26
28
|
"Operating System :: OS Independent",
|
|
27
29
|
"Topic :: Office/Business :: Financial :: Investment",
|
|
@@ -37,16 +39,21 @@ setup(
|
|
|
37
39
|
"yfinance>=0.1.63",
|
|
38
40
|
"scipy>=1.5.0",
|
|
39
41
|
"matplotlib>=3.3.0",
|
|
42
|
+
"statsmodels>=0.12.0",
|
|
40
43
|
],
|
|
41
44
|
extras_require={
|
|
42
45
|
"optimization": ["cvxpy>=1.0.0"],
|
|
46
|
+
"advanced": ["scikit-learn>=1.0.0"],
|
|
43
47
|
"dev": [
|
|
44
48
|
"pytest>=6.0.0",
|
|
45
49
|
"black>=21.5b2",
|
|
46
50
|
"flake8>=3.9.0",
|
|
47
51
|
"sphinx>=4.0.0",
|
|
48
52
|
"sphinx-rtd-theme>=0.5.0",
|
|
53
|
+
"sphinx-autodoc-typehints>=1.22.0",
|
|
54
|
+
"myst-parser>=1.0.0",
|
|
55
|
+
"pytest-cov>=2.12.0",
|
|
49
56
|
],
|
|
50
57
|
},
|
|
51
|
-
keywords="finance, risk, portfolio, investment, stocks, analysis, visualization",
|
|
58
|
+
keywords="finance, risk, portfolio, investment, stocks, analysis, visualization, drawdown, var, cvar, entropic, ulcer index",
|
|
52
59
|
)
|
|
@@ -244,7 +244,9 @@ def cvar(data: pd.DataFrame,
|
|
|
244
244
|
window: int = DEFAULT_CVAR_WINDOW,
|
|
245
245
|
start: Optional[str] = None,
|
|
246
246
|
end: Optional[str] = None,
|
|
247
|
-
method: str = 'historical'
|
|
247
|
+
method: str = 'historical',
|
|
248
|
+
holding_period: int = DEFAULT_VAR_HOLDING_PERIOD, # Add parameter
|
|
249
|
+
scaling_method: str = 'sqrt_time') -> pd.DataFrame: # Add parameter
|
|
248
250
|
"""
|
|
249
251
|
Calculate rolling Conditional Value at Risk (CVaR) for specified assets
|
|
250
252
|
|
|
@@ -256,6 +258,8 @@ def cvar(data: pd.DataFrame,
|
|
|
256
258
|
start (str, optional): Start date in format 'YYYY-MM-DD'
|
|
257
259
|
end (str, optional): End date in format 'YYYY-MM-DD'
|
|
258
260
|
method (str): Method to calculate CVaR - 'historical', 'parametric', default is 'historical'
|
|
261
|
+
holding_period (int): Holding period in days, default is 10 days
|
|
262
|
+
scaling_method (str): Method to scale 1-day CVaR, default is 'sqrt_time'
|
|
259
263
|
|
|
260
264
|
Returns:
|
|
261
265
|
DataFrame: Rolling CVaR for specified assets
|
|
@@ -267,7 +271,9 @@ def cvar(data: pd.DataFrame,
|
|
|
267
271
|
window=window,
|
|
268
272
|
start=start,
|
|
269
273
|
end=end,
|
|
270
|
-
method=method
|
|
274
|
+
method=method,
|
|
275
|
+
holding_period=holding_period, # Pass parameter
|
|
276
|
+
scaling_method=scaling_method # Pass parameter
|
|
271
277
|
)
|
|
272
278
|
return calculator.calculate()
|
|
273
279
|
|
|
@@ -389,21 +395,31 @@ def mad(data: pd.DataFrame,
|
|
|
389
395
|
def erm(data: pd.DataFrame,
|
|
390
396
|
assets: List[str],
|
|
391
397
|
z: float = 1.0,
|
|
392
|
-
|
|
398
|
+
confidence: float = DEFAULT_CONFIDENCE,
|
|
393
399
|
window: int = DEFAULT_ERM_WINDOW,
|
|
394
400
|
start: Optional[str] = None,
|
|
395
|
-
end: Optional[str] = None
|
|
401
|
+
end: Optional[str] = None,
|
|
402
|
+
method: str = 'historical',
|
|
403
|
+
holding_period: int = 1,
|
|
404
|
+
scaling_method: str = 'sqrt_time',
|
|
405
|
+
decay_factor: float = 0.94) -> pd.DataFrame:
|
|
396
406
|
"""
|
|
397
407
|
Calculate the Entropic Risk Measure (ERM) for specified assets.
|
|
398
408
|
|
|
399
409
|
Parameters:
|
|
400
410
|
data (DataFrame): DataFrame with asset price data
|
|
401
411
|
assets (List[str]): List of asset columns to calculate for
|
|
402
|
-
z (float): Risk aversion parameter, must be greater than zero
|
|
403
|
-
|
|
412
|
+
z (float): Risk aversion parameter, must be greater than zero. Default is 1.0
|
|
413
|
+
confidence (float): Significance level (0-1), default is 0.95 (95%)
|
|
404
414
|
window (int): Rolling window size in trading days, default is 252 (1 year)
|
|
405
415
|
start (str, optional): Start date in format 'YYYY-MM-DD'
|
|
406
416
|
end (str, optional): End date in format 'YYYY-MM-DD'
|
|
417
|
+
method (str, optional): Method to use for calculation: 'historical', 'parametric', or 'weighted'.
|
|
418
|
+
Default is 'historical'
|
|
419
|
+
holding_period (int, optional): Time horizon for risk projection. Default is 1
|
|
420
|
+
scaling_method (str, optional): Method to scale for holding period: 'sqrt_time', 'linear', or 'none'.
|
|
421
|
+
Default is 'sqrt_time'
|
|
422
|
+
decay_factor (float, optional): Decay factor for weighted method (between 0 and 1). Default is 0.94
|
|
407
423
|
|
|
408
424
|
Returns:
|
|
409
425
|
DataFrame: Entropic Risk Measure for specified assets
|
|
@@ -412,43 +428,42 @@ def erm(data: pd.DataFrame,
|
|
|
412
428
|
data=data,
|
|
413
429
|
assets=assets,
|
|
414
430
|
z=z,
|
|
415
|
-
|
|
431
|
+
confidence=confidence,
|
|
416
432
|
window=window,
|
|
417
433
|
start=start,
|
|
418
|
-
end=end
|
|
434
|
+
end=end,
|
|
435
|
+
holding_period=holding_period,
|
|
436
|
+
scaling_method=scaling_method
|
|
419
437
|
)
|
|
420
438
|
return calculator.calculate()
|
|
421
439
|
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
440
|
+
def evar(
|
|
441
|
+
data: pd.DataFrame,
|
|
442
|
+
assets: List[str],
|
|
443
|
+
confidence: float = DEFAULT_CONFIDENCE, # Changed from alpha to confidence
|
|
444
|
+
window: int = DEFAULT_EVAR_WINDOW,
|
|
445
|
+
start: Optional[str] = None,
|
|
446
|
+
end: Optional[str] = None,
|
|
447
|
+
holding_period: int = 1,
|
|
448
|
+
scaling_method: str = 'sqrt_time',
|
|
449
|
+
z_bounds: tuple = (0.1, 10.0), # Added z_bounds parameter
|
|
450
|
+
z_default: float = 1.0 # Changed from initial_z to z_default
|
|
451
|
+
) -> pd.DataFrame:
|
|
434
452
|
"""
|
|
435
|
-
Calculate
|
|
436
|
-
This implementation uses convex optimization via CVXPY when available,
|
|
437
|
-
with fallback to grid search if needed.
|
|
453
|
+
Calculate Entropic Value at Risk for specified assets.
|
|
438
454
|
|
|
439
455
|
Parameters:
|
|
440
456
|
data (DataFrame): DataFrame with asset price data
|
|
441
457
|
assets (List[str]): List of asset columns to calculate for
|
|
442
|
-
|
|
458
|
+
confidence (float): Confidence level (0-1), default is 0.95 (95%)
|
|
443
459
|
window (int): Rolling window size in trading days, default is 252 (1 year)
|
|
444
460
|
start (str, optional): Start date in format 'YYYY-MM-DD'
|
|
445
461
|
end (str, optional): End date in format 'YYYY-MM-DD'
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
fallback_steps (int): Number of steps for fallback grid search
|
|
462
|
+
method (str, optional): Method to use - 'historical', 'parametric', or 'weighted'. Default is 'parametric'
|
|
463
|
+
holding_period (int): Time horizon for risk projection, default is 1
|
|
464
|
+
scaling_method (str): Method to scale 1-day EVaR, default is 'sqrt_time'
|
|
465
|
+
z_bounds (tuple): Bounds for z parameter optimization (lower, upper). Default is (0.1, 10.0)
|
|
466
|
+
z_default (float): Default z value to use if optimization fails. Default is 1.0
|
|
452
467
|
|
|
453
468
|
Returns:
|
|
454
469
|
DataFrame: Entropic Value at Risk for specified assets
|
|
@@ -456,18 +471,18 @@ def evar(data: pd.DataFrame,
|
|
|
456
471
|
calculator = EntropicValueAtRisk(
|
|
457
472
|
data=data,
|
|
458
473
|
assets=assets,
|
|
459
|
-
|
|
474
|
+
confidence=confidence, # Match the parameter name with the class
|
|
460
475
|
window=window,
|
|
461
476
|
start=start,
|
|
462
477
|
end=end,
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
fallback_steps=fallback_steps
|
|
478
|
+
holding_period=holding_period,
|
|
479
|
+
scaling_method=scaling_method,
|
|
480
|
+
z_bounds=z_bounds,
|
|
481
|
+
z_default=z_default
|
|
468
482
|
)
|
|
469
483
|
return calculator.calculate()
|
|
470
484
|
|
|
485
|
+
|
|
471
486
|
def cdar(data: pd.DataFrame,
|
|
472
487
|
assets: List[str],
|
|
473
488
|
confidence: float = DEFAULT_CONFIDENCE,
|