0

I have a dataframe dictionary labelled as data : which holds information about stocks and their pricing/volumes, etc...

That I would like to iterate through and plot all the keys and specific values. I'm upgrading the original program that I built, which only works on one stock. I would like to take it to the next level by giving my program a list of stocks to work with, in this case, the list of stocks is called tickers = ["LRCX", "FB", "COF"]

Below, is how my original program plots for only one stock (AKA one dataframe).

 f, (ax1, ax2) = plt.subplots(1, 2, figsize=(14,5))
ax1.plot(dte_df["date"], dte_df["Close"])
ax1.set_xlabel("Date", fontsize=12)
ax1.set_ylabel("Stock Price")
ax1.set_title(f"{ticker} Close Price History")

# first Subplot (layer two)
ax1.plot(dte_df["date"], dte_df["High"], color="green")
ax1.set_xlabel("Date", fontsize=12)
ax1.set_ylabel("Stock Price")
ax1.set_title(f"{ticker} High Price History")

# first Subplot (layer three)
ax1.plot(dte_df["date"], dte_df["Low"], color="red")
ax1.set_xlabel("Date", fontsize=12)
ax1.set_ylabel("Stock Price")
ax1.set_title(f"{ticker} Low Price History")

# Second Subplot
ax2.plot(dte_df["date"], dte_df["Volume"], color="orange")
ax2.set_xlabel("Date", fontsize=12)
ax2.set_ylabel("Stock Price")
ax2.set_title(f"{ticker} Volume History")
plt.show()

The code above has two subplots. Daily stock price (high, low, close) onto one plot, and then the stock volume on the other. I'm trying to replicate this code but for a dictionary looping over the keys, instead of a dataframe with only one stock. I have never had to deal with dictionaries in such capacity, I greatly appreciate any help and guidance in advance,

Cheers!

1 Answer 1

1

This is more a pandas question than matplotlib, but anyway.

There are several ways to go about iterating through your dataframe.

if you have a list of columns names, then you can simply use a for-loop:

l0 = ["L1",'L2']
l1 = ["A1",'A2','A3']

df = pd.DataFrame(np.random.random(size=(10,6)))
df.columns = pd.MultiIndex.from_product([l0,l1])

display(df)

for l in l0:
    print('==== {:s} ====='.format(l))
    display(df.xs(l,axis=1))

if you want to be more general, you can use groupby and iterate of the result:

for (l,temp_df) in df.groupby(level=0, axis=1):
    print('==== {:s} ===='.format(l))
    temp_df = temp_df.droplevel(level=0, axis=1)
    display(temp_df)
Sign up to request clarification or add additional context in comments.

1 Comment

I'm a little confused, I have set up my dataframe dictionary, can I not use my format to plot the graphs which I mentioned above? Or do I need to circle back and re-arrange my data. Thank you kindly!

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.