Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Convexity of price curve - curve fitting or non-linear regression

Hi All,

This is a newbie question, please be indulgent.

I'm looking to fit the price of a security to a simple quadratic in time model:

Pt=alpha+beta*t+gamma*t^2

what i'm looking for is the gamma value. This will enable me to know if the price is convex or not. I want to test if the behavior of prices is somewhat different depending on this indicator.

However, i quite sadly failed to implement this logic in my Notebook coding

from scipy.optimize import curve_fit  
import statsmodels.formula.api as sm

PGJ = get_pricing(  
    assets,  
    fields='close_price', #modify to price, open_price, high, low or volume to change the field  
    start_date='2015-01-01', #customize your pricing date range  
    end_date = '2016-06-01',  
    frequency='daily', #change to daily for daily pricing  
)

# statsmodels.formula.api fails  
data = {"C":PGJ.values, "t":PGJ.index.values}  
model = sm.ols(formula = 'a ~ np.power(t, 2) + t ', data = data).fit()


#  scipy.optimize import fails  
def func(x, alpha,beta,gamma):  
  return gamma*np.power(x, 2) + beta*x+gamma

popt, pcov = curve_fit(func, PGJ.index.values, PGJ.values,p0=(1,1,1))  

I'm pretty much at a dead end... Has anyone please tried and succeeded to get this data ?

Thank you for your kind assistance

3 responses

hi all,

Got a nice answer from Lotanna Ezenwa of quantopian. package scipy.optimize has been made available


def func1(x, gamma,beta,alpha):  
  return gamma*np.power(x, 2) + beta*x + alpha

#PGJ.values[:,0]

length_values=len(np.array(PGJ.values[:,0]))  
arr=np.array([0.0])  
for i in range(1,length_values):  
    arr=np.append(arr,(1.0/length_values)*i)

popt, pcov = curve_fit(func1, arr, np.array(PGJ.values[:,0]))  

this ugly code results in the following result:

Curve= 20.08963115.t^2 + -27.69074113.t+ 39.13609521

Why fit something driven by the whim and fund flow of the masses, into some elegant but useless curve?

Because of behvioral bias my friend. as you should have guessed :-)