Getting started on plotly. I import from Yahoo, quotes of two values doing:
import pandas as pd
import pandas_datareader as pdr
dicc_tickers = {"Apple":'AAPL', "Google":'GOOG'}
from pandas_datareader import data as pdr
import datetime
def get(tickers, startdate, enddate):
def data(ticker):
return (pdr.DataReader(ticker, 'yahoo' ))
datas = map (data, tickers)
return(pd.concat(datas, keys=tickers, names=['Ticker', 'Date']))
startdate = "2016-1-4"
enddate = "2020-10-30"
tickers = dicc_tickers.values()
cotizaciones = get(tickers, datetime.datetime(2006, 10, 1), datetime.datetime(2012, 1, 1))
datos_yahoo = cotizaciones[['Adj Close']].reset_index().pivot('Date', 'Ticker', 'Adj Close')
df = datos_yahoo.resample('M').mean()
Below I try to present the graphs of the historical evolution of these average monthly prices. I need a date scale on the X axis, executing the following script:
import chart_studio.plotly as ply
import plotly.graph_objs as go
import numpy as np
df = datos_yahoo[["AAPL", "GOOG"]]["2016-1-4":"2020-11-15"].resample('M').mean()
x = df.index.values
y1 = df["AAPL"]
y2 = df["GOOG"]
trace1 = go.Scatter(
x = x,
y = y1,
name = 'AAPL'
)
trace2 = go.Scatter(
x = x,
y = y2,
name = 'GOOG',
yaxis = 'y2'
)
data = [trace1, trace2]
layout = go.Layout(
title = 'Double Y Axis Example',
yaxis = dict(
title = 'AAPL',zeroline=True,
showline = True
),
yaxis2 = dict(
title = 'GOOG',
zeroline = True,
showline = True,
overlaying = 'y',
side = 'right'
)
)
fig = go.Figure(data=data, layout=layout)
iplot(fig)
To do this, I define the variable x: x = df.index.values
But I can't get the date scale to appear on the x axis. How can I get this scale on the chart? I will appreciate your suggestions.
The problem is how you have your variable
x
. It's in a time format that leads toPlotly
confusion when it comes to representing it on the axis in a useful way.I'm going to save myself from putting all the code and I'm going to go to the concrete part, which is when you define your variable
x
Departure:
Simply using
pd.to_datetime()
dePandas
nos changes the format so thatPlotly
it interprets it properly.What we have done is convert the temporal sequence of
datetime64
aTimestamp
Note
It is not that the variable was being represented incorrectly, mathematically speaking the representation was correct, the only thing that represented the abscissa axis in nanoseconds. Thus
1.5*10^18