Skip to main content

A Python library for Value at Risk (VaR) calculations

Project description

VaR Calculation Library

Overview

This Python library provides functions to calculate the Value at Risk (VaR) and Conditional Value at Risk (cVaR) for financial portfolios, including stock and forex portfolios. These risk measures help in understanding potential losses under given confidence levels. It also allows you to conveniently download price data from Yahoo Finance and perform portfolio optimization using multiple strategies.

Features

  • Download stock price data.
  • Calculate VaR and cVaR for a stock portfolio.
  • Calculate VaR and cVaR for a forex portfolio.
  • Supports both long and short positions.
  • Outputs results in both percentage and cash value.
  • Rebalance a stock portfolio.
  • Portfolio optimization for multiple strategies.

Installation

Ensure you have the required dependencies installed:

pip install scipy
pip install numpy 
pip install pandas
pip install yfinance
pip install matplotlib

Functions

get_data(stocks, start_date, end_date, type)

Parameters

  • stocks (list): List of stock tickers to download.
  • start_date (str): Start date in the format YYYY-MM-DD.
  • end_date (str): End date in the format YYYY-MM-DD.
  • type (str): Type of price to retrieve (e.g., "Adj Close", "Close").

Returns

  • pd.DataFrame: A DataFrame containing the selected price type for the specified stocks.

Note: If you prefer to directly download the data from yfinance it is encouraged a format like this:

stocks = ["AAPL", "TSLA", "AMD", "LMT", "JPM"]
data=yf.download(stocks, start="2020-01-01", end="2023-01-01")['Adj Close'][stocks]

Also if you get the data from an excel or csv file create the list stocks or currencieswith the name of the columns in your file for correct functioning.

var_stocks(data, n_stocks, conf, long, stocks)

Calculates the VaR and cVaR for a stock portfolio.

Parameters:

  • data (pd.DataFrame): DataFrame containing stock prices.
  • stocks (list): List of stock tickers.
  • n_stocks (list): Number of stocks per ticker.
  • conf (float): Confidence level (e.g., 95 for 95%).
  • long (bool): True for long position, False for short position.

Returns:

A DataFrame with the following columns:

  • Métrica: "VaR" and "cVaR".
  • Porcentaje: The percentage value of risk.
  • Cash: The risk in monetary terms.

var_forex(data, positions, conf, long, currencies)

Calculates the VaR and cVaR for a forex portfolio.

Parameters:

  • data (pd.DataFrame): DataFrame containing forex currency pair prices.
  • currencies (list): List of currency pairs.
  • positions (list): Number of units per currency pair.
  • conf (float): Confidence level (e.g., 95 for 95%).
  • long (bool): True for long position, False for short position.

Returns:

A DataFrame with the following columns:

  • Métrica: "VaR" and "cVaR".
  • Porcentual: The percentage value of risk.
  • Cash: The risk in monetary terms.

rebalance_stocks(w_original, target_weights, data, stocks, portfolio_value)

Calculates the number of shres to buy/sell to rebalance a stock portfolio..

Parameters:

  • w_original: list of floats representing the original weights of each asset in the portfolio.
  • target_weights: list of floats representing the target weights of each asset in the portfolio.
  • data: pd.DataFrame with historical stock prices, where columns represent different stocks.
  • stocks: list of stock tickers (column names in the data DataFrame).
  • portfolio_value: float representing the total value of the portfolio.

Returns:

  • A pd.DataFrame showing the original weights, target weights, and the number of shares to buy or sell for each asset to rebalance the portfolio.

Usage Example

import numpy as np
import pandas as pd
import yfinance as yf
import vartools as vt

get_data

stocks = ["AAPL", "TSLA", "AMD", "LMT", "JPM"]
start_date = "2020-01-01"
end_date = "2023-01-01"
type = 'Adj Close' # 'Close', select the type of price you want to download

data = vt.get_data(stocks, start_date, end_date, type)

var_stocks

stocks = ["AAPL", "TSLA", "AMD", "LMT", "JPM"]
start_date = "2020-01-01"
end_date = "2023-01-01"
type = 'Adj Close' # 'Close', select the type of price you want to download

data = vt.get_data(stocks, start_date, end_date, type)
n_stocks =[2193, 1211, 3221, 761, 1231]
conf = 95
long = True

var_df = vt.var_stocks(data, n_stocks, conf, long, stocks)

var_forex

currencies = ['CHFMXN=X', 'MXN=X']
start_date = "2020-01-01"
end_date = "2024-12-02"
type = 'Adj Close'

data = vt.get_data(stocks, start_date, end_date, type)
positions = [7100000, 5300000] # How much you have in each currency. Must match the order in currencies.
conf = 99 # Nivel de confianza
long = True

var_forex_df = var_forex(data, positions, conf, long, currencies)

rebalance_stocks

stocks = ["AAPL", "TSLA", "AMD", "LMT", "JPM"]
start_date = "2020-01-01"
end_date = "2023-01-01"
type = 'Adj Close' # 'Close', select the type of price you want to download

data = vt.get_data(stocks, start_date, end_date, type)

rt = data.pct_change().dropna()
stock_value = n_stocks * data.iloc[-1]
portfolio_value = stock_value.sum()
w_original = stock_value / portfolio_value
w_opt = [0.33, 0.15, 0.06, 0.46, 0.00]

rebalance_df = vt.rebalance_stocks(w_original, w_opt, data, stocks, portfolio_value)

License

This project is licensed under the GPL-3.0 license.

Author

Luis Fernando Márquez Bañuelos

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

vartools-0.0.3.tar.gz (15.9 kB view details)

Uploaded Source

Built Distribution

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

vartools-0.0.3-py3-none-any.whl (16.5 kB view details)

Uploaded Python 3

File details

Details for the file vartools-0.0.3.tar.gz.

File metadata

  • Download URL: vartools-0.0.3.tar.gz
  • Upload date:
  • Size: 15.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for vartools-0.0.3.tar.gz
Algorithm Hash digest
SHA256 70ba16fd17831363e966497bcd7626c1b46894b80bc57bde48525effc8528983
MD5 ecf6c03e45c1234a97f1f468faa5ba81
BLAKE2b-256 638b6ee859beb41172e2a7d0b21f157c4f19f4411d9001585ff355f573659de0

See more details on using hashes here.

File details

Details for the file vartools-0.0.3-py3-none-any.whl.

File metadata

  • Download URL: vartools-0.0.3-py3-none-any.whl
  • Upload date:
  • Size: 16.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for vartools-0.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 0b858681ee79ddf335178857e652e9c0505f400975a51d6b670f8fac769dac6d
MD5 0215415b06522ec2a67a9c40b16d65c7
BLAKE2b-256 7a77d15ea1cbbe69eb80958f2a1c9cc4f3f93a071c1ec7901edba8a8364d3fc0

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