Discover how our trading algorithm applies Lagrangian mechanics to analyze market dynamics.
All Juice Capital - May 2025. Advancing science through transparency and access. Contact Us on LinkedIn.
Note: Downloads are currently supported only on Google Chrome, Firefox, or other major browsers.
Downloads historical stock data using yfinance — Identifies potential buy signals when kinetic energy dominates over mean reversion — Computes velocity, potential energy, kinetic energy, and Lagrangian from price movements — Exports trading signals to a text file — Visualizes price, velocity, energy metrics, and Lagrangian over time using matplotlib — Designed for conceptual and educational demonstration of physics-inspired trading strategies.
This section explores how our trading algorithm uses the Lagrangian formulation to analyze price dynamics, providing insights into potential trading opportunities.
In physics, the Lagrangian (L) describes a system's energy. Our algorithm adapts this by combining kinetic energy (KE) and potential energy (PE):
Kinetic energy is defined as:
Where m is a mass-like coefficient reflecting market volatility, and v is the price velocity:
The potential energy represents the system's market positioning and can be modeled as a function of price deviations from an equilibrium.
The potential energy models price pullbacks toward their mean:
// Function to calculate the Lagrangian
double CalculateLagrangian(double velocity, double price, double meanPrice)
{
double kineticEnergy = 0.5 * m * MathPow(velocity, 2);
double potentialEnergy = CalculatePotentialEnergy(price, meanPrice);
return kineticEnergy - potentialEnergy;
}
// Function to calculate velocity and acceleration of the price
void CalculatePriceDynamics(double &velocity, double &acceleration)
{
static double previousPrice = 0.0;
static double previousVelocity = 0.0;
double currentPrice = iClose(_Symbol, PERIOD_CURRENT, 0);
velocity = (currentPrice - previousPrice) / PeriodSeconds();
velocity *= 1e5;
acceleration = (velocity - previousVelocity) / PeriodSeconds();
previousPrice = currentPrice;
previousVelocity = velocity;
}
// Buy condition
double lagrangianThreshold = -500.0;
if (lagrangian > lagrangianThreshold && velocity > 0.0001)
{
// Open buy order
}