Homunculus Reticulli
Homunculus Reticulli

Reputation: 68476

How to plot timeseries data in a dataframe using matplotlib

I have loaded some stock price data into a dataframe. I want to quickly plot the close price on Y axis, and date on the X axis.

This is what my dataframe looks like:

    Open    High    Low Close   Adjusted_close  Volume
Date                        
1980-12-11  22.000  22.000  22.000  22.000  0.0308  0
1980-12-12  28.750  28.876  28.750  28.750  0.0395  2093900
1980-12-15  27.250  27.376  27.250  27.250  0.0375  785200
1980-12-16  25.250  25.376  25.250  25.250  0.0350  472000
1980-12-17  25.876  26.000  25.876  25.876  0.0359  385900

When I type df.plot() it plots something that looksl like a histogram.

When I type df.plot('Close') it plots a bunch of squiggly lines.

I have two questions:

  1. How do I quickly plot close price versus date
  2. Assuming I have two other columns ('Buy' and 'Sell') which are boolean flags, in the dataframe, how can I plot the 'Buy' and 'Sell' points using say a green up arrow and a red down arrow on the same plot ?

Upvotes: 0

Views: 1543

Answers (2)

Jitendra
Jitendra

Reputation: 856

I just tried with the same data. I had to draw 02 plots in the same figure and had to add colors based on the new column as shown.


import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

# data wrangling
columns = ['date', 'open', 'high', 'low', 'close', 'adjusted_close', 'volume']
df = pd.read_csv('timeseries.csv', parse_dates=True, names=columns)
#df['date'] = pd.to_datetime(df['date'])
signals = [True, True, False, False, True]
df['signals'] = signals

# plots
plt.plot(df['date'], df['close'])
kcolors = ['green' if s else 'red' for s in df['signals']]
plt.scatter(df['date'], df['close'], c=kcolors)
#rotate label if too long
plt.xticks(rotation=60)
plt.show()

enter image description here

Upvotes: 1

Sebastian Wozny
Sebastian Wozny

Reputation: 17526

What you described works perfectly for me.

import pandas as pd
df = pd.read_clipboard()
df['Close'].plot()

enter image description here Are you sure you converted the index to pandas datetime? if not try

df.index = pd.to_datetime(df.index)

Upvotes: 1

Related Questions