Your question is Real-Time Moving Metrics Structure. Start with the requirements on the right.
Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.
AKUNA Capital's real-time trading components need moving statistics for a stream of integer market prices. Given a fixed window size, process each arriving price and return the current mean and mode of the prices currently in the window.
The window contains at most the most recent window_size prices. For the mode, return the value with the highest frequency. If multiple values have the same highest frequency, return the smallest value.
Implement moving_metrics(prices, window_size), where prices is a list of integers and window_size is a positive integer. Return a list of dictionaries, one per arriving price, with the exact keys mean and mode. The mean must be returned as a Python floating-point value. Before the window reaches window_size, calculate metrics over all prices seen so far.
An efficient solution should avoid rescanning the complete window after every insertion.
def moving_metrics(prices, window_size):