Unlocking Quantitative Analysis
We recognise that programming is crucial for automating calculations, managing large datasets, and developing models. Python is a great starting language due to its simplicity and powerful libraries, such as NumPy for numerical computations, Pandas for data manipulation, and Matplotlib for visualisation.
Quantitative analysis involves using mathematical and statistical methods to evaluate data, often in fields like finance, economics, or data science.
So why don’t we check out how they work together?
As a problem solver, we know a few things like Basic Statistical Analysis (like calculating Mean and Standard Deviation):
import numpy as np
returns = [0.01, -0.02, 0.03, 0.015, -0.005]
mean_return = np.mean(returns)
print(f"Mean Return: {mean_return:.4f}")
std_dev = np.std(returns)
print(f"Standard Deviation: {std_dev:.4f}")
Or maybe consider a situation like using a CSV file:
import pandas as pd
data = pd.read_csv('stock_data.csv', parse_dates=['Date'])
data.set_index('Date', inplace=True)
data['Avg'] = data['Price'].rolling(window=5).mean()
print(data.head())
import matplotlib.pyplot as plt
data['Price'].plot(label='Price')
data['Avg'].plot(label='5-Day MA')
plt.legend()
plt.show()
Or maybe something like this helps identify trends in quantitative trading strategies.
Now it’s time to know we’ll know algorithms that are super useful and every programmer should know, regardless of whether they’re part of a quant analysis.
Monte Carlo Simulation
import numpy as np
import matplotlib.pyplot as plt
initial_price = 100
days = 252 # Trading days in a year
mean_return = 0.001 # Daily return
volatility = 0.01 # Daily volatility
simulations = 1000
prices = np.zeros((days, simulations))
prices[0] = initial_price
for t in range(1, days):
shocks = np.random.normal(mean_return, volatility, simulations)
prices[t] = prices[t-1] * (1 + shocks)
plt.plot(prices[:, :5])
plt.title('Monte Carlo Simulation of Stock Prices')
plt.show()
# Here I am just checking using a few examples.
final_prices = prices[-1]
print(f"Mean Final Price: {np.mean(final_prices):.2f}")
print(f"Std Dev of Final Prices: {np.std(final_prices):.2f}")
You can simulate future stock prices using random walks. This model's uncertainty, common in options pricing
And recently, I was going through a coding platform. And I’ve come across this problem that is super good to solve. Check this one.
Question: You are given an array of integers representing daily stock prices. Find the maximum profit you can achieve by buying on one day and selling on a later day. If no profit is possible, return 0.
Let's just assume:
Ex-1
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Ex-2
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Let's just assume constraints:
1 <= prices.length <= 10^5
0 <= prices[i] <= 10^4
My solution
def maxProfit(self, prices: List[int]) -> int:
min_price = math.inf
max_profit = 0
for price in prices:
min_price = min(min_price, price)
potential_profit = price - min_price
max_profit = max(max_profit, potential_profit)
return max_profit
here as we iterate through the prices list, min_price = min(min_price, price) keeps a running memory of the absolute lowest price encountered
And I implemented max_profit = max(max_profit, potential_profit) to check if this profit is better than any other profit we could have made on a previous day.
It's just a single-pass iteration, and it only needs to go through the list of prices once. Pretty much greedy. It has a time complexity of O(N).
Top comments (0)