For any given date, I am trying to find the previous close value that was 1.2x than the present close value. I made a loop that will check that for every row. However, it is not efficient. The runtime is 45 seconds. How do I make my code more efficient to work with a much larger dataset than this?
Dataset- TSLA or TSLA Daily 5Y Stock Yahoo
df = pd.read_csv(os.getcwd()+"\\TSLA.csv")
# Slicing the dataset
df2 = df[['Date', 'Close']]
irange = np.arange(1, len(df))
for i in irange:
# Dicing first i rows
df3 = df2.head(i)
# Set the target close value that is 1.2x the current close value
targetValue = 1.2 * df3['Close'].tail(1).values[0]
# Check the last 200 days
df4 = df3.tail(200)
df4.set_index('Date', inplace=True)
# Save all the target values in a list
req = df4[df4['Close'] > targetValue]
try:
lent = (req.index.tolist()[-1])
except:
lent = str(9999999)
# Save the last value to the main dataframe
df.at[i,'last_time'] = lent
df.tail(20)