Mathematically, what is going on here?
If two price series are cointegrated, you can run the linear regression to calculate the hedge ratio.
The linear regression is in the form: $$y = \beta X + \epsilon$$
where, $y$ is the dependent variable, $X$ is the independent variables, and $\beta$ is the slope that we want to estimate and $\epsilon$ is the error term.
In Python, the OLS function from the statsmodels package is used to calculate the hedge Ratio:
statsmodels.api.OLS (dependent_variable(y), independent_variable(X))
To find the hedge ratio you can run the Johansen Cointegration test and the eigen-vector corresponding to the largest eigenvalue would give you the hedge ratio, you can see with a bit mathematical intuition that it means “The best linear combination of the two series to maintain a stationary series”. The eigenvector would ideally be something like (1, -ve) for a pair since hedge ratio has to be negative. Also before this you’d need to check whether the original pair was individually non-stationary.