Reputation: 187
I am learning classes. The script below, shows the graph correctly using plotly express, but if I integrate it as a method in a class, it doesn't. I show the classes below. With the first one, we import quotes from Yahoo! With the second, we try to represent a graph of the imported normalized prices.
import pandas as pd
import pandas_datareader as pdr
import datetime as dt
from datetime import date
from plotly.offline import iplot
import plotly.express as px
class ImportadorCotizaciones:
def __init__(self):
self.cotizaciones = None
self.start = "2000-1-4"
self.end = date.today()
self.cotizaciones = None
def Importar_cotizaciones(self):
dicc_tickers = {"IBE.MC":"Iberdrola", "TEF.MC":"Telefonica", "^IBEX":"Ibex35" }
dfs = []
nombres = []
for (k,v) in dicc_tickers.items():
self.cotizaciones_de_ticker = pdr.DataReader(k, 'yahoo', self.start, self.end)
self.cotizaciones_de_ticker = self.cotizaciones_de_ticker[["Close"]]
self.cotizaciones_de_ticker = self.cotizaciones_de_ticker.rename(columns={"Close": v})
dfs.append(self.cotizaciones_de_ticker)
dfs = iter(dfs)
self.cotizaciones = next(dfs)
for df_ in dfs:
self.cotizaciones = self.cotizaciones.merge(df_, on='Date')
class Indicadores:
def __init__(self, importador):
self.importador = importador
def dibujar_grafico(self):
self.aux_val_ind = importador.cotizaciones[["Iberdrola", "Ibex35"]].pct_change().dropna()
df = self.aux_val_ind.copy(deep=True)
df['Media'] = df.mean(axis = 1)
# Usando plotly.express
px.line((df + 1).cumprod() ,y=df.columns ,title=f"\nValor de 1€ invertido desde el { importador.start} hasta el {importador.end} ")
importador = ImportadorCotizaciones()
importador.Importar_cotizaciones()
importador.cotizaciones[:3]
indicadores = Indicadores(importador)
indicadores.dibujar_grafico()
The script that works outside the class is:
# Usando plotly.express
from plotly.offline import iplot
import plotly.express as px
start = "2000-1-4"
end = date.today()
aux_val_ind = importador.cotizaciones[["Iberdrola", "Ibex35"]].pct_change().dropna()
df = aux_val_ind.copy(deep=True)
df['Media'] = df.mean(axis = 1)
px.line((df + 1).cumprod() ,y=df.columns ,title=f"\nValor actual de 1€ invertido el {start} ")
Upvotes: 0
Views: 77
Reputation: 31166
Only one issue, you missed to return the figure.
class Indicadores:
def __init__(self, importador):
self.importador = importador
def dibujar_grafico(self):
self.aux_val_ind = importador.cotizaciones[["Iberdrola", "Ibex35"]].pct_change().dropna()
df = self.aux_val_ind.copy(deep=True)
df['Media'] = df.mean(axis = 1)
# Usando plotly.express
return px.line((df + 1).cumprod() ,y=df.columns ,title=f"\nValor de 1€ invertido desde el { importador.start} hasta el {importador.end} ")
Upvotes: 1