[Play Quantitative 15 from scratch] How to calculate historical market quantile points

quantile

This is the quantile point in quantitative analysis that most intuitively represents the current price level. Its specific value is a percentage, with a value between 0 and 100, representing the ranking order of prices within a period of time. Let's take a look at the visualization I made first.

The picture below shows the historical market data of the Shenwan Bank Index in the past year. I have drawn three lines on it, representing the 1-year, 3-year, and 5-year quantile points respectively.
insert image description here
It can be seen that the 1-year quantile has risen to more than 50%, while the 3-year and 5-year periods are still at 20%. It shows that it has been rising recently, but the medium and long-term position is still relatively low.

pct_rank

The specific use stats.pct_rank, its source code is as follows.

def pct_rank(prices, window=60):
    """Rank prices by window"""
    rank = _utils.multi_shift(prices, window).T.rank(pct=True).T
    return rank.iloc[:, 0] * 100.

Prices is a Series with time as index and price as value, window is the number of days in the window, and I choose 250 for one year.

combat

First find a way to obtain historical data and save it as a pandas data table df. First, you need to dfset the index as a date, so that you can directly calculate it.

import quantstats as qs

df = ak.stock_zh_a_hist(symbol='600519', adjust='hfq')
df.index = res['日期']


df['pct_rank1'] = qs.stats.pct_rank(df['收盘'], 250)
df['pct_rank3'] = qs.stats.pct_rank(df['收盘'], 750)
df['pct_rank5'] = qs.stats.pct_rank(df['收盘'], 1250)

df

Guess you like

Origin blog.csdn.net/u010214511/article/details/128755742