# --------------------------------
# ----- Variables del modelo -----
# --------------------------------
ACCION = 'AAPL'
FECHA_INICIO = '2019-01-01'
FECHA_FINAL = '2019-01-30'
# Importaciones
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt
import pandas as pd
from pandas_datareader.data import DataReader
%matplotlib inline
# Cargamos el dataset
dataframe = DataReader(
ACCION,
data_source='yahoo',
start=FECHA_INICIO,
end=FECHA_FINAL
)
dataframe["Date"] = dataframe.index
dataframe.head()
# Formateamos los datos
df = pd.DataFrame({
"open": dataframe['Open'],
"volume": dataframe['Volume'],
"high": dataframe['High'],
"low": dataframe['Low'],
"close": dataframe['Close'],
"date": dataframe['Date'].astype(str),
"adjclose": dataframe['Adj Close'],
})
df.head()
def get_data(df):
data = df.copy()
data['date'] = data['date'].str.split('-').str[2]
data['date'] = pd.to_numeric(data['date'])
return [ data['date'].tolist(), data['close'].tolist() ] # Convertimos la serie a una lista
dates, prices = get_data(df)
print(dates, prices)
def predict_prices(dates, prices, x):
dates = np.reshape(dates,(len(dates), 1)) # Convertimos a 1 dimensión
x = np.reshape(x,(len(x), 1))
svr_lin = SVR(kernel='linear', C=1e3)
svr_poly = SVR(kernel='poly', C=1e3, degree=2)
svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)
# Llenamos con los datos los modelos de regresión
svr_lin .fit(dates, prices)
svr_poly.fit(dates, prices)
svr_rbf.fit(dates, prices)
plt.scatter(dates, prices, c='k', label='Data')
plt.plot(dates, svr_lin.predict(dates), c='g', label='Linear model')
plt.plot(dates, svr_rbf.predict(dates), c='r', label='RBF model')
plt.plot(dates, svr_poly.predict(dates), c='b', label='Polynomial model')
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Support Vector Regression')
plt.legend()
plt.show()
return svr_rbf.predict(x)[0], svr_lin.predict(x)[0], svr_poly.predict(x)[0]
predicted_price = predict_prices(dates, prices, [31])
predicted_price
# -------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------