宽客秀

宽客秀

Quant.Show的Web3站点,Archives from quant.show

Use the shift+diff function of pandas to calculate price differences.

When calculating securities prices, we often need to calculate price differences, such as Pt-Pt-1 or log(Pt)-log(Pt-1). Given that the data we obtain is often a complete time-price series, it can be awkward to calculate the aforementioned price differences. In such cases, the shift() and diff() functions in pandas can help us achieve price difference calculations in one step.

For example, the time-price series of Bank of China (601988.XSHG) is shown in the table below. From the table, we can also see that the diff() function is essentially the difference between the shifted() function and the original number.

8a5f006ffd4ce801c8e888ec3bc68361

PAflog.df.diff()[1:0] can be used as the time series of price differences, and further analysis of time series, such as ADF testing, can be performed.

Here is an example program using diff() to determine whether a stock has been continuously rising or falling (run on JoinQuant):

# Get price data for the past 5 days
hist = attribute_history('000001.XSHG', 5, unit='1d',
fields=['open', 'close', 'high', 'low', 'volume', 'money'],
skip_paused=True, df=True, fq='pre')['close']

if all(np.diff(hist)>0):
print('Stock has been rising for 5 consecutive days')
elif all(np.diff(hist) < 0):
print('Stock has been falling for 5 consecutive days')
else:
print('Neither a strong nor weak stock')

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.