# Market Risk

The risk of loss from movements in prices, rates, spreads, currencies or volatility.

**Rests on:** Linear Regression

*Applied Domains · AI in Finance*


## Why learn this

Understanding market risk is essential because it explains why financial AI systems exist and how they protect capital. Before any AI can forecast losses or read the tone of an earnings call, it must first understand that prices move unpredictably and that these movements can cause significant financial damage. You need this foundation to grasp later topics like backtesting (checking if a strategy works) and sentiment analysis (using AI to read news). Without this concept, you cannot understand how computers are trained to avoid a specific error: assuming future information is available when it wasn't at the time of the decision. This concept unlocks your entire 'AI in Finance' learning path.


## The intuition

Imagine you own a small spice shop. You buy turmeric and cumin in bulk, waiting for the best price to resell. The risk here is not that customers won't buy spices; it is that the wholesale price of spices might jump up before you can sell your stock, or fall down, leaving you with inventory worth less than what you paid for it. This uncertainty—will prices move against you?—is market risk. It arises from movements in prices, interest rates, currency exchange rates, or volatility (which is simply how wildly prices bounce around). In finance, market risk is neutral; it is not about whether an investment is 'good' or 'bad', but about the fact that values change. A trader holding stocks faces this daily: if the general market drops, their holdings lose value. A bank that lent money in US dollars but borrowed funds in Indian Rupees faces currency risk: if the Rupee becomes stronger, it costs more Rupees to repay that dollar debt. Even a global company buying raw materials in one currency and selling finished goods in another faces this risk. AI models enter this space not to predict the future, but to calculate the likely range of these swings, helping humans estimate how much money might be lost in different scenarios.


## An analogy

Think of a ship captain navigating stormy seas. The captain knows waves will rock the vessel but cannot predict every single wave. Instead, the captain measures the 'roughness' of the sea—how high waves typically get and how often they occur—to decide whether to sail or stay in port. Market risk is that sea; prices are the waves, and your investment portfolio is the ship. To manage this, traders use a metric called Value at Risk (VaR). This statistic tells you: 'There is a 95% chance that our biggest loss on any given day will be no more than ₹10 lakh.' However, VaR has a blind spot: it does not tell you how bad the losses are when they *do* exceed that limit. For that, we use Expected shortfall. If the loss exceeds ₹10 lakh, the Expected shortfall calculates the average severity of those rare, severe days—perhaps showing that on the worst 5% of days, the average loss is actually ₹25 lakh. The analogy breaks down here: unlike ocean waves, which follow physical laws, financial markets are driven by human behavior, which can change abruptly and unpredictably. A model trained on calm seas will fail during a tsunami; similarly, risk models built on normal times often underestimate extreme crashes because they rely only on past data that may not repeat.


## Definition

Market risk is the potential for financial loss caused by unfavorable changes in market prices, interest rates, exchange rates, or the volatility (the rate of price fluctuation) of assets.


## How it connects

This concept serves as the baseline for 'AI in Finance'. Later, you will see how it connects to backtesting (evaluating a trading strategy using past data). When backtesting, one must avoid lookahead bias (a mistake where a model accidentally uses future information that wasn't available at the time of the trade, leading to falsely impressive results). You will also explore how market risk relates to earnings call analysis; when company executives use evasive language, market volatility often rises, signaling increased risk. Finally, specialized AI tools like FinBERT and BloombergGPT are designed to process this financial text to quantify those risks.


## The mathematics

Market risk is measured using statistics from past price data. The most common measure is Value at Risk (VaR). Think of it as a threshold: 'We are 95% confident that our losses will not exceed this amount over the next day.' To calculate VaR, you look at the daily changes (returns) of your portfolio over a period (say, the last 250 trading days). You sort those returns from worst to best. The 5th percentile—the point below which the worst 5% of returns fall—is your VaR. If that 5th percentile is a return of -2%, and your portfolio is worth ₹1 crore, then your daily VaR at 95% confidence is ₹2 lakh. Expected shortfall (ES) goes further: instead of just the threshold, it averages the losses in the worst 5% of days. If the worst 5% of returns are -1%, -2%, -3%, -4%, -5%, the average is -3%, so ES is ₹3 lakh. Both measures are about the distribution of losses, not a single prediction. The mathematics involved is arithmetic and probability: you sort numbers, find percentiles, and take averages. No calculus, no algebra—just counting and dividing.

VaR_95 = -percentile(returns, 5)  (the negative of the 5th percentile of daily returns)
ES_95 = -average(returns where return ≤ VaR_95)  (the average of the worst 5% of returns)


## A worked example

```
You have a portfolio worth ₹1 crore. Over the last 5 days, the daily percentage returns were: +1%, -2%, +0.5%, -3%, -1%. We want to calculate the daily VaR at 95% confidence (the 5th percentile) and the Expected Shortfall (the average of the worst 5% of returns).

Step 1: Sort returns from worst to best: -3%, -2%, -1%, +0.5%, +1%   # Sorting is the first step: we need to know how bad the worst days were.
Step 2: The 5th percentile: since we have 5 returns, the 5th percentile is the worst return, -3%.   # With only 5 data points, the worst return is the 5th percentile. In practice, with 250 days, the 5th percentile would be the 13th worst (5% of 250 = 12.5).
Step 3: VaR = 3% of ₹1 crore = ₹3,00,000   # That's the threshold: we are 95% confident that we won't lose more than this in a day, based on past data.
Step 4: Expected Shortfall: average of the worst 5% of returns. Here, the worst 5% is just the -3% day, so ES = -3% = ₹3,00,000.   # With a larger sample, we'd average the worst 5% of days, not just one.

Result: Daily VaR at 95% confidence = ₹3,00,000. Expected Shortfall = ₹3,00,000 (since we only have 5 days, worst 5% is one day).
```


## From scratch, in Python

```python
# We'll calculate VaR and Expected Shortfall from a list of daily returns.
# In Python, a list is a collection of items in order, e.g., [1, -2, 0.5, -3, -1]
# We'll use a loop to go through each return and a function to calculate the percentile.

# Step 1: Define the list of daily returns (as percentages)
returns = [1, -2, 0.5, -3, -1]

# Step 2: Sort the list from worst to best (ascending order)
sorted_returns = sorted(returns)
# After sorting: [-3, -2, -1, 0.5, 1]

# Step 3: Find the index for the 5th percentile.
# With 5 items, the 5th percentile is the worst (index 0).
# Formula: index = max(0, int(0.05 * len(sorted_returns)) - 1)  (but for simplicity, we'll use index 0)
index_5th_percentile = 0  # since 5% of 5 is 0.25, we take the floor, which is 0

# Step 4: VaR is the negative of that return (since we express loss as positive)
var_95 = -sorted_returns[index_5th_percentile]  # -(-3) = 3, meaning 3% loss

# Step 5: Expected Shortfall: average of the worst 5% of returns.
# Here, with only 5 items, the worst 5% is just the first item.
worst_5_percent_returns = sorted_returns[:1]  # slice from start to index 1 (exclusive) => [-3]
# Calculate average: sum of worst_5_percent_returns divided by number of items
es_95 = -sum(worst_5_percent_returns) / len(worst_5_percent_returns)  # -(-3)/1 = 3

# Step 6: Print the results
print("VaR at 95% confidence:", var_95, "%")
print("Expected Shortfall at 95% confidence:", es_95, "%")
```


## What the code does

Let's walk through the code step by step. First, we create a list called 'returns' that holds our daily percentage changes. A list is like a row of boxes, each holding a number, in a specific order. We sort it with 'sorted()'—that rearranges the boxes from smallest (most negative) to largest (most positive). To find the 5th percentile, we pick the first box (index 0) because with 5 data points, the 5th percentile is the worst. (In general, we'd calculate the index as 'int(0.05 * len(returns))' but for small lists, index 0 is fine.) Then we take the negative of that return to express it as a loss—so -3% becomes +3%. That's our VaR. For Expected Shortfall, we take the worst 5% of returns—here, just the first item—and average them. We use 'sum()' to add them up and 'len()' to count them, then divide to get the average. Again, we negate to get a positive loss. The code prints both numbers. Notice we used a slice: 'sorted_returns[:1]' takes the first item. This is a simple example, but in practice with 250 returns, the worst 5% would be 12.5 days, and we'd slice 'sorted_returns[:13]' (rounding up).


## Common misconceptions

**VaR tells you the maximum possible loss** — If my VaR is ₹10 lakh, I can't lose more than that.

VaR is a threshold based on historical data, not a ceiling. In the worst 5% of days, losses can be much larger—VaR gives no information about how bad they can get. In fact: VaR is a confidence threshold: 'We are 95% confident we won't lose more than this.' The actual loss on a bad day could be far worse.

**Risk measures are predictions** — VaR is a forecast of tomorrow's loss.

VaR is computed from past data; it describes the distribution of past returns, not the future. Markets can change regime. In fact: VaR and ES are summary statistics of historical returns. They are useful for understanding how much you could have lost in the past, and for setting exposure limits, but they are not crystal balls.

**Tail events are rare, so ignore them** — A 5% tail is so unlikely that I can focus on the 95%.

Tail events—market crashes—happen more often than a normal distribution would suggest, and they are catastrophic. Models fitted to calm periods systematically underweight these events. In fact: Risk management must explicitly consider tail events. Expected Shortfall focuses on the average of the worst outcomes, which is more informative than VaR alone.

**Higher volatility is always bad** — Volatility means risk, so any volatility is bad.

Volatility is just price movement. If you are a trader, volatility creates opportunities to profit. The library notes that financial language inverts everyday sentiment—volatility is not simply bad. In fact: Volatility is a double-edged sword: it increases the chance of loss but also the chance of gain. The key is to measure it and size positions accordingly.


## In short

Market risk is the potential loss from price movements. It is measured with Value at Risk (VaR), a threshold from the worst 5% of past returns, and Expected Shortfall, the average of the worst 5%. These are simple arithmetic: sort, find percentile, average. But they have a serious limitation: tail events are underweighted by models built from normal times. In AI-driven finance, market risk is the underlying quantity that every model—from sentiment analysis to portfolio optimization—ultimately tries to inform. Remember: VaR is not a ceiling, and the past is not a promise of the future.


## Where this is used

Market risk is everywhere AI touches finance. Start with large language models (LLMs) applied to financial news: a model like FinBERT, built from the general LLM, reads a headline about a central bank raising interest rates. The model doesn't just classify sentiment as positive or negative—it estimates how that news will move bond prices, stock prices, and volatility. That's market risk quantification. A developer might write a prompt asking the LLM to output a prediction of the 10-day VaR for a bond portfolio, and the model would reason about the linkage between rates and bond prices. But the model's numerical reasoning is weak, so a good system would use a tool—like a calculator or a Python function—to compute the exact VaR from the model's output. In small models on devices, think of a mobile trading app that alerts users when their portfolio's VaR exceeds a threshold. The model runs on the phone, estimates potential losses from pre-downloaded market data, and sends a notification. This requires the model to be small and fast, but the risk calculation itself is simple arithmetic once you have the portfolio and the volatility. In retrieval-augmented generation (RAG), an AI assistant for a bank's risk desk retrieves historical loss events from a knowledge base, then generates a report on how similar market conditions could impact current positions. The 'similarity' part uses embeddings—mathematical representations of text—but the risk measures themselves are still VaR and ES. In agentic systems, an AI agent monitors market data, and when volatility spikes, it triggers a rebalancing trade. The agent doesn't just guess—it computes the current VaR using the same formula we wrote, compares it to the bank's risk limit, and if it's too high, sells part of the portfolio. The agent's 'tool' is a Python function that calculates VaR from live prices. In everyday applied machine learning, a hedge fund uses a ML model to predict daily returns of a stock. The model's output is a distribution, not a point estimate, and the risk team converts that distribution into a VaR number to set position limits. A developer would write code to sort the model's predicted returns, take the 5th percentile, and multiply by the portfolio value—exactly what we did. What breaks when done badly? If you use a model trained on a calm period to estimate tail risk, you'll underestimate losses—that's the 'tail events are systematically underweighted' warning. Also, if you use today's data to calculate a historical VaR, you introduce lookahead bias, which the library notes warn about. In practice, a risk analyst at an Indian bank might use a Python library like 'numpy' to compute percentiles, but the underlying logic is the same. The developer would write: `import numpy as np; var = -np.percentile(returns, 5)`—and that line of code does exactly the sorting and indexing we did by hand.


---

Read this on the web: https://basavapurushottam.com/learn-ai/market-risk
