-3

I have two curves (supply and demand) and I want to find their intersection point (both, x and y). I was not able to find a simple solution for the mentioned problem. I want my code in the end to print what is the value of X and what is the value of Y.

supply = final['0_y']
demand = final['0_x']
price = final[6]
plt.plot(supply, price)
plt.plot(demand, price)

The main problem and challenge (something wrong) are that I have tried every other method, and every single time I get an empty set/list. Even when I try to visualize the intersection, I also get empty visual.

GRAPH:
enter image description here

Mr. T
  • 11,960
  • 10
  • 32
  • 54
CaptainG
  • 15
  • 5
  • unfortunately no :( I have edited my question and added another complication that makes it complicated – CaptainG Jan 28 '22 at 13:44
  • 2
    Then please provide a sample input (5 data points per curve are enough) that does not work with the approach in the linked question. – Mr. T Jan 28 '22 at 13:50

1 Answers1

0

As the implementation of the duplicate is not straightforward, I will show you how you can adapt it to your case. First, you use pandas series instead of numpy arrays, so we have to convert them. Then, your x- and y-axes are switched, so we have to change their order for the function call:

import pandas as pd          
import matplotlib.pyplot as plt  
import numpy as np 


final = pd.DataFrame({'0_y': [0, 0, 0, 10, 10, 30], 
                      '0_x': [20, 11, 10, 4, 1, 0,], 
                      "6": [-200, 50, 100, 200, 600, 1000]})

supply = final['0_y'].to_numpy()
demand = final['0_x'].to_numpy()
price = final["6"].to_numpy()
plt.plot(supply, price)
plt.plot(demand, price)


def find_roots(x,y):
    s = np.abs(np.diff(np.sign(y))).astype(bool)
    return x[:-1][s] + np.diff(x)[s]/(np.abs(y[1:][s]/y[:-1][s])+1)

z = find_roots(price, supply-demand)
x4z = np.interp(z, price, supply)


plt.scatter(x4z, z, color="red", zorder=3)
plt.title(f"Price is {z[0]} at supply/demand of {x4z[0]}")

plt.show()

Sample output: enter image description here

Mr. T
  • 11,960
  • 10
  • 32
  • 54