I have the following code that is intended to look at the “delta” values and where they are negative the relevant subplot background color should either become red or green:
def chartit():
global strikes
chartlist = []
src = r'C:UsersUserPycharmProjectsactivetickhttp v3spyvalue.txt'
dst = r'C:UsersUserPycharmProjectspythonProject6spyvalue.txt'
shutil.copyfile(src, dst)
file = open("spyvalue.txt", "r")
spyprice = file.readline()
spyprice = round(float(spyprice), 0)
print("spy price is ", spyprice)
upper = int(spyprice) + 3
lower = int(spyprice) - 3
for item in strikes:
if float(item) <= upper and float(item) >= lower:
chartlist.append(item)
chartlist.sort()
print("chart list is ", chartlist)
count = 1
apds = []
resampled_data = {}
for item in chartlist:
file = open(str(item) + ".txt", "r")
df = pd.read_csv(str(item) + ".txt")
df['time'] = pd.to_datetime(df['time'])
df = df.set_index('time')
resampled = df['delta'].resample('s').ohlc()
resampled_data[item] = resampled
apds.append(mpf.make_addplot(resampled,type="candle",panel=count,ylabel=str(item)))
count = count + 1
fig, axlist = mpf.plot(resampled, addplot=apds,ylabel="SPY", returnfig=True)
for i in range(1, len(axlist)): # Start from 1 to skip the main plot
if i-1 < len(chartlist): # Ensure we don't exceed the chartlist length
strike = chartlist[i-1]
print(strike)
set_background_color(axlist[i], resampled_data[strike]['close'])
#for x in range(0,count):
# for strike in chartlist:
# set_background_color(axlist[count], resampled_data[strike]['close'])
#formatter = FuncFormatter(custom_formatter)
#for ax in axlist:
# ax.yaxis.set_major_formatter(formatter)
mpf.show()
def set_background_color(ax, series):
# Find the first non-NaN value in the series to set the initial color
if series.dropna().iloc[0] >= 0:
initial_color = 'lightgreen'
print("green")
else:
initial_color = 'red'
print("red")
ax.set_facecolor(initial_color)
def custom_formatter(x, pos):
formatted = f'{x:.1e}'
# Replace 'e' with 'x10^' and ensure the exponent is only 1 digit if possible
base, exponent = formatted.split('e')
exponent = int(exponent)
return f'{base}x10^{exponent}'
I want each -ve delta to be red in background and position to be green. But instead I get this:
New contributor
Daniel Khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.