> *If you want to know where the price is going, draw a line through where it's been. LSMA does this for every single bar, tirelessly fitting linear regressions while you sleep.*
- LSMA (Least Squares Moving Average), also known as the Moving Linear Regression or Endpoint Moving Average, calculates the least squares regression...
- **Similar:** [EPMA](../epma/epma.md), [ALMA](../alma/alma.md) | **Complementary:** R-squared for regression quality | **Trading note:** Least Squares MA; linear regression value at current bar, minimizing squared deviations.
LSMA (Least Squares Moving Average), also known as the Moving Linear Regression or Endpoint Moving Average, calculates the least squares regression line for the preceding time periods. In plain English: it finds the "best fit" line for the data window and tells you where that line ends.
## Historical Context
Linear regression is as old as Gauss (c. 1809). Applying it as a moving window to financial time series is a more recent development, popularized by traders who realized that a moving average is just a poor man's regression line (specifically, an SMA is a regression line with a slope of 0). LSMA captures both the level and the trend (slope) of the data.
## Architecture & Physics
LSMA is computationally heavier than an SMA because it minimizes the sum of squared errors for a line equation $y = mx + b$.
* **Slope ($m$)**: Represents the trend strength/direction.
* **Intercept ($b$)**: Represents the value at the start of the window.
* **Endpoint**: The value at the current bar ($y = m \times 0 + b$ in our coordinate system where current bar is 0).
## Mathematical Foundation
The regression line is $y = mx + b$.
$$ m = \frac{N \sum xy - \sum x \sum y}{N \sum x^2 - (\sum x)^2} $$
$$ b = \frac{\sum y - m \sum x}{N} $$
$$ \text{LSMA} = b - m \times \text{Offset} $$
(Note: In the QuanTAlib implementation, $x$ ranges from $N-1$ (oldest) to $0$ (newest) to simplify the math).
## Performance Profile
### Operation Count (Streaming Mode, Scalar)
The O(1) algorithm maintains running sums instead of recomputing the regression on each bar:
**State variables maintained:**
-`sum_x`: Sum of x indices (precomputed constant for fixed period)