Monday, 2 December 2019

quotopian lecture polyfit

start = '2003-01-01'
end = '2009-02-01'
price = get_pricing('SPY', fields='price', start_date=start, end_date=end)
price.plot()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

x = np.arange(len(price))
order1 = np.polyfit(x, price.values, 1)
order2 = np.polyfit(x, price.values, 2)
order3 = np.polyfit(x, price.values, 3)
order4 = np.polyfit(x, price.values, 4)

print order1
print order2
print order3
print order4

[  2.98372866e-02   9.18866880e+01]
[ -5.51333401e-05   1.14191297e-01   7.03904744e+01]
[ -1.03180489e-07   1.81665882e-04  -3.06824879e-02   8.88317032e+01]
[ -2.56304740e-10   6.81112016e-07  -5.89573938e-04   2.31339274e-01 6.88459783e+01]

f1 = pd.Series(x*order1[0] + order1[1], index=price.index, name='f1')
f2 = pd.Series(np.power(x,2)*order2[0] + x*order2[1] + order2[2], index=price.index, name='f2')
f3 = pd.Series(np.power(x,3)*order3[0] + np.power(x,2)*order3[1] + x*order3[2] + order3[3], index=price.index, name='f3')
f4 = pd.Series(np.power(x,4)*order4[0] + np.power(x,3)*order4[1] + np.power(x,2)*order4[2] + x*order4[3] + order4[4], index=price.index, name='f4')

pd.concat([price, f1, f2, f3, f4], axis=1).plot()


reference:
https://www.geeksforgeeks.org/numpy-power-python/
http://chuanshuoge2.blogspot.com/2019/11/quantopian-lecture-linear-regression.html
https://www.quantopian.com/lectures/the-dangers-of-overfitting

No comments:

Post a Comment