0

Let's imagine I get the stock market of Tesla and Microsoft and I want to print the close price for both.

import pandas as pd
import yfinance as yf

start = '2010-01-01'
end = '2020-12-31'
tesla = yf.download('TSLA', start=start, end=end)
microsoft = yf.download('MSFT', start=start, end=end)

I can easily plot each on its own plot:

microsoft.Close.plot()

Or use axes to hack them on the same plot, but I don't get the legend:

ax = microsoft.Close.plot()
ax = tesla.Close.plot(ax=ax)

Or I can merge my two DataFrame

# Ugly but elegant...
frames = []
for u in ['microsoft', 'tesla']:
    df = globals()[u]
    df.columns = pd.MultiIndex.from_arrays([[u] * len(df.columns), list(df.columns.values)])
    frames.append(df)
df = pd.merge(*frames, on=["Date"])

df[[('tesla', 'Open'), ('microsoft', 'Open')]].plot()

The latter solution seems better since I am simply plotting whatever I want, but the merge process seems cumbersome.

Any better alternative?

1 Answer 1

1

You can download the data from both stocks directly from yfinance and plot the open data

import pandas as pd
import yfinance as yf

start = '2010-01-01'
end = '2020-12-31'
stocks = ['TSLA', 'MSFT']

data = yf.download(stocks, start=start, end=end)
data['Open'].plot()
Sign up to request clarification or add additional context in comments.

2 Comments

Well, you kind of answer my question, but this is an X-Y answer :( I took stocks as an example, this is not my real use case...
Oh, ok, I did not understand that at first. If the issue is just the legend, for first case you can just use import matplotlib.pyplot as plt and plt.legend(['MSFT', 'TSLA']) to add the legend in the plot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.