Rolling median in python

I have stock data based on daily closing values. I need to be able to insert these values ​​in a python list and get the median for the last 30 closures. Is there a python library that does this?

+4
source share
3 answers

Did you consider pandas ? It is based on numpy and can automatically associate timestamps with your data and discards any unknown dates while you fill it with numpy.nan . It also offers some pretty powerful graphics through matplotlib.

It was mainly developed for financial analysis in python.

+4
source

In pure Python, having your data in Python a list you could do

 median = sum(sorted(a[-30:])[14:16]) / 2.0 

(It is assumed that a has at least 30 elements.)

Using the NumPy package, you can use

 median = numpy.median(a[-30:]) 
+9
source

is not median only average value in sorted range?

so if your list is stock_data :

 last_thirty = stock_data[-30:] median = sorted(last_thirty)[15] 

Now you just need to find the errors found and corrected, as well as handle the case of stock_data less than 30 elements ...

let's try a little here:

 def rolling_median(data, window): if len(data) < window: subject = data[:] else: subject = data[-30:] return sorted(subject)[len(subject)/2] 
+2
source

Source: https://habr.com/ru/post/1345871/


All Articles