The code below solves the following task
Find the maximum price change over any 1 to 5 day rolling window, over a 1000 day period.
To be clear "any 1 to 5 day rolling window" means t[i:i + j]
where j
can range from 1 to 5. Rather than t[i:i + 5]
if it were just "any 5 day rolling window".
I used NumPy native functions to do this. But I've used a for-loop for the inner iteration.
import numpy as np
import numpy.random as npr
prices = npr.random([1000,1])*1000
max_array = np.zeros([(prices.size-5),1])
for index, elem in np.ndenumerate(prices[:-5,:]):
local_max = 0.0
for i in range(1,6,1):
price_return = prices[(index[0] + i),0] / elem
local_max = max(local_max, price_return)
max_array[index[0]] = local_max
global_max = np.amax(max_array)
Can I somehow eliminate the inner for loop and use NumPy vectorization instead?
I also don't particularly like using "index[0]" to extract the actual index of the current loop from the tuple object that is returned into the variable "index" via the call:
for index, elem in np.ndenumerate(prices[:-5,:]):