Implement EMA Crossovers and Root Solvers
SquarepointQuantitative Trader · Technical ScreenLast updated
This problem tests your ability to manipulate time-series data using vectorized operations and implement iterative numerical approximations for square roots.
Part 1: EMA Crossover Signal
Given a pandas Series prices of daily closing values, compute a boolean Series crossover_signal that is True on the day the 10-day Exponential Moving Average (EMA) crosses above the 50-day EMA, and False otherwise.
Implement the function:
def get_ema_crossovers(prices: pd.Series) -> pd.Series:
# Returns a boolean Series of the same index as prices
Note: Use the standard pandas ewm method. Assume the first few days where EMAs cannot be fully calculated result in False.
Part 2: Numerical Square Root
Implement a function to find the square root of a non-negative float n using Newton’s Method. You must not use the math.sqrt function or the ** 0.5 operator.
Implement the function:
def sqrt_newton(n: float, tolerance: float = 1e-7) -> float:
# Returns the square root of n using Newton's method
Newton's formula for sqrt(n) is x_{k+1} = 0.5 * (x_k + n / x_k). Stop when the difference between the current guess and the previous guess is less than tolerance.
Example
sqrt_newton(25) should return 5.0 (or a value very close to it, e.g., 5.000000000000001).
Constraints
n >= 0- Handle the edge case
n = 0. - For
n < 1, ensure the algorithm converges efficiently.
Hints
Hint 1
For the EMA, use pandas' `ewm(span=...).mean()` and remember to shift the result by 1 index to compare the current day's EMAs with the previous day's EMAs.
Hint 2
For the square root, choose an initial guess `x = n / 2` if `n > 1`, or `x = 1` if `n < 1` to ensure faster convergence.
Hint 3
In the EMA crossover logic, ensure you strictly check that the 10-day was *below* (or equal to) the 50-day on the previous day and *above* on the current day.
Follow-up questions
- How would you modify the EMA crossover logic to account for a 'buffer' or 'band' to filter out false-positive noise where the lines are nearly touching?
- If the Newton's method fails to converge, what are the potential causes, and how would you implement a fallback mechanism?
- How does the time complexity of Newton's method compare to a binary search approach for finding the square root of a number?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.