Created
November 30, 2017 22:36
-
-
Save memonkey01/d203682e1b7c0939209e704aed7033ee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| """ | |
| Calculando Beta | |
| Autor: Guillermo Izquierdo | |
| Este código es para fines educativos | |
| """ | |
| import matplotlib | |
| import pandas_datareader as pdr | |
| import matplotlib.pyplot as plt | |
| import statsmodels.api as sm | |
| import datetime | |
| import numpy as np | |
| matplotlib.style.use('ggplot') | |
| #Definimos una fecha de análisis | |
| end = datetime.datetime(2017,11,29).isoformat() | |
| start = datetime.datetime(2017,2,1).isoformat() | |
| index = pdr.get_data_yahoo('^DJI', start=start, end=end) | |
| index_close = index['Close'] #Seleccionamos la columna de cierre | |
| stock = pdr.get_data_yahoo('TSLA', start=start, end=end) | |
| stock_close = stock['Close'] #Seleccionamos la columna de cierre | |
| #Calculamos los retornos diarios | |
| index = index_close.pct_change().dropna().values | |
| stock = stock_close.pct_change().dropna().values | |
| #Definimos el modelo usando stats models | |
| x = sm.add_constant(index) | |
| model = sm.OLS(stock,x) | |
| results = model.fit() | |
| beta = results.params[1] | |
| alpha = results.params[0] | |
| vector = stock * beta + alpha | |
| #Validamos el modelo usando polifit de numpy | |
| z = np.polyfit(index, stock, 1) | |
| #Imprimimos los resultados | |
| print(results.summary()) | |
| print(z) | |
| print('La Beta de nuestro modelo es:', beta) | |
| #Graficamos nuestro modelo de regresión por OLS | |
| plt.figure() | |
| plt.scatter(stock, index, color='r') | |
| plt.plot(stock, vector, color='b') | |
| plt.title('Beta') | |
| plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment