forked from heartlife16/Python-Class-Portfolio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_application.py
More file actions
455 lines (376 loc) · 19.3 KB
/
main_application.py
File metadata and controls
455 lines (376 loc) · 19.3 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
"""
Main Application and Demonstration Script
Enhanced Portfolio Management System - Complete Integration
"""
import os
import sys
from datetime import datetime, timedelta
import random
import json
# Import all our modules
from enhanced_portfolio_system import (
Investment, Stock, Bond, Portfolio, Investor,
InvestmentType, PortfolioAnalytics
)
from database_file_manager import DatabaseManager, FileManager
from visualization_reporting import PortfolioVisualizer, ReportGenerator
class PortfolioManagementApp:
"""
Main application class that integrates all functionality
Demonstrates comprehensive use of all programming concepts
"""
def __init__(self, base_path: str = None):
if base_path is None:
base_path = os.path.join(os.path.expanduser("~"), "portfolio_data")
self.base_path = base_path
os.makedirs(base_path, exist_ok=True)
self.db_manager = DatabaseManager("portfolio_app.db")
# Use relative paths (folders will be created in your project directory)
self.file_manager = FileManager("app_data")
self.visualizer = PortfolioVisualizer("app_charts")
self.report_generator = ReportGenerator("app_reports")
self.investors = {} # Dictionary to store investors
# If you want to use the user's home directory instead, uncomment below:
# base_path = os.path.join(os.path.expanduser("~"), "portfolio_data")
# self.file_manager = FileManager(os.path.join(base_path, "app_data"))
# self.visualizer = PortfolioVisualizer(os.path.join(base_path, "app_charts"))
# self.report_generator = ReportGenerator(os.path.join(base_path, "app_reports"))
def create_sample_data(self):
"""
Create comprehensive sample data for demonstration
Uses loops, dictionaries, lists extensively
"""
print("Creating sample data...")
# Sample stock data with various sectors
sample_stocks = [
{"symbol": "AAPL", "sector": "Technology", "dividend": 0.5},
{"symbol": "GOOGL", "sector": "Technology", "dividend": 0.0},
{"symbol": "MSFT", "sector": "Technology", "dividend": 2.1},
{"symbol": "JPM", "sector": "Financial", "dividend": 2.5},
{"symbol": "BAC", "sector": "Financial", "dividend": 2.8},
{"symbol": "JNJ", "sector": "Healthcare", "dividend": 2.8},
{"symbol": "PFE", "sector": "Healthcare", "dividend": 3.2},
{"symbol": "XOM", "sector": "Energy", "dividend": 5.5},
{"symbol": "CVX", "sector": "Energy", "dividend": 3.8},
{"symbol": "WMT", "sector": "Consumer", "dividend": 1.6},
]
# Sample bond data
sample_bonds = [
{"symbol": "US10Y", "coupon": 4.5, "maturity": "03/10/2034", "rating": "AAA"},
{"symbol": "CORP1", "coupon": 5.2, "maturity": "02/15/2029", "rating": "BBB"},
{"symbol": "MUNI1", "coupon": 3.8, "maturity": "06/01/2031", "rating": "AA"},
{"symbol": "CORP2", "coupon": 6.1, "maturity": "12/15/2027", "rating": "BB"},
]
# Create multiple investors with different portfolios
investors_data = [
{
"id": "INV001", "name": "Alice Johnson", "email": "alice@email.com",
"phone": "555-0101", "address": "123 Main St, New York, NY"
},
{
"id": "INV002", "name": "Bob Smith", "email": "bob@email.com",
"phone": "555-0102", "address": "456 Oak Ave, Los Angeles, CA"
},
{
"id": "INV003", "name": "Carol Davis", "email": "carol@email.com",
"phone": "555-0103", "address": "789 Pine Rd, Chicago, IL"
}
]
# Create investors and portfolios using loops
for inv_data in investors_data:
investor = Investor(
inv_data["id"], inv_data["name"], inv_data["email"],
inv_data["phone"], inv_data["address"]
)
# Create multiple portfolios for each investor
portfolio_types = ["Growth", "Income", "Balanced"]
for i, port_type in enumerate(portfolio_types):
portfolio_id = f"{inv_data['id']}_PORT{i+1}"
portfolio = investor.create_portfolio(
portfolio_id, f"{port_type} Portfolio",
f"{port_type} focused investment strategy"
)
# Add random investments to each portfolio
self._populate_portfolio_with_random_data(
portfolio, sample_stocks, sample_bonds, port_type
)
# Store investor in our dictionary
self.investors[investor.investor_id] = investor
# Save to database
self.db_manager.save_investor(investor)
for portfolio in investor.portfolios.values():
self.db_manager.save_portfolio(portfolio, investor.investor_id)
for investment in portfolio.investments.values():
self.db_manager.save_investment(investment, portfolio.portfolio_id)
print(f"Created {len(self.investors)} investors with sample data")
def _populate_portfolio_with_random_data(self, portfolio: Portfolio,
stocks_data: list, bonds_data: list,
portfolio_type: str):
"""
Populate portfolio with random investments based on type
Demonstrates extensive use of loops and conditional logic
"""
# Different allocation strategies based on portfolio type
allocation_strategies = {
"Growth": {"stocks": 0.8, "bonds": 0.2, "stock_count": 6, "bond_count": 2},
"Income": {"stocks": 0.4, "bonds": 0.6, "stock_count": 4, "bond_count": 4},
"Balanced": {"stocks": 0.6, "bonds": 0.4, "stock_count": 5, "bond_count": 3}
}
strategy = allocation_strategies[portfolio_type]
# Add stocks
selected_stocks = random.sample(stocks_data, strategy["stock_count"])
for i, stock_data in enumerate(selected_stocks):
# Generate random but realistic data
shares = random.randint(50, 200)
purchase_price = random.uniform(50, 300)
# Simulate price changes (-20% to +40%)
price_change = random.uniform(-0.2, 0.4)
current_value = purchase_price * (1 + price_change)
# Random purchase date in the last 2 years
days_ago = random.randint(30, 730)
purchase_date = (datetime.now() - timedelta(days=days_ago)).strftime("%m/%d/%Y")
stock = Stock(
f"STK_{portfolio.portfolio_id}_{i+1:03d}",
stock_data["symbol"], shares, purchase_price, current_value,
purchase_date, stock_data["sector"], stock_data["dividend"]
)
portfolio.add_investment(stock)
# Add bonds
selected_bonds = random.sample(bonds_data, strategy["bond_count"])
for i, bond_data in enumerate(selected_bonds):
shares = random.randint(5, 20) # Bonds typically in smaller quantities
purchase_price = random.uniform(950, 1050) # Around par value
# Bonds are more stable, smaller price changes
price_change = random.uniform(-0.05, 0.05)
current_value = purchase_price * (1 + price_change)
days_ago = random.randint(30, 730)
purchase_date = (datetime.now() - timedelta(days=days_ago)).strftime("%m/%d/%Y")
bond = Bond(
f"BND_{portfolio.portfolio_id}_{i+1:03d}",
bond_data["symbol"], shares, purchase_price, current_value,
purchase_date, bond_data["coupon"], bond_data["maturity"],
bond_data["rating"]
)
portfolio.add_investment(bond)
def demonstrate_calculations(self):
"""
Demonstrate the earnings/loss calculations with the specified formulas
"""
print("\\nDemonstrating Earnings/Loss Calculations")
print("=" * 50)
# Get first investor for demonstration
investor = list(self.investors.values())[0]
portfolio = list(investor.portfolios.values())[0]
print(f"Portfolio: {portfolio.name}")
print(f"Owner: {investor.name}")
print()
print("Formula 1: Earnings/Loss Calculation")
print("(current_value - purchase_price) × number_of_shares")
print("-" * 60)
print(f"{'Symbol':<8}{'Shares':<8}{'Purchase':<12}{'Current':<12}{'Earnings/Loss':<15}")
print("-" * 60)
total_earnings = 0
for investment in portfolio.investments.values():
earnings = investment.earnings_loss()
total_earnings += earnings
print(f"{investment.symbol:<8}{investment.shares:<8}"
f"${investment.purchase_price:<11.2f}${investment.current_value:<11.2f}"
f"${earnings:<14.2f}")
print("-" * 60)
print(f"{'TOTAL':<36}${total_earnings:<14.2f}")
print()
print("Formula 2: Yearly Earnings/Loss Rate Calculation")
print("((((current_value - purchase_price) / purchase_price) / (current_date - purchase_date))) × 100")
print("-" * 80)
print(f"{'Symbol':<8}{'Purchase Date':<15}{'Days Held':<12}{'Price Change %':<15}{'Yearly Rate %':<15}")
print("-" * 80)
current_date = datetime.now()
for investment in portfolio.investments.values():
purchase_date = datetime.strptime(investment.purchase_date, "%m/%d/%Y")
days_held = (current_date - purchase_date).days
price_change_pct = ((investment.current_value - investment.purchase_price) /
investment.purchase_price) * 100
yearly_rate = investment.yearly_earnings_loss_rate()
print(f"{investment.symbol:<8}{investment.purchase_date:<15}{days_held:<12}"
f"{price_change_pct:<14.2f}%{yearly_rate:<14.2f}%")
print("-" * 80)
def demonstrate_data_structures(self):
"""
Demonstrate extensive use of dictionaries, lists, and loops
"""
print("\\nDemonstrating Data Structures Usage")
print("=" * 40)
# Dictionary comprehension for sector analysis
all_investments = []
for investor in self.investors.values():
for portfolio in investor.portfolios.values():
all_investments.extend(portfolio.investments.values())
# Use dictionary to group by sector
sector_analysis = {}
for investment in all_investments:
if isinstance(investment, Stock):
sector = investment.sector
if sector not in sector_analysis:
sector_analysis[sector] = {
'count': 0, 'total_value': 0, 'total_earnings': 0, 'investments': []
}
sector_analysis[sector]['count'] += 1
sector_analysis[sector]['total_value'] += investment.get_total_value()
sector_analysis[sector]['total_earnings'] += investment.earnings_loss()
sector_analysis[sector]['investments'].append(investment)
print("Sector Analysis (using dictionaries and loops):")
print(f"{'Sector':<15}{'Count':<8}{'Total Value':<15}{'Avg Earnings':<15}")
print("-" * 55)
# Loop through dictionary items
for sector, data in sector_analysis.items():
avg_earnings = data['total_earnings'] / data['count'] if data['count'] > 0 else 0
print(f"{sector:<15}{data['count']:<8}${data['total_value']:<14,.0f}${avg_earnings:<14,.0f}")
# List comprehension examples
print("\\nList Comprehension Examples:")
# Get all profitable investments
profitable_investments = [inv for inv in all_investments if inv.earnings_loss() > 0]
print(f"Profitable investments: {len(profitable_investments)} out of {len(all_investments)}")
# Get high-yield dividend stocks
high_dividend_stocks = [inv for inv in all_investments
if isinstance(inv, Stock) and inv.dividend_yield > 2.0]
print(f"High dividend stocks (>2%): {len(high_dividend_stocks)}")
# Get investment symbols sorted by performance
sorted_by_performance = sorted(all_investments,
key=lambda x: x.yearly_earnings_loss_rate(),
reverse=True)
top_performers = [inv.symbol for inv in sorted_by_performance[:5]]
print(f"Top 5 performers: {', '.join(top_performers)}")
def demonstrate_file_operations(self):
"""
Demonstrate comprehensive file I/O operations
"""
print("\\nDemonstrating File Operations")
print("=" * 35)
# Get first investor for demonstration
investor = list(self.investors.values())[0]
portfolio = list(investor.portfolios.values())[0]
# Export to different formats
print("Exporting portfolio data...")
# CSV export
csv_success = self.file_manager.export_portfolio_to_csv(portfolio, "demo_portfolio.csv")
print(f"CSV export: {'Success' if csv_success else 'Failed'}")
# JSON export
json_success = self.file_manager.export_portfolio_to_json(portfolio, "demo_portfolio.json")
print(f"JSON export: {'Success' if json_success else 'Failed'}")
# Complete investor export
investor_success = self.file_manager.export_investor_to_json(investor, "demo_investor.json")
print(f"Investor export: {'Success' if investor_success else 'Failed'}")
# Generate comprehensive report
report_success = self.file_manager.generate_portfolio_report(portfolio, "demo_report.txt")
print(f"Report generation: {'Success' if report_success else 'Failed'}")
# Demonstrate file reading
print("\\nReading generated files...")
try:
with open(os.path.join(self.file_manager.base_path, "demo_portfolio.json"), 'r') as f:
data = json.load(f)
print(f"JSON file contains {len(data['investments'])} investments")
except Exception as e:
print(f"Error reading JSON file: {e}")
def demonstrate_visualizations(self):
"""
Demonstrate data visualization capabilities
"""
print("\\nDemonstrating Data Visualizations")
print("=" * 40)
# Get investor with most diverse portfolio
best_investor = max(self.investors.values(),
key=lambda inv: sum(len(p.investments) for p in inv.portfolios.values()))
best_portfolio = max(best_investor.portfolios.values(),
key=lambda p: len(p.investments))
print(f"Creating visualizations for {best_investor.name}'s {best_portfolio.name}")
# Create various charts
charts_created = []
# Portfolio allocation pie chart
pie_chart = self.visualizer.create_portfolio_pie_chart(best_portfolio, "demo_allocation.png")
if pie_chart:
charts_created.append("Portfolio Allocation Pie Chart")
# Performance comparison
perf_chart = self.visualizer.create_performance_bar_chart(best_portfolio, "demo_performance.png")
if perf_chart:
charts_created.append("Performance Comparison Chart")
# Sector analysis
sector_chart = self.visualizer.create_sector_analysis(best_portfolio, "demo_sectors.png")
if sector_chart:
charts_created.append("Sector Analysis Chart")
# Interactive dashboard
dashboard = self.visualizer.create_interactive_dashboard(best_portfolio, "demo_dashboard.html")
if dashboard:
charts_created.append("Interactive Dashboard")
print(f"Created {len(charts_created)} visualizations:")
for chart in charts_created:
print(f" - {chart}")
# Generate comprehensive report
report = self.report_generator.generate_comprehensive_report(best_investor, "demo_comprehensive.html")
if report:
print(" - Comprehensive HTML Report")
def run_comprehensive_demo(self):
"""
Run complete demonstration of all features
"""
print("ENHANCED PORTFOLIO MANAGEMENT SYSTEM")
print("=" * 50)
print("Comprehensive Demonstration of All Features")
print("=" * 50)
# Create sample data
self.create_sample_data()
# Demonstrate calculations
self.demonstrate_calculations()
# Demonstrate data structures
self.demonstrate_data_structures()
# Demonstrate file operations
self.demonstrate_file_operations()
# Demonstrate visualizations
self.demonstrate_visualizations()
# Final summary
print("\\nSYSTEM SUMMARY")
print("=" * 20)
print(f"Total Investors: {len(self.investors)}")
total_portfolios = sum(len(inv.portfolios) for inv in self.investors.values())
print(f"Total Portfolios: {total_portfolios}")
total_investments = 0
total_value = 0
for investor in self.investors.values():
for portfolio in investor.portfolios.values():
total_investments += len(portfolio.investments)
for investment in portfolio.investments.values():
total_value += investment.get_total_value()
print(f"Total Investments: {total_investments}")
print(f"Total Portfolio Value: ${total_value:,.2f}")
print("\\nFEATURES DEMONSTRATED:")
features = [
"✓ Object-Oriented Programming (Classes, Inheritance, Polymorphism)",
"✓ Dictionaries and Lists (Extensive usage throughout)",
"✓ Functions and Methods (Modular code organization)",
"✓ Loops (for, while, list comprehensions)",
"✓ Database Operations (SQLite with full CRUD)",
"✓ File I/O (CSV, JSON, Text, Pickle formats)",
"✓ Data Visualization (Matplotlib, Seaborn, Plotly)",
"✓ Exception Handling (Try-catch blocks)",
"✓ Mathematical Calculations (Specified formulas)",
"✓ Data Analysis and Reporting",
"✓ Interactive Dashboards",
"✓ Comprehensive Documentation"
]
for feature in features:
print(f" {feature}")
print("\\nDemonstration completed successfully!")
def main():
"""
Main function to run the application
"""
try:
app = PortfolioManagementApp()
app.run_comprehensive_demo()
except Exception as e:
print(f"Error running application: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()
with open("enhanced_portfolio_system.py", "w") as f:
pass