benito.cano
benito.cano

Reputation: 857

How to find all the points in time series data were new lows were made?

So I have a set of data, which is AMD stock prices and the code looks like the following:

import pandas as pd
import pandas_datareader as web
import datetime as dt

#get stock prices
start = dt.datetime(2017, 1, 1)
end = dt.datetime(2020, 1, 1)
d = web.DataReader('AMD', 'yahoo', start, end)

So know my question is, what code would be able to find out every time the stock ( so in other words d['Adj Close']), made a new 52 week low. So then you would be able to print the price of the stock everytime this happened. Thank You

Upvotes: 1

Views: 588

Answers (1)

zabop
zabop

Reputation: 7852

# import packages, seed numpy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.seed=42

Generate mock data

Timestamps and price data as list:

timestamps = ['timestamp'+str(x) for x in range(20)]
price = [np.random.normal(100,10) for _ in range(20)]

Put them to a Pandas dataframe:

df = pd.DataFrame({'timestamps':timestamps,'price':price})

Look for lows

Let's define window. Every time the code considers a datapoint, it will consider window-many datapoints before it (not including itself).

window=3

Iterate through price, checking if the current price is the lower than any of the window-many prices before. Save the indices of those datapoints for which this is True:

indices=[]
for index, row in enumerate(df.iterrows()):
    if index >= window:
        if all(df.loc[index,'price'] < each for each in df[index-window:index]['price'].values):
            indices.append(index)

Or, if you prefer list comprehensions:

indices = [index for index, row in enumerate(df.iterrows()) if index>=window and all(df.loc[index,'price'] < each for each in df[index-window:index]['price'].values)]

Check results

Let's plot the data & our findings to make sure it is right. We will plot the lows as vertical lines on our plot.

df.plot()
for index in indices:
    plt.axvline(index,c='r')

Resulting in:

enter image description here

Which is what we have expected.

Upvotes: 1

Related Questions