Code Review Asked by HJA24 on November 15, 2021
I want to calculate the hitting time of a sequence of prices. I define a log price corridor by for forming a double barrier, up_threshold
and down_threshold
.
When one of the barriers is touched, I note the time and reset the barriers around the last price
My script looks as follows:
import pandas as pd
def speed(prices: pd.DataFrame, threshold: float=0.05):
times = []
up_threshold, down_threshold = threshold, -threshold
returns = (prices['Price'] / prices['Price'].shift(1)).apply(np.log)
cum_returns = returns.cumsum(axis=0)
for cum_return in cum_returns:
if -threshold < cum_return < threshold:
# this possibility will probably occur the most frequently
continue
elif cum_return > threshold:
times.append(cum_return)
up_threshold += threshold
down_threshold += threshold
else:
times.append(cum_return)
up_threshold -= threshold
down_threshold -= threshold
if __name__ == '__main__':
prices = np.random.random_integers(10, 25, 100)
prices = pd.DataFrame(prices, columns=['Price'])
speed(prices=prices, threshold=0.05)
How can I improve this script? Is it wise to also use an apply function for the cum_returns
-part? The speed of the script is important. Thanks in advance
This:
if -threshold < cum_return < threshold:
# this possibility will probably occur the most frequently
continue
elif cum_return > threshold:
times.append(cum_return)
up_threshold += threshold
down_threshold += threshold
else:
times.append(cum_return)
up_threshold -= threshold
down_threshold -= threshold
can be
if -threshold < cum_return < threshold:
# this possibility will probably occur the most frequently
continue
times.append(cum_return)
if cum_return > threshold:
up_threshold += threshold
down_threshold += threshold
else:
up_threshold -= threshold
down_threshold -= threshold
Answered by Reinderien on November 15, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP