3
\$\begingroup\$

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

enter image description here

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

\$\endgroup\$
0
\$\begingroup\$

else-after-continue

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
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.