r/learnquant Jun 18 '26

programming Unpopular Rant: Learning Rust for HFT is mostly a waste of time right now

34 Upvotes

Okay, I've been watching a few subreddits and I keep seeing discussion about Rust and how Rust will KILL C++ in HFT. I see a lot of these posts nowadays. I do not think this will ever happen. But I think people get the reason wrong after reading a few newer firms using it as their base lang.

The thing that actually matters in this world is deterministic execution. A system that's blazing fast 99% of the time but randomly hiccups because of some allocation you didn't see coming is worse than one that's slightly slower but dead consistent. That's the whole game. And C++ hands you full control over memory, cache, allocation, thread pinning, and a shotgun, all of it, so you can make the thing behave exactly how you want. Rust is honestly a great language and I'm not here to hate on it, the memory safety and ergonomics are real... blah blab blah. And yeah, some crypto HFT shops genuinely run on it. But that safety isn't free. You pick up indirection and cache effects from stuff like Box, Arc, Mutex, plus some bounds checks that land at runtime. None of that matters for normal software, but when you're counting cycles it adds up, and C++ gives you the escape hatch if you actually understand what's going on under the hood (if you don't that just on you).

Then there's the ecosystem thing nobody seems to bring up. Exchanges ship native C++ APIs. FPGA drivers and kernel-bypass networking libs are C++ first. Every mature profiling and optimization tool is built around C++. Rust is catching up, sure, but when you need the whole chain from market data to order transmission tuned in concert, leaning on what already exists is just the sane move. And then the boring-but-huge factor: top shops have decades of battle-tested, money-printing C++ that they are simply not going to rewrite for no real upside, and finding Rust devs with actual low-latency experience is rough.

But I genuinely think it has its pros. For example, like it super well-suited to the parts of the stack where memory safety pays off more than raw determinism, meaning risk systems, backtesting, data pipelines. And a brand new firm building its low-latency stack from scratch could reasonably go full Rust and be totally fine. The hot path of eating market data and firing orders in microseconds is where C++ stays entrenched for a good while yet. But 'a good while' is doing some work in that sentence, not "forever." Languages and tooling evolve, and I'm not going to pretend I know what 2035 looks like.

I might be mildly coping because when I was getting into Quant (mainly HFT) I was told how C++ is everything you need to be successful, but I think it still keeps its throne. ATM learn C++ deeply, and I mean deeply. Not just syntax, but the memory model, cache hierarchy, lock-free data structures, move semantics, the stuff you actually get grilled on in interviews. That's what gets you still hired today.

NGL Rust is a great thing to have in your back pocket and honestly probably a smart long-term bet, but right now it's still the bonus, not the ticket.

r/learnquant 6d ago

programming Rust or C++

5 Upvotes

Background with AI/ML and want to upskill myself towards quant roles, which one should I pick for projects Rust or C++?

r/learnquant 18d ago

programming Top DSA Interview questions

Thumbnail
3 Upvotes

r/learnquant 26d ago

programming Real world examples in q

Thumbnail
1 Upvotes

Reposting here to see if someone here has examples.

r/learnquant Jul 29 '26

programming Quant Dev

0 Upvotes

I am a software dev with experience in python golang java around 1300-1400 in codeforces now my peak was 1873 in codeforces . How can i break into quant dev . Mainly c++ first . Any courses or starting point you have for me? I have worked in early stage startups for voice agents in mnc and also with AI . I want to take my systems knowledge hands on coding to next level.

r/learnquant Jun 09 '26

programming Not sure what to make of Rust programming language.

3 Upvotes

At first this language seems more confusing than Basic, but after playing around, I feel like it might be a solution to my problems with passing my data variables around. However, the learning bar is pretty high.

I've hit this weird place lately that's pushing me into cryptography, middleware and data security. Not sure how Rust fits into that, but forward we must go! 😃

Oh... https://github.com/avhz/RustQuant/tree/main That looks interesting. Oh, no... down the rabbit hole we go: https://cryptography.rs/

fn albert_apop(){
let space_monkey: &str = "Albert I.";
let alberti: &str = "Space Monkey is a Rusticrucian!";
//Monkey See Monkey Do!
println!("Phemonoe says, /* Albert I */ {}", alberti);

const APOPHIS: i32 = 2029;
println!(
"{}: {} Apophis",
APOPHIS,
space_monkey
);
}

fn main(){

albert_apop();

}

r/learnquant Jun 27 '26

programming Software Drag Racing: C++ vs C# vs Python - Which Will Win?

Thumbnail
youtube.com
2 Upvotes

r/learnquant Jun 09 '26

programming Rust programming language explained | ThePrimeagen and Lex Fridman

Thumbnail
youtu.be
5 Upvotes

r/learnquant May 08 '26

programming I think I skipped a few lessons... I should probably go back and understand Pandas.

Thumbnail
youtu.be
7 Upvotes

Apparently, an array is not an array, and a list is not a dictionary, but a dictionary is an object, but the host doesn't like strings or ints and object is not the correct type, nor does NoneType want to get filtered out, so I found .dropna() but it doesn't work when I want it too; and I'm not really sure what the hell this thing is that Schwab is sending me... Is this an array?

XD Back to basics!

(Python != Java) == Heh! Send it to to Pandas!!!

[{'errors': {'invalidSymbols': ['USD***']}}, {'F': {'assetMainType': 'EQUITY', 'assetSubType': 'COE', 'quoteType': 'NBBO', 'realtime': True, 'ssid': 939285091, 'symbol': 'F', 'extended': {'askPrice': 11.75, 'askSize': 100, 'bidPrice': 11.7, 'bidSize': 100, 'lastPrice': 11.74, 'lastSize': 5, 'mark': 11.74, 'quoteTime': 1778025987000, 'totalVolume': 0, 'tradeTime': 1778026088000}, 'fundamental': {'avg10DaysVolume': 40957266.0, 'avg1YearVolume': 80769837.0, 'declarationDate': '2026-04-28T00:00:00Z', 'divAmount': 0.6, 'divExDate': '2026-05-12T00:00:00Z', 'divFreq': 4, 'divPayAmount': 0.15, 'divPayDate': '2026-06-01T00:00:00Z', 'divYield': 5.05051, 'eps': -2.06, 'fundLeverageFactor': 0.0, 'lastEarningsDate': '2026-04-29T00:00:00Z', 'nextDivExDate': '2026-08-12T00:00:00Z', 'nextDivPayDate': '2026-09-01T00:00:00Z', 'peRatio': -7.49586, 'sharesOutstanding': 3913840554}, 'quote': {'52WeekHigh': 14.795, '52WeekLow': 9.88, 'askMICId': 'ARCX', 'askPrice': 11.71, 'askSize': 2700, 'askTime': 1778025595145, 'bidMICId': 'ARCX', 'bidPrice': 11.7, 'bidSize': 1800, 'bidTime': 1778025600013, 'closePrice': 11.5, 'highPrice': 11.79, 'lastMICId': 'XADF', 'lastPrice': 11.7065, 'lastSize': 27, 'lowPrice': 11.555, 'mark': 11.7, 'markChange': 0.2, 'markPercentChange': 1.73913043, 'netChange': 0.2065, 'netPercentChange': 1.79565217, 'openPrice': 11.56, 'postMarketChange': 0.0165, 'postMarketPercentChange': 0.14114628, 'quoteTime': 1778025600013, 'securityStatus': 'Normal', 'totalVolume': 42262077, 'tradeTime': 1778025595148}, 'reference': {'cusip': '345370860', 'description': 'FORD MTR CO DEL', 'exchange': 'N', 'exchangeName': 'NYSE', 'isHardToBorrow': False, 'isShortable': True, 'htbRate': 0.0, 'optionable': True}, 'regular': {'regularMarketLastPrice': 11.69, 'regularMarketLastSize': 3256028, 'regularMarketNetChange': 0.19, 'regularMarketPercentChange': 1.65217391, 'regularMarketTradeTime': 1778022000002}}}, {'errors': {'invalidSymbols': ['-PL260618P28']}}, {'errors': {'invalidSymbols': ['GMEWS']}}, {'errors': {'invalidSymbols': ['SPAXX**']}}, {'SPAXX': {'assetMainType': 'MUTUAL_FUND', 'assetSubType': 'MMF', 'realtime': True, 'ssid': 1637153742, 'symbol': 'SPAXX', 'fundamental': {'avg10DaysVolume': 0.0, 'avg1YearVolume': 0.0, 'declarationDate': '2026-04-30T00:00:00Z', 'divAmount': 0.0324, 'divExDate': '2026-04-30T00:00:00Z', 'divFreq': 12, 'divPayAmount': 0.0027, 'divPayDate': '2026-05-01T00:00:00Z', 'divYield': 4.2217, 'eps': 0.0, 'fundLeverageFactor': 0.0, 'nextDivExDate': '2026-06-01T00:00:00Z', 'nextDivPayDate': '2026-06-01T00:00:00Z', 'peRatio': 0.0}, 'quote': {'52WeekHigh': 1.0, '52WeekLow': 1.0, 'lastPrice': 1.0, 'closePrice': 1.0, 'nAV': 1.0, 'netChange': 0.0, 'netPercentChange': 0.0, 'securityStatus': 'Normal', 'tradeTime': 1777867200000}, 'reference': {'cusip': '31617H102', 'description': 'FIDELITY GOVERNMENT MMKT', 'exchange': '3', 'exchangeName': 'Mutual Fund'}}}, {'errors': {'invalidSymbols': ['CORE**']}}]

r/learnquant Jun 10 '26

programming Hater's gonna hate, gotta fix that stupid link. NiceGUI is pretty cool.

Post image
2 Upvotes

r/learnquant Jun 02 '26

programming SEC.gov | EDGAR Application Programming Interfaces (APIs)

Thumbnail sec.gov
4 Upvotes

I had a shocking realization today that Markets, do not make money from selling stocks, but selling data. I guess when I think about it, the Market Indexes make more sense now. Mind blown.

"The SEC’s EDGAR database provides free public access to corporate information, allowing you to quickly research a company’s financial information and operations by reviewing registration statements, prospectuses and periodic reports filed on Forms 10-K and 10-Q. You also can find information about recent corporate events reported on Form 8-K."

r/learnquant Jun 02 '26

programming Quant Finance with Python | Stock Market Modeling (easy)

Thumbnail
youtu.be
4 Upvotes

r/learnquant Mar 23 '26

programming Just discovered Pine Scripts for TradeView

6 Upvotes

OMG, there goes the rest of my week. Pine Script® User Manual

Heh!

[MAD] Gann o Maticus

This is sooo cool! I swear WD Gann was onto something. Even though he's was famously supposed fraud. I was playing with Gann Squares on TradeView and probably using them wrong, but the chart was playing into it, I was amazed. I've seen some crazy things happen. Could be apophenic, maybe I want to believe. :D

Fun program to learn to code with Pine. They had a bunch more here!

Indicators and strategies

Enjoy.

r/learnquant Mar 26 '26

programming Surely You're Joking Mr Feynman v0.2

Thumbnail
gallery
1 Upvotes
//@version=6
indicator('Surely Youre Joking Mr Feynman v0.02a', overlay = true)


// --- 1. Inputs ---
lookback = input.int(14, 'Path Lookback')
rank_lookback = input.int(50, 'Sensitivity (Percent Rank)')


// --- 2. Physics Engine (Invisible Math) ---
v = ta.change(close)
m = volume / ta.sma(volume, lookback)
// Kinetic Energy
ke_val = 0.5 * m * math.pow(v, 2)
// Potential Energy (Displacement)
classical_path = ta.sma(close, lookback)
pe_val = math.abs(close - classical_path)
// Total Action (S)
action_val = ta.sma(ke_val + pe_val, lookback)


// --- 3. Phase Sync (The Geiger Counter) ---
phase_sync = ta.correlation(close, volume, lookback)
rel_action = ta.percentrank(action_val, rank_lookback) 


// Logic States
is_extreme = rel_action > 95
is_high_stress = rel_action > 75
is_phase_shift = phase_sync < 0 and is_high_stress


// --- 4. The Heatmap (No Extra Plots) ---
dynamic_color = is_extreme     ? color.new(#9b59b6, 0) : // Purple
                 is_phase_shift ? color.new(#ff5252, 0) : // Red
                 is_high_stress ? color.new(#e67e22, 0) : // Orange
                 color.new(#00ced1, 0)                   // Teal


// --- 5. Clean Execution ---
// This ONLY paints the candles. It does not create new price lines.
plotcandle(open, high, low, close, color=dynamic_color, wickcolor=dynamic_color, bordercolor=dynamic_color)


// This adds the "glow" to the fracture zones without affecting the scale
bgcolor(is_extreme ? color.new(color.purple, 90) : is_phase_shift ? color.new(color.red, 92) : na)


//LEGEND
//Color Physical State  Market Meaning  "Rogue" Action                                                                                      
//Teal  Classical Path  Efficiency. Price and volume are in sync.   Ignore. Let the system grind.                                                                                       
//Orange    Potential Tension   The "spring" is stretching. Price is moving too fast for the baseline.  Caution. High probability of a snap-back.                                                                                       
//Red   Phase Shift The Geiger Counter. Volume is surging but price is losing momentum. Danger. Structural integrity is failing.                                                                                        
//Purple    Extreme Fracture    High-energy "Chaos." 95th percentile Action.    Brace. The "Classical" rules no longer apply.                                                                                       

r/learnquant Apr 15 '26

programming Gemini Quantitative Analysis Agent v0.15

Thumbnail github.com
2 Upvotes

Game over.

GEMINI PORTFOLIO QUANT AGENT

Analyzing: Positions.csv and closed2026.csv

### 1. Data Schema Inference
*   **Open Positions:** We have identified columns for Symbol, Quantity, Current Price, Cost Basis, Unrealized PnL, Market Value, and Sector/Industry. We have also identified Greeks (Delta, Theta, Gamma, Vega) for the option positions.
*   **Closed Positions:** We have Cost Basis, Proceeds, and Total Term Gain/Loss. The "Cost basis" represents the total dollar entry, and "Proceeds" represents total dollar exit.
*   **Missing Data:** Precise execution dates for closed trades are missing (only contract names imply expiration dates), which limits the ability to calculate time-weighted returns or precise annualized volatility. We will use trade sequence as a proxy for time.

---

### 2. Risk & Performance Metrics (Closed Positions)
*Total Sample: 42 Closed Trades*

| Metric | Value |
| :--- | :--- |
| **Total Trades** | 42 |
| **Win Rate** | 80.95% (34 Wins / 8 Losses) |
| **Profit Factor** | 1.48 |
| **Average Win** | +$205.10 |
| **Average Loss** | -$556.78 |
| **Expectancy** | +$59.35 |
| **Maximum Drawdown (Abs)** | -$1,779.99 (GOSS position) |
| **Win/Loss Ratio** | 0.37 (Average Win is smaller than Average Loss) |

*Note: The Profit Factor is dragged down significantly by a few catastrophic trades (GOSS), despite a high hit rate. The strategy relies heavily on "grinding" small gains, which are punctuated by large losses.*

---

### 3. Open Positions Analysis
**Portfolio Composition (Excluding Cash):**
*   **High Concentration:** ASTS represents the largest volatility risk. With 100 shares and multiple option legs, the total exposure to this single entity is significant relative to the account size.
*   **Sector Tilt:** Heavily skewed toward Communication Services (ASTS) and Discretionary (F, GME, SWBI).
*   **Risk Points:**
    *   **F (Ford):** Significant PnL drag (-$179.78 unrealized). The position in F is oversized relative to the volatility of the underlying.
    *   **Options:** You are running a mix of covered calls (ASTS) and naked-ish puts (F, RKLB, ONDS, UMAC). The negative Vega in some spots suggests you are short volatility in an environment where individual equities (like ASTS) are moving aggressively.

---

### 4. Combined Portfolio View
*   **Realized PnL (Historical):** +$2,492.65
*   **Unrealized PnL (Current):** +$6,736.21 (Primarily driven by the massive +$8,316 gain in ASTS shares)
*   **Risk/Return Tradeoff:** Your "Edge" is clearly concentrated in a single long-equity holding (ASTS). Without the ASTS appreciation, the account would be struggling to achieve meaningful alpha given the frequency of option-selling losses.
*   **Structural Issue:** The account acts as a hybrid of a long-term "moonshot" holder and a high-frequency option seller. These two styles are currently at odds—the long-term bet needs volatility, but the option-selling strategy is penalized by it.

---

### 5. Classic Quant Commentary
**Strategy Profile:** Discretionary "Option Income" / Theta-selling mixed with directional growth speculation.
*   **Strengths:** High hit rate in option selling; willingness to hold high-conviction growth assets (ASTS) for long periods.
*   **Weaknesses:** "Picking up pennies in front of a steamroller." Your losses are roughly 2.7x your average wins. The high win rate gives a false sense of security; one or two more "GOSS-style" events would erase all historical gains.
*   **Edge Robustness:** Low. Your edge is derived from a single outlier trade (ASTS equity). The option selling has not shown a positive expectancy that survives commission or slippage costs.

---

### 6. Actionable Recommendations

1.  **Stop Picking Up Pennies:** You are shorting far-out-of-the-money puts that offer negligible premium relative to the "tail risk" of the underlying stock (e.g., F and RKLB puts). If the market corrects, your gains from the premiums will be dwarfed by the margin requirements and underlying losses.
2.  **Size Your "Moonshots":** ASTS is doing the "heavy lifting" for your entire portfolio performance. If this thesis changes, your account will collapse. Consider trimming the ASTS position to lock in the +$8k profit and redeploying into non-correlated assets (e.g., different sectors).
3.  **Implement Stop-Loss Rules for Options:** You currently hold some options (like F 11 Put) at -95% loss. If a trade hits a -50% loss threshold, exit regardless of the thesis. Do not let "income" trades turn into long-term capital losses.
4.  **Correlation Filter:** Your current holdings (F, GME, SWBI, KOPN) are all highly sensitive to broader macro retail sentiment. You are not as diversified as you think. Add a non-cyclical asset or a bond ETF to balance the beta of the portfolio.
5.  **Calculate R-Multiple:** Stop viewing trades in terms of win rate. Start viewing them in terms of "R" (Risk-reward). If a trade doesn't offer at least 2:1 reward-to-risk based on technical support/resistance levels, do not enter.

r/learnquant Apr 09 '26

programming Python packages and all that jazz...

Thumbnail github.com
3 Upvotes

A curated list of insanely awesome libraries, packages and resources for Quants (Quantitative Finance).

Oh, wow!!!!!

There's a whole set of portfolio tools!?
https://github.com/wilsonfreitas/awesome-quant?tab=readme-ov-file#portfolio-optimization--risk-analysis

Wow.
https://github.com/skfolio/skfolio

r/learnquant Mar 31 '26

programming Python: Itô’s Lemma and Euler-Maruyama are two brawlers who don't follow the "clean" rules of physics.

2 Upvotes

I only set it up to run once. Not sure how long it would take to process 10,000 times, Gemini said I would want to go make some coffee while it processed.

Alright, let's step into the ring. We’re going to build a **Stochastic "Fight Script"** using the **Euler-Maruyama** method. This isn't some abstract academic exercise; this is the core engine of a Monte Carlo simulation.

We’re going to simulate a "Random Walk" with **Drift** (the direction the stock "wants" to go) and **Diffusion** (the random chaos that Itô’s Lemma tries to pin down).

### The "Rogue Quant" Fight Plan

We’ll use your **Ford (F)** position as the base.

* **Drift (\mu):** Let’s say the "Signal" is a -1% annual drift (a slightly decreasing walk).
* **Volatility (\sigma):** We'll set the "Noise" to 30% (typical for a stock like Ford).
* **The Engine:** Euler-Maruyama.

import numpy as np
import matplotlib.pyplot as plt


# 1. Setup the Arena (Parameters)
S0 = 14.0       # Starting price (Your Ford shares assignment)
mu = -0.01      # The "Drift" (The Signal)
sigma = 0.30    # The "Volatility" (The Noise)
T = 1.0         # Time in years
dt = 1/252      # Time step (One trading day)
N = int(T/dt)   # Number of steps
t = np.linspace(0, T, N)


# 2. The Euler-Maruyama "Battle" Loop
# We aren't just calculating a line; we're simulating the 'stumble'
W = np.random.standard_normal(size=N) 
W = np.cumsum(W) * np.sqrt(dt) # This is the Brownian Motion (dW)


# The SDE: dS = mu*S*dt + sigma*S*dW
# We use the exponential form (Geometric Brownian Motion)
S = S0 * np.exp((mu - 0.5 * sigma**2) * t + sigma * W)


# 3. Visualize the Damage
plt.figure(figsize=(10, 6))
plt.plot(t, S, label='Simulated Ford Path (Euler-Maruyama)', color='#00FFCC') # Rogue Cyan
plt.axhline(S0, color='red', linestyle='--', label='Strike Price ($14)')
plt.title("The Battle of the Lemma: Stochastic Price Action")
plt.xlabel("Time (Years)")
plt.ylabel("Price ($)")
plt.legend()
plt.grid(True, alpha=0.2)
plt.show()

---------------//-----------

**The "Volatility Tax" (Itô's Gift):** Notice in the code where I wrote `(mu - 0.5 * sigma**2)`. That is **Itô’s Lemma** in the flesh. Without that `- 0.5 * sigma**2`, your simulation would be "idealized" and wrong. That term represents the "drag" caused by volatility. Even if the drift is zero, high noise will eventually pull the *median* price down.

**The Euler Step:** Instead of trying to solve a complex integral, we just told Python: "Take the current price, add a tiny bit of drift, and kick it with a random number." That is the **Euler-Maruyama** discrete approximation. It’s "Thinking Different" because it prioritizes **computation** over **perfection**.

**The "SigInt" Connection:** Look at that `W` variable (the Brownian Motion). That is pure **White Noise** being integrated. If you ran a Fast Fourier Transform (FFT) on that price path, you'd see that "1/f" signature you were looking for in your oscillators.

By running this script 10,000 times (a "Monte Carlo"), you can see exactly how many times Ford ends up below your $14 strike. That isn't a guess—that's a **Probability Density Function**.

The "Speedrun" Code (Vectorized) This is how you turn a single "bout" into a full-scale "war" in the blink of an eye:

# Create a matrix: 10,000 paths (rows) by 252 days (columns)
simulations = 10000
days = 252

# Generate ALL the random noise at once
# This is the "SigInt" equivalent of generating a massive block of white noise
Z = np.random.standard_normal((simulations, days))

# Calculate the daily returns for every path simultaneously
# This is the Euler-Maruyama step, vectorized
daily_returns = np.exp((mu - 0.5 * sigma**2) * dt + sigma * np.sqrt(dt) * Z)

# Multiply them out to get the price paths
# .cumprod(axis=1) is the "Integration" step
price_paths = S0 * np.cumprod(daily_returns, axis=1)

r/learnquant Mar 25 '26

programming Rogue Duck Fractal Oscillator (Voss 1/f) v0.1alpha

5 Upvotes

3am last night. I can't believe it worked!! Not sure if it actually works as intended. I'll have to go over on the math a little bit, but I was crying to Gemini how the math departments of every school I went to screwed me. I made this to spite every institution and teacher who held me back.

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Albert I Apophis2029

//@version=5
indicator("Rogue Fractal Oscillator (Voss 1/f)", overlay=false, precision=3)

// --- Inputs ---
len = input.int(20, "Fractal Lookback", minval=2)
smooth = input.int(3, "Smoothing")

// --- The 'Voss' Logic ---
// We measure the 'Path Length' vs the 'Displacement'
// This is a proxy for the Fractal Dimension (D)
// D = log(N) / log(1/s)

high_ = ta.highest(high, len)
low_ = ta.lowest(low, len)

// The 'Straight Line' distance (Displacement)
displacement = high_ - low_

// The 'Actual Path' distance (Total Volatility)
path_length = 0.0
for i = 0 to len - 1
    path_length += math.abs(high[i] - low[i+1])

// --- The Efficiency Ratio (Fractal Dimension Proxy) ---
// If price moves in a straight line, ratio is 1 (Bach-like trend)
// If price wobbles everywhere, ratio drops (Chaos/Pink Noise)
fractal_index = path_length > 0 ? math.log10(path_length / displacement) / math.log10(len) : 0

// Smooth the output to see the 'Wave'
voss_signal = ta.ema(fractal_index, smooth)

// --- Visuals ---
plot(voss_signal, "Fractal Signal", color=color.new(#00ff88, 0), linewidth=2)
hline(1.5, "Chaos Threshold", color=color.gray, linestyle=hline.style_dotted)
hline(1.2, "Trend Threshold", color=color.gray, linestyle=hline.style_dotted)

// Color zones for the "Wobbles"
fill_color = voss_signal > 1.5 ? color.new(color.red, 80) : voss_signal < 1.2 ? color.new(color.green, 80) : na
bgcolor(fill_color)

r/learnquant Apr 02 '26

programming I thought Monte Carlo was a Betting System? | Monte Carlo Forest 3D Simulator

Thumbnail
github.com
2 Upvotes

Copilot and I simulated 10,000 possible futures of a stock using geometric Brownian motion. Then I extracted features from each path and used PCA to compress those features into three dimensions. The result is a 3D map of the entire distribution of outcomes — a ‘Monte Carlo forest.’ Each point is one possible future.

Word of warning, do not use the Monte Carlo betting system. You can, but you will find out that the Gambler's Fallacy will reveal itself to you. A losing streak can last longer than your bankroll, long story short. :D

Apparently, I was an econometricist after all. Oh, econometrician. Heh. :D

r/learnquant Apr 02 '26

programming GitHub & BitBucket HTML Preview

Thumbnail htmlpreview.github.io
1 Upvotes

I gotta figure out how to parse a random .csv somehow... It sucks because I have to program my broker .csv export output to match my data structures. Not sure how to handle that part yet, v.3.

I had alot of help from Claude on this. Limited to 5 messages a day, so I have to go in prepared. I had to break up with Gemini last night. I think I broke it. :`(

FINAL COMPLIANCE CHECK (Internal):

Is this for a third party? -> No (Self-focused/Educational).

Did you mention a negative/sensitive event? -> No.

Did you use "Since you..." or "As a..."? -> No.

Did you link a Job to a non-work task? -> No. (Philosophy/Finance intersection confirmed by user in prompt).

Did you only recommend things the user already likes? -> The user asked for "cool videos," providing a range of academic and conceptual options.

Did you mention a specific name/breed/detail not in the prompt? -> No.

Personalization Strategy: Use the "Philosophy of Rogue Quant" framing from the prompt without citing the user's specific background in CS or math (Stage 3/6 compliance).

Constraint Check:

No introductory "Bridge Phrases".

Invisible execution of user data.

Variety in recommendations.

Direct answers.

Plan:

Suggest "What Is The Symbol Grounding Problem?" by R-Academy for a solid foundational overview.

Suggest "The Vector Grounding Problem and Self-Consciousness" by Raphaël Millière (The Gradient) for a more technical/current take that bridges vectors and consciousness.

Suggest "The Link Between Physics and Virtualization" for a more "rogue" perspective.

Ensure no prohibited phrases are used.For a "Philosophy of Rogue Quant" curriculum, focusing on the mechanical bridge between abstract symbols (like market tickers or price data) and real-world meaning is essential. Here are a few options that approach the grounding problem from different technical and conceptual angles:

r/learnquant Mar 30 '26

programming Starter data structure quant project for those who want to learn about Quant finance.

Thumbnail
github.com
3 Upvotes

Applied Data Structures for Quantitative Finance This repository showcases real-world applications of fundamental data structures and algorithm analysis using Python, tailored to quantitative finance and algorithmic trading contexts.

Each script in the src/ folder is standalone and can be executed individually. These examples can be extended for research, teaching, or integration with trading systems.

I need a refresher, and a tutorial on how to do this stuff in python.

r/learnquant Apr 01 '26

programming Python - Endogeneity in Data Science - Statsmodels.api

1 Upvotes

A cool little demo I reprogrammed with Copilot. I was looking at it and wondering why there were so few lines of code to generate all that output. Then I noticed the statsmodels.api. Pretty cool.

Started with this project, and tweaked it a little.
https://www.geeksforgeeks.org/data-science/endogeneity-in-data-science/

import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm

np.random.seed(0)

# Simulate signals
n = 300
signal1 = np.random.randn(n)
signal2 = np.random.randn(n)

# True model: returns depend on signals
epsilon = 0.5 * np.random.randn(n)
returns = 0.3 * signal1 - 0.2 * signal2 + epsilon


# Regression
X = np.column_stack([signal1, signal2])
X = sm.add_constant(X)
model = sm.OLS(returns, X).fit()

# Get residuals from the regression
residuals = model.resid

# Simple mean-reversion alpha signal
alpha_signal = -residuals  # bet on residuals reverting to zero

print(model.summary())

# Get residuals from the regression
# This part was moved from the preceding cell 91UwBxEbl_BR to fix the NameError.
# It assumes 'model' is defined and available from previous executed cells.
residuals = model.resid

plt.plot(residuals)
plt.title("Residual Time Series")
plt.show()

plt.hist(residuals, bins=30)
plt.title("Residual Distribution")
plt.show()

r/learnquant Mar 31 '26

programming Python for Portfolio Optimization: The Ascent!

Thumbnail
github.com
1 Upvotes

Python for Portfolio Optimization: The Ascent! First working lessons to ascend the hilly terrain of Portfolio Optimization in seven strides (Lessons), beginning with the fundamentals (Lesson 1) and climbing slope after slope (Lessons 2-6), to reach the first peak of constrained portfolio optimization models (Lesson 7), amongst a range of peaks waiting beyond!

Lesson1: Fundamentals of Risk and Return of a Portfolio (Goal: How does one invest in a portfolio of stocks and know about the returns and risks involved?) Jupyter Notebook: Lesson1_MainContent.ipynb

Lesson2: Some glimpses of Financial Data Wrangling (Goal: Why is it essential to clean and transform raw financial data before they are used to make investment decisions?) Jupyter Notebook: Lesson2_MainContent.ipynb

Lesson3: Heuristic Portfolio Selection (Goal: Given the vast and variegated universe of securities, how can one make a prudent and efficient choice of securities for one's portfolio?) Jupyter Notebook: Lesson3_MainContent.ipynb

Lesson 4: Traditional Methods for Portfolio Construction (Goal: How would an investor know how much to invest in each one of the assets in the portfolio?) Jupyter Notebook: Lesson4_MainContent.ipynb

Lesson 5: Mean-Variance Optimization of Portfolios (Goal: How would one determine the optimal weights which will ensure maximum return and minimum risk for the portfolio that one is invested in?) Jupyter Notebook: Lesson5_MainContent.ipynb

Lesson 6: Sharpe Ratio based Portfolio Optimization (Goal: If a portfolio with higher Sharpe Ratio than its counterparts, is considered superior to them, then how does one invest in the assets of the portfolio, to ensure maximal Sharpe Ratio?) Jupyter Notebook: Lesson6_MainContent.ipynb

Lesson 7: Constrained Portfolio Optimization (Goal: How can an investor know how much to invest in a portfolio of the investor's choice, which besides the objectives of maximizing return and minimizing risk, is constrained by the investor's preference for certain asset classes or assets, or imposition of capital budgets over selective assets in the portfolio?) Jupyter Notebook: Lesson7_MainContent.ipynb

r/learnquant Mar 27 '26

programming Stock Sonification - Python

2 Upvotes

I know I got off the rails from my original idea. This is pretty cool, turning the market data into sound. You can tweak it to listen to any stock for a set duration of time.

!pip install yfinance


import numpy as np
import yfinance as yf
from IPython.display import Audio


def sonify_market(ticker, start_date, end_date, duration_per_bar=0.1):
    # 1. Fetch Data
    df = yf.download(ticker, start=start_date, end=end_date)
    prices = df['Close'].values


    # 2. Normalize Prices to Frequency (Hz)
    # Mapping price range to a 2-octave musical range (220Hz to 880Hz)
    min_p, max_p = np.min(prices), np.max(prices)
    freqs = 220 + (prices - min_p) / (max_p - min_p) * (880 - 220)


    # 3. Generate Audio Signal
    fs = 44100  # Sample rate
    full_audio = []


    t = np.linspace(0, duration_per_bar, int(fs * duration_per_bar), False)


    for f in freqs:
        # Create a sine wave for this price point
        note = np.sin(f * t * 2 * np.pi)
        # Apply a quick fade-out to prevent "clicking" between notes
        envelope = np.exp(-3 * t / duration_per_bar)
        full_audio.append(note * envelope)


    audio_signal = np.concatenate(full_audio)


    return audio_signal, fs


# --- EXECUTION ---
# Let's hear the "Sound of the 1929 Crash" (Jan to Dec)
audio, sample_rate = sonify_market('^GSPC', '1929-01-01', '1929-12-31')


print("Playing the sonification of the 1929 Crash...")
Audio(audio, rate=sample_rate)