Skip to main content

A Python package for financial risk metrics and stock data analysis

Project description

SquareQuant

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 and data retrieval from multiple sources.

Features

  • Financial Data Access: Multiple data sources including YFinance and Theta Data
  • Extensive Risk Metrics: Comprehensive set of traditional and advanced risk measures
  • Modular Design: Organized into specialized modules (data, var, etc.)
  • Flexible API: Consistent function-based and object-oriented interfaces

Installation

pip install squarequant

Quick Start

import squarequant as sq
import pandas as pd
import matplotlib.pyplot as plt

# Configure data download
config = sq.DownloadConfig(
    start_date="2020-01-01",
    end_date="2023-12-31",
    interval='1d',
    columns=['Close'],
    source="yfinance"  # Or "theta" for Theta Data
)

# Download data
data = sq.download_tickers(['AAPL', 'MSFT', 'GOOGL'], config)
data = pd.DataFrame({
    'AAPL': data['AAPL_Close'],
    'MSFT': data['MSFT_Close']
})

# Calculate volatility
vol = sq.vol(data=data, assets=['AAPL', 'MSFT', 'GOOGL'], use_returns=False, window=21)

# Calculate Sharpe ratio
sharpe = sq.sharpe(data=data, assets=['AAPL', 'MSFT', 'GOOGL'], use_returns=False, window=252)

# Visualize results (using matplotlib directly)
plt.figure(figsize=(12, 6))
plt.plot(vol)
plt.title('21-Day Rolling Volatility')
plt.legend(vol.columns)
plt.show()

Available Risk Metrics

SquareQuant provides a comprehensive set of risk metrics, including:

Metric Function Description
Sharpe Ratio sq.sharpe() Risk-adjusted return using standard deviation
Sortino Ratio sq.sortino() Risk-adjusted return using downside deviation
Volatility sq.vol() Standard deviation of returns
Maximum Drawdown sq.mdd() Largest peak-to-trough decline
Value at Risk sq.var() Maximum expected loss at given confidence level
Conditional Value at Risk sq.cvar() Expected loss beyond the VaR threshold
Semi-Deviation sq.semidev() Downside volatility below target return
Average Drawdown sq.avgdd() Mean of all drawdowns in a period
Ulcer Index sq.ulcer() Square root of mean squared drawdown percentage
Mean Absolute Deviation sq.mad() Average absolute deviation from mean
Entropic Risk Measure sq.erm() Risk measure based on information theory
Entropic Value at Risk sq.evar() VAR using entropy concepts
Conditional Drawdown at Risk sq.cdar() Expected drawdown beyond threshold

Data Sources

SquareQuant now supports multiple data providers:

YFinance

The default data provider for historical price data:

config = sq.DownloadConfig(
    start_date="2020-01-01",
    end_date="2023-12-31",
    source="yfinance"  # Default
)

Theta Data

A new alternative data provider with the same interface:

config = sq.DownloadConfig(
    start_date="2020-01-01",
    end_date="2023-12-31",
    source="theta"
)

Advanced Usage Examples

Analyzing Multiple Risk Metrics

import squarequant as sq
import matplotlib.pyplot as plt

# Download data
config = sq.DownloadConfig(
    start_date="2018-01-01",
    end_date="2023-12-31",
    interval='1d'
)
data = sq.download_tickers(['SPY', 'QQQ'], config)

# Calculate multiple risk metrics
vol = sq.vol(data=data, assets=['SPY', 'QQQ'], use_returns=False, window=21)
mad = sq.mad(data=data, assets=['SPY', 'QQQ'], use_returns=False, window=252)
mdd = sq.mdd(data=data, assets=['SPY', 'QQQ'], use_returns=False, window=252)
ulcer = sq.ulcer(data=data, assets=['SPY', 'QQQ'], use_returns=False, window=252)

# Visualize comparison (using matplotlib directly)
plt.figure(figsize=(12, 8))
plt.subplot(3, 1, 1)
plt.plot(vol['SPY_Vol'])
plt.title('SPY Volatility')

plt.subplot(3, 1, 2)
plt.plot(mdd['SPY_MDD'])
plt.title('SPY Max Drawdown')

plt.subplot(3, 1, 3)
plt.plot(ulcer['SPY_Ulcer'])
plt.title('SPY Ulcer Index')

plt.tight_layout()
plt.show()

Portfolio Risk Analysis

import squarequant as sq
import pandas as pd

# Example portfolio weights
weights = pd.Series({'AAPL': 0.3, 'MSFT': 0.3, 'AMZN': 0.2, 'GOOGL': 0.2})

# Download data
config = sq.DownloadConfig(start_date="2020-01-01", end_date="2023-12-31")
data = sq.download_tickers(weights.index.tolist(), config)

# Calculate portfolio risk measures
portfolio_var = sq.var(
    data=data,
    use_returns = False,
    assets=weights.index.tolist(),
    confidence=0.95,
    window=252,
    holding_period=10
)

# Print results
print(f"Latest Portfolio VaR (95%): {portfolio_var.iloc[-1].values[0]:.4f}")

Using Advanced Risk Measures

import squarequant as sq

# Download data
config = sq.DownloadConfig(start_date="2018-01-01", end_date="2023-12-31")
data = sq.download_tickers(['SPY'], config)

# Calculate Entropic Risk Measure with different risk aversion parameters
erm1 = sq.erm(data=data, use_returns=False, assets=['SPY'], z=0.5, confidence=0.95)
erm2 = sq.erm(data=data, use_returns=False, assets=['SPY'], z=1.0, confidence=0.95)
erm3 = sq.erm(data=data, use_returns=False, assets=['SPY'], z=2.0, confidence=0.95)

# Compare with traditional VaR and CVaR
var = sq.var(data=data, use_returns=False, assets=['SPY'], confidence=0.95)
cvar = sq.cvar(data=data, use_returns=False, assets=['SPY'], confidence=0.95)

print(f"Latest ERM (z=0.5): {erm1.iloc[-1, 0]:.4f}")
print(f"Latest ERM (z=1.0): {erm2.iloc[-1, 0]:.4f}")
print(f"Latest ERM (z=2.0): {erm3.iloc[-1, 0]:.4f}")
print(f"Latest VaR (95%): {var.iloc[-1, 0]:.4f}")
print(f"Latest CVaR (95%): {cvar.iloc[-1, 0]:.4f}")

Library Structure

The package has been reorganized into specialized modules:

  • squarequant.data: Data retrieval functionality (YFinance, Theta Data)
  • squarequant.core: Core risk metrics and calculations
  • squarequant.var: Value at Risk and related risk measures
  • squarequant.monte_carlo: Monte Carlo simulations (alpha version)

Documentation

For detailed documentation on each function and class, please see the official documentation.

License

MIT License

Credits

SquareQuant was developed to provide financial analysts, quantitative researchers, and portfolio managers with a comprehensive toolkit for risk assessment and performance analysis.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

squarequant-0.2.3.tar.gz (36.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

squarequant-0.2.3-py3-none-any.whl (37.5 kB view details)

Uploaded Python 3

File details

Details for the file squarequant-0.2.3.tar.gz.

File metadata

  • Download URL: squarequant-0.2.3.tar.gz
  • Upload date:
  • Size: 36.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for squarequant-0.2.3.tar.gz
Algorithm Hash digest
SHA256 325300d7a6649c7397b83e5011e107acd7b76aa0267ac21ef81d2df95dbdc1be
MD5 0197c9919a5dffb54608fab29a248f2f
BLAKE2b-256 b5a014bbca464b4875cf91d6397e59171666a975cf807e6c5ce03f52a765d3e3

See more details on using hashes here.

File details

Details for the file squarequant-0.2.3-py3-none-any.whl.

File metadata

  • Download URL: squarequant-0.2.3-py3-none-any.whl
  • Upload date:
  • Size: 37.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for squarequant-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 9903a88fc46ca5490b1626dc56d6104a727caacca56a3f2998ee414d41ea19b4
MD5 f33439e229d285a3719b4d58f7589874
BLAKE2b-256 05f0ba5ee49dbe3cd28cc374efee775a1560caa7c2aa2126310d13599de4e8fd

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page