I would like to develop a code which add a Series to my DataFrame; the Series should store the lowest value of the Close until a new low is reached. When a new low is reached a new value should appear in the Series. The starting code is:
import yfinance as yf import pandas as pd import numpy as np import matplotlib.pyplot as plt ticker = 'EURUSD=X' df = yf.download(ticker, start='2020-1-1') df['fixed_low'] = ...?
So, for example, if the most recent low of EURUSD is 1.1000, in the column ‘fixed_low’ that value should stay until a new low is reached (let’s say 1.0999). Then, if the asset is still going down, the column should store new low values until a new low will last for some time, and so on. I hope I was clear. Thank you
Advertisement
Answer
import yfinance as yf import numpy as np ticker = 'EURUSD=X' df = yf.download(ticker, start='2021-2-1', end= '2021-3-1') minimum = np.min(df['Close'])#you saved the minimum print('minimum', minimum) df1 = yf.download(ticker, start='2021-3-2', end= '2022-5-1') for i in df1['Close'].values: if i < minimum: minimum = i print('update minimum', minimum)
Two dataframes are created. In the first we find the minimum, in the second we update the minimum value.
ticker = 'EURUSD=X' df = yf.download(ticker, start='2020-1-1') df['fixed_low'] = np.nan low = np.inf for i in range(0, len(df)): if df.loc[df.index[i], 'Low'] < low: low = round(df.loc[df.index[i], 'Low'], 6) df.loc[df.index[i], 'fixed_low'] = low
Output df
Open High Low ... Adj Close Volume fixed_low Date ... 2019-12-31 1.120448 1.124101 1.120072 ... 1.120230 0 1.120072 2020-01-01 1.122083 1.122838 1.115947 ... 1.122083 0 1.115947 2020-01-02 1.121894 1.122712 1.116682 ... 1.122083 0 1.115947 2020-01-03 1.117081 1.118068 1.112570 ... 1.117144 0 1.112570 2020-01-06 1.116246 1.120825 1.115810 ... 1.116196 0 1.112570 ... ... ... ... ... ... ... ... 2022-05-06 1.053974 1.059839 1.048537 ... 1.053974 0 1.047285
Before the loop, I set the value of the low variable to the largest. If the current minimum is less than low, then an update occurs. df[‘fixed_low’] set all values to nan first.