Here's a Python demo program that creates an efficient frontier visualization using tkinter with a motif-style GUI:
import tkinter as tk
from tkinter import ttk
import math
import random
class EfficientFrontierApp:
def __init__(self, root):
self.root = root
self.root.title("Efficient Frontier Visualization")
self.root.geometry("800x600")
# Use motif style
try:
self.root.tk.call('tk_setPalette', 'grey85')
except:
pass
# Mock data for 3 indices
self.generate_mock_data()
# Create GUI
self.create_widgets()
# Initial plot
self.plot_frontier()
def generate_mock_data(self):
"""Generate mock return/volatility data for 3 indices"""
random.seed(42) # For reproducible results
# Index 1: Conservative (low vol, low return)
self.index1_data = []
for _ in range(50):
volatility = random.uniform(0.05, 0.15)
returns = random.uniform(0.03, 0.08) + volatility * 0.3
self.index1_data.append((volatility, returns))
# Index 2: Moderate (medium vol, medium return)
self.index2_data = []
for _ in range(50):
volatility = random.uniform(0.10, 0.25)
returns = random.uniform(0.06, 0.12) + volatility * 0.4
self.index2_data.append((volatility, returns))
# Index 3: Aggressive (high vol, high return)
self.index3_data = []
for _ in range(50):
volatility = random.uniform(0.20, 0.40)
returns = random.uniform(0.08, 0.18) + volatility * 0.3
self.index3_data.append((volatility, returns))
def create_widgets(self):
"""Create the GUI widgets"""
# Main frame
main_frame = tk.Frame(self.root, relief=tk.RAISED, bd=2)
main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Control panel
control_frame = tk.Frame(main_frame, relief=tk.SUNKEN, bd=2)
control_frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
tk.Label(control_frame, text="Efficient Frontier Controls",
font=("Arial", 12, "bold")).pack(pady=5)
# Checkboxes for indices
self.show_index1 = tk.BooleanVar(value=True)
self.show_index2 = tk.BooleanVar(value=True)
self.show_index3 = tk.BooleanVar(value=True)
checkbox_frame = tk.Frame(control_frame)
checkbox_frame.pack(pady=5)
tk.Checkbutton(checkbox_frame, text="Conservative Index",
variable=self.show_index1, command=self.plot_frontier,
relief=tk.RAISED, bd=1).pack(side=tk.LEFT, padx=10)
tk.Checkbutton(checkbox_frame, text="Moderate Index",
variable=self.show_index2, command=self.plot_frontier,
relief=tk.RAISED, bd=1).pack(side=tk.LEFT, padx=10)
tk.Checkbutton(checkbox_frame, text="Aggressive Index",
variable=self.show_index3, command=self.plot_frontier,
relief=tk.RAISED, bd=1).pack(side=tk.LEFT, padx=10)
# Canvas for plotting
self.canvas = tk.Canvas(main_frame, bg='white', relief=tk.SUNKEN, bd=2)
self.canvas.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Bind resize event
self.canvas.bind('<Configure>', self.on_canvas_resize)
def on_canvas_resize(self, event):
"""Handle canvas resize"""
self.plot_frontier()
def plot_frontier(self):
"""Plot the efficient frontier and data points"""
self.canvas.delete("all")
# Get canvas dimensions
width = self.canvas.winfo_width()
height = self.canvas.winfo_height()
if width <= 1 or height <= 1:
return
# Margins
margin_left = 80
margin_right = 40
margin_top = 40
margin_bottom = 60
plot_width = width - margin_left - margin_right
plot_height = height - margin_top - margin_bottom
if plot_width <= 0 or plot_height <= 0:
return
# Determine data ranges
all_data = []
if self.show_index1.get():
all_data.extend(self.index1_data)
if self.show_index2.get():
all_data.extend(self.index2_data)
if self.show_index3.get():
all_data.extend(self.index3_data)
if not all_data:
return
min_vol = min(point[0] for point in all_data)
max_vol = max(point[0] for point in all_data)
min_ret = min(point[1] for point in all_data)
max_ret = max(point[1] for point in all_data)
# Add some padding
vol_range = max_vol - min_vol
ret_range = max_ret - min_ret
min_vol -= vol_range * 0.1
max_vol += vol_range * 0.1
min_ret -= ret_range * 0.1
max_ret += ret_range * 0.1
# Helper functions for coordinate conversion
def vol_to_x(vol):
return margin_left + (vol - min_vol) / (max_vol - min_vol) * plot_width
def ret_to_y(ret):
return margin_top + (1 - (ret - min_ret) / (max_ret - min_ret)) * plot_height
# Draw axes
self.canvas.create_line(margin_left, margin_top + plot_height,
margin_left + plot_width, margin_top + plot_height,
width=2, fill='black')
self.canvas.create_line(margin_left, margin_top,
margin_left, margin_top + plot_height,
width=2, fill='black')
# Draw grid and labels
for i in range(6):
# Vertical grid lines (volatility)
vol = min_vol + (max_vol - min_vol) * i / 5
x = vol_to_x(vol)
self.canvas.create_line(x, margin_top, x, margin_top + plot_height,
fill='lightgray', dash=(2, 2))
self.canvas.create_text(x, margin_top + plot_height + 20,
text=f"{vol:.1%}", anchor='n')
# Horizontal grid lines (returns)
ret = min_ret + (max_ret - min_ret) * i / 5
y = ret_to_y(ret)
self.canvas.create_line(margin_left, y, margin_left + plot_width, y,
fill='lightgray', dash=(2, 2))
self.canvas.create_text(margin_left - 10, y,
text=f"{ret:.1%}", anchor='e')
# Axis labels
self.canvas.create_text(margin_left + plot_width // 2, height - 20,
text="Volatility (Annualized)", anchor='center',
font=("Arial", 10, "bold"))
# Rotate y-axis label (simulate rotation with positioning)
self.canvas.create_text(20, margin_top + plot_height // 2,
text="Returns", anchor='center',
font=("Arial", 10, "bold"))
self.canvas.create_text(20, margin_top + plot_height // 2 + 15,
text="(Annualized)", anchor='center',
font=("Arial", 10, "bold"))
# Plot data points
colors = ['blue', 'red', 'green']
labels = ['Conservative', 'Moderate', 'Aggressive']
datasets = [self.index1_data, self.index2_data, self.index3_data]
show_flags = [self.show_index1.get(), self.show_index2.get(), self.show_index3.get()]
for i, (data, color, label, show) in enumerate(zip(datasets, colors, labels, show_flags)):
if not show:
continue
for vol, ret in data:
x = vol_to_x(vol)
y = ret_to_y(ret)
self.canvas.create_oval(x-2, y-2, x+2, y+2, fill=color, outline=color)
# Draw efficient frontier curve (simplified)
if all_data:
# Create a simple efficient frontier by connecting the upper envelope
frontier_points = []
vol_steps = [min_vol + (max_vol - min_vol) * i / 50 for i in range(51)]
for vol in vol_steps:
# Find the maximum return for this volatility level (simplified)
nearby_points = [point for point in all_data
if abs(point[0] - vol) <= (max_vol - min_vol) * 0.1]
if nearby_points:
max_return = max(point[1] for point in nearby_points)
frontier_points.append((vol, max_return))
# Draw the frontier curve
if len(frontier_points) > 1:
coords = []
for vol, ret in frontier_points:
coords.extend([vol_to_x(vol), ret_to_y(ret)])
if len(coords) >= 4:
self.canvas.create_line(coords, fill='darkred', width=3, smooth=True)
# Legend
legend_x = margin_left + plot_width - 150
legend_y = margin_top + 20
self.canvas.create_rectangle(legend_x - 10, legend_y - 10,
legend_x + 140, legend_y + 80,
fill='white', outline='black')
for i, (color, label, show) in enumerate(zip(colors, labels, show_flags)):
if show:
y_pos = legend_y + i * 20
self.canvas.create_oval(legend_x, y_pos, legend_x + 8, y_pos + 8,
fill=color, outline=color)
self.canvas.create_text(legend_x + 15, y_pos + 4, text=label,
anchor='w', font=("Arial", 9))
def main():
root = tk.Tk()
app = EfficientFrontierApp(root)
root.mainloop()
if __name__ == "__main__":
main()
This program creates a complete efficient frontier visualization with the following features:
Key Components:
- Motif-style GUI with raised/sunken borders and grey color scheme
- Three mock datasets representing different risk profiles (Conservative, Moderate, Aggressive)
- Interactive checkboxes to show/hide different indices
- Canvas-based plotting with proper scaling and grid lines
- Simplified efficient frontier curve drawn as the upper envelope
- Legend and axis labels
Features:
- Responsive design that redraws when the window is resized
- Proper coordinate transformation from data space to screen space
- Grid lines and percentage formatting for both axes
- Color-coded scatter points for each index
- Smooth curve drawing for the efficient frontier
The mock data generates realistic-looking return/volatility relationships where higher volatility generally corresponds to higher potential returns, which is typical for financial data. The efficient frontier is simplified but demonstrates the concept of the optimal risk-return trade-off.