Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to skip empty dates (weekends) in a financial Matplotlib Python graph?
When creating financial charts in Matplotlib, you often need to skip weekends (Saturday and Sunday) to display only business days. This prevents gaps in your time series visualization and provides a cleaner representation of trading data.
Understanding Weekdays in Python
Python's weekday() method returns integers where Monday=0, Tuesday=1, ..., Saturday=5, Sunday=6. To skip weekends, we check if weekday() returns 5 (Saturday) or 6 (Sunday).
Basic Example
Here's how to plot only weekdays while skipping weekends ?
import pandas as pd
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
# Create a DataFrame with dates
df = pd.DataFrame(dict(
time=list(pd.date_range(start="2021-01-01", end="2021-01-15")),
price=[100 + i*2 for i in range(15)] # Sample price data
))
# Plot only weekdays (skip weekends)
weekday_indices = []
weekday_times = []
weekday_prices = []
for i, (time, price) in enumerate(zip(df.time, df.price)):
if time.weekday() in (5, 6): # Skip Saturday (5) and Sunday (6)
continue
else:
weekday_indices.append(len(weekday_times))
weekday_times.append(time)
weekday_prices.append(price)
# Plot the filtered data
plt.plot(weekday_indices, weekday_prices, marker="o", linewidth=2, markersize=8)
plt.title("Financial Data - Weekdays Only")
plt.xlabel("Business Days")
plt.ylabel("Price")
plt.grid(True, alpha=0.3)
plt.show()
Using Pandas Business Days
A more efficient approach is using pandas bdate_range() which automatically generates business day dates ?
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Create business days only (automatically skips weekends)
business_dates = pd.bdate_range(start="2021-01-01", end="2021-01-31")
prices = 100 + np.cumsum(np.random.randn(len(business_dates)) * 2)
plt.figure(figsize=(12, 6))
plt.plot(business_dates, prices, marker="o", linewidth=2, markersize=6)
plt.title("Stock Price - Business Days Only")
plt.xlabel("Date")
plt.ylabel("Price ($)")
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Comparison of Methods
| Method | Pros | Cons |
|---|---|---|
| Manual weekday filtering | Full control over logic | More code, potential for errors |
bdate_range() |
Clean, built-in solution | Less flexibility for custom rules |
| DataFrame filtering | Works with existing data | Requires additional processing |
Advanced Filtering with DataFrame
For existing datasets, you can filter out weekends using boolean indexing ?
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Create sample financial data with all days
all_dates = pd.date_range(start="2021-01-01", end="2021-01-31")
df = pd.DataFrame({
'date': all_dates,
'price': 100 + np.cumsum(np.random.randn(len(all_dates)) * 1.5)
})
# Filter out weekends
weekdays_only = df[df['date'].dt.weekday < 5]
plt.figure(figsize=(12, 6))
plt.plot(weekdays_only['date'], weekdays_only['price'],
marker="s", linewidth=2, markersize=5, color="green")
plt.title("Financial Chart - Weekends Excluded")
plt.xlabel("Date")
plt.ylabel("Price ($)")
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Conclusion
Use pandas.bdate_range() for generating business day sequences, or filter existing data using weekday() < 5. Both methods effectively skip weekends in financial visualizations, providing cleaner and more meaningful charts for trading analysis.
