-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvisualization.py
More file actions
530 lines (446 loc) · 15.6 KB
/
Copy pathvisualization.py
File metadata and controls
530 lines (446 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
"""
OilPriceAPI Visualization Module
Data visualization following Edward Tufte's principles:
- Maximize data-ink ratio
- Remove chartjunk
- Show data variation, not design variation
- Clear labeling and context
- Small multiples for comparisons
"""
import warnings
from datetime import datetime, timedelta
from typing import List, Optional
try:
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.axes import Axes
from matplotlib.figure import Figure
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
try:
import pandas as pd
HAS_PANDAS = True
except ImportError:
HAS_PANDAS = False
class TufteStyle:
"""Tufte-inspired visual style settings."""
# Colors - muted, professional palette
COLORS = {
'primary': '#2E3440', # Dark gray for primary data
'secondary': '#5E81AC', # Muted blue
'accent': '#BF616A', # Muted red for emphasis
'grid': '#E5E9F0', # Very light gray for minimal grid
'text': '#2E3440', # Dark gray for text
'background': '#FFFFFF', # White background
}
# Typography
FONTS = {
'family': 'sans-serif',
'title_size': 14,
'label_size': 10,
'tick_size': 9,
}
# Layout
LAYOUT = {
'figure_width': 10,
'figure_height': 6,
'dpi': 100,
'line_width': 1.5,
'marker_size': 4,
}
@classmethod
def apply(cls, ax: 'Axes') -> None:
"""Apply Tufte style to an axes object."""
if not HAS_MATPLOTLIB:
return
# Remove top and right spines (Tufte box plots)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_linewidth(0.5)
ax.spines['bottom'].set_linewidth(0.5)
# Minimize grid
ax.grid(True, alpha=0.2, linewidth=0.5, color=cls.COLORS['grid'])
ax.set_axisbelow(True)
# Clean tick marks
ax.tick_params(colors=cls.COLORS['text'], labelsize=cls.FONTS['tick_size'])
ax.xaxis.set_tick_params(width=0.5, length=4)
ax.yaxis.set_tick_params(width=0.5, length=4)
class PriceVisualizer:
"""Visualize oil price data following Tufte principles."""
def __init__(self, client):
"""Initialize visualizer with OilPriceAPI client."""
self.client = client
if not HAS_MATPLOTLIB:
warnings.warn(
"matplotlib is required for visualization. "
"Install with: pip install matplotlib",
ImportWarning
)
def plot_price_series(
self,
commodity: str,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
interval: str = "daily",
show_range: bool = True,
annotate_extremes: bool = True
) -> Optional['Figure']:
"""Create a clean time series plot.
Args:
commodity: Commodity code
start_date: Start date for data
end_date: End date for data
interval: Data interval
show_range: Show min/max range band
annotate_extremes: Annotate highest and lowest points
Returns:
matplotlib Figure object
"""
if not HAS_MATPLOTLIB:
raise ImportError("matplotlib required for visualization")
# Fetch data
history = self.client.historical.get(
commodity=commodity,
start_date=start_date,
end_date=end_date,
interval=interval,
per_page=1000
)
if not history.data:
warnings.warn("No data available for visualization")
return None
# Extract data
dates = [p.date for p in history.data]
prices = [p.value for p in history.data]
# Create figure
fig, ax = plt.subplots(
figsize=(TufteStyle.LAYOUT['figure_width'], TufteStyle.LAYOUT['figure_height']),
dpi=TufteStyle.LAYOUT['dpi']
)
# Apply Tufte style
TufteStyle.apply(ax)
# Plot main price line
ax.plot(
dates, prices,
color=TufteStyle.COLORS['primary'],
linewidth=TufteStyle.LAYOUT['line_width'],
label=commodity
)
# Add range band if requested
if show_range and len(prices) > 20:
# Calculate rolling min/max
window = min(20, len(prices) // 5)
rolling_min = pd.Series(prices).rolling(window, center=True).min()
rolling_max = pd.Series(prices).rolling(window, center=True).max()
ax.fill_between(
dates,
rolling_min,
rolling_max,
alpha=0.1,
color=TufteStyle.COLORS['secondary'],
label='Range'
)
# Annotate extremes
if annotate_extremes and len(prices) > 0:
max_idx = prices.index(max(prices))
min_idx = prices.index(min(prices))
# Annotate maximum
ax.annotate(
f'${prices[max_idx]:.2f}',
xy=(dates[max_idx], prices[max_idx]),
xytext=(10, 10),
textcoords='offset points',
fontsize=TufteStyle.FONTS['tick_size'],
color=TufteStyle.COLORS['accent'],
ha='left'
)
# Annotate minimum
ax.annotate(
f'${prices[min_idx]:.2f}',
xy=(dates[min_idx], prices[min_idx]),
xytext=(10, -15),
textcoords='offset points',
fontsize=TufteStyle.FONTS['tick_size'],
color=TufteStyle.COLORS['secondary'],
ha='left'
)
# Labels and title
ax.set_xlabel('Date', fontsize=TufteStyle.FONTS['label_size'])
ax.set_ylabel('Price (USD)', fontsize=TufteStyle.FONTS['label_size'])
ax.set_title(
f'{commodity} Price History',
fontsize=TufteStyle.FONTS['title_size'],
pad=20
)
# Format dates on x-axis
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate(rotation=45, ha='right')
# Add data source note (Tufte principle)
fig.text(
0.99, 0.01,
f'Source: OilPriceAPI | {datetime.now().strftime("%Y-%m-%d")}',
fontsize=7,
color='gray',
ha='right',
va='bottom',
transform=fig.transFigure
)
plt.tight_layout()
return fig
def plot_spread(
self,
commodity1: str,
commodity2: str,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
interval: str = "daily"
) -> Optional['Figure']:
"""Plot price spread between two commodities.
Following Tufte's principle of showing data relationships clearly.
"""
if not HAS_MATPLOTLIB:
raise ImportError("matplotlib required for visualization")
# Fetch data for both commodities
hist1 = self.client.historical.get(
commodity=commodity1,
start_date=start_date,
end_date=end_date,
interval=interval,
per_page=1000
)
hist2 = self.client.historical.get(
commodity=commodity2,
start_date=start_date,
end_date=end_date,
interval=interval,
per_page=1000
)
if not hist1.data or not hist2.data:
warnings.warn("Insufficient data for spread calculation")
return None
# Align dates
dates1 = {p.date.date(): p.value for p in hist1.data}
dates2 = {p.date.date(): p.value for p in hist2.data}
common_dates = sorted(set(dates1.keys()) & set(dates2.keys()))
if not common_dates:
warnings.warn("No overlapping dates for spread calculation")
return None
spreads = [dates1[d] - dates2[d] for d in common_dates]
# Create figure with two subplots
fig, (ax1, ax2) = plt.subplots(
2, 1,
figsize=(TufteStyle.LAYOUT['figure_width'], TufteStyle.LAYOUT['figure_height']),
dpi=TufteStyle.LAYOUT['dpi'],
height_ratios=[2, 1]
)
# Apply Tufte style
TufteStyle.apply(ax1)
TufteStyle.apply(ax2)
# Top plot: Individual prices
ax1.plot(
common_dates,
[dates1[d] for d in common_dates],
color=TufteStyle.COLORS['primary'],
linewidth=TufteStyle.LAYOUT['line_width'],
label=commodity1
)
ax1.plot(
common_dates,
[dates2[d] for d in common_dates],
color=TufteStyle.COLORS['secondary'],
linewidth=TufteStyle.LAYOUT['line_width'],
label=commodity2
)
ax1.set_ylabel('Price (USD)', fontsize=TufteStyle.FONTS['label_size'])
ax1.legend(loc='upper left', frameon=False, fontsize=TufteStyle.FONTS['tick_size'])
ax1.set_title(
f'{commodity1} vs {commodity2}',
fontsize=TufteStyle.FONTS['title_size'],
pad=20
)
# Bottom plot: Spread
ax2.fill_between(
common_dates,
spreads,
0,
where=[s >= 0 for s in spreads],
color=TufteStyle.COLORS['accent'],
alpha=0.3,
label='Positive spread'
)
ax2.fill_between(
common_dates,
spreads,
0,
where=[s < 0 for s in spreads],
color=TufteStyle.COLORS['secondary'],
alpha=0.3,
label='Negative spread'
)
ax2.plot(
common_dates,
spreads,
color=TufteStyle.COLORS['primary'],
linewidth=1
)
ax2.axhline(y=0, color='gray', linewidth=0.5, linestyle='-')
ax2.set_xlabel('Date', fontsize=TufteStyle.FONTS['label_size'])
ax2.set_ylabel('Spread (USD)', fontsize=TufteStyle.FONTS['label_size'])
# Format dates
for ax in [ax1, ax2]:
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate(rotation=45, ha='right')
# Add statistics annotation
mean_spread = np.mean(spreads)
std_spread = np.std(spreads)
ax2.text(
0.02, 0.95,
f'Mean: ${mean_spread:.2f}\nStd: ${std_spread:.2f}',
transform=ax2.transAxes,
fontsize=TufteStyle.FONTS['tick_size'],
verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='white', alpha=0.8, edgecolor='none')
)
# Data source note
fig.text(
0.99, 0.01,
f'Source: OilPriceAPI | {datetime.now().strftime("%Y-%m-%d")}',
fontsize=7,
color='gray',
ha='right',
va='bottom',
transform=fig.transFigure
)
plt.tight_layout()
return fig
def create_sparkline(
self,
commodity: str,
days: int = 30,
width: float = 3,
height: float = 1
) -> Optional['Figure']:
"""Create a Tufte sparkline - data-dense, word-sized graphic.
Perfect for embedding in reports or dashboards.
"""
if not HAS_MATPLOTLIB:
raise ImportError("matplotlib required for visualization")
# Fetch recent data
end_date = datetime.now()
start_date = end_date - timedelta(days=days)
history = self.client.historical.get(
commodity=commodity,
start_date=start_date.isoformat(),
end_date=end_date.isoformat(),
interval="daily"
)
if not history.data:
return None
prices = [p.value for p in history.data]
# Create minimal figure
fig, ax = plt.subplots(figsize=(width, height), dpi=100)
# Remove all axes and labels
ax.axis('off')
# Plot line
x = range(len(prices))
ax.plot(x, prices, color=TufteStyle.COLORS['primary'], linewidth=1)
# Add start and end points
ax.plot(0, prices[0], 'o', color=TufteStyle.COLORS['secondary'], markersize=3)
ax.plot(len(prices)-1, prices[-1], 'o', color=TufteStyle.COLORS['accent'], markersize=3)
# Add min/max markers
min_idx = prices.index(min(prices))
max_idx = prices.index(max(prices))
ax.plot(min_idx, prices[min_idx], 'v', color='gray', markersize=2)
ax.plot(max_idx, prices[max_idx], '^', color='gray', markersize=2)
# Add end value label
ax.text(
len(prices) - 1, prices[-1],
f'${prices[-1]:.1f}',
fontsize=8,
ha='right',
va='bottom'
)
plt.tight_layout(pad=0)
return fig
def create_small_multiples(
self,
commodities: List[str],
days: int = 30,
cols: int = 3
) -> Optional['Figure']:
"""Create Tufte small multiples - multiple similar graphics for comparison.
Allows easy comparison across multiple commodities.
"""
if not HAS_MATPLOTLIB:
raise ImportError("matplotlib required for visualization")
n = len(commodities)
rows = (n + cols - 1) // cols
fig, axes = plt.subplots(
rows, cols,
figsize=(12, 3 * rows),
dpi=100
)
if rows == 1:
axes = [axes]
if cols == 1:
axes = [[ax] for ax in axes]
end_date = datetime.now()
start_date = end_date - timedelta(days=days)
for idx, commodity in enumerate(commodities):
row = idx // cols
col = idx % cols
ax = axes[row][col] if rows > 1 else axes[col]
# Fetch data
history = self.client.historical.get(
commodity=commodity,
start_date=start_date.isoformat(),
end_date=end_date.isoformat(),
interval="daily"
)
if history.data:
dates = [p.date for p in history.data]
prices = [p.value for p in history.data]
# Apply Tufte style
TufteStyle.apply(ax)
# Plot
ax.plot(
dates, prices,
color=TufteStyle.COLORS['primary'],
linewidth=1
)
# Minimal labeling
ax.set_title(commodity, fontsize=10, pad=10)
ax.set_xlabel('')
# Only show y-label on leftmost plots
if col == 0:
ax.set_ylabel('Price (USD)', fontsize=9)
else:
ax.set_ylabel('')
# Rotate x labels
ax.tick_params(axis='x', rotation=45, labelsize=7)
ax.tick_params(axis='y', labelsize=7)
# Remove empty subplots
for idx in range(n, rows * cols):
row = idx // cols
col = idx % cols
ax = axes[row][col] if rows > 1 else axes[col]
ax.axis('off')
# Add overall title and source
fig.suptitle(
f'Commodity Price Comparison ({days} days)',
fontsize=14,
y=1.02
)
fig.text(
0.99, 0.01,
f'Source: OilPriceAPI | {datetime.now().strftime("%Y-%m-%d")}',
fontsize=7,
color='gray',
ha='right',
va='bottom',
transform=fig.transFigure
)
plt.tight_layout()
return fig