下载地址:https://www.pan38.com/share.php?code=JCnzE 提取密码:7789
这个完整的股票账户模拟系统包含四个主要模块:主模拟器、持仓可视化、交割单生成和主程序入口。系统可以模拟随机交易、生成持仓图表、创建交割单和投资组合报告。您可以根据需要调整参数或扩展功能。
import random
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime, timedelta
import numpy as np
from faker import Faker
class StockAccountSimulator:
def init(self, initial_balance=100000):
self.balance = initial_balance
self.portfolio = {}
self.transaction_history = []
self.fake = Faker()
self.stock_pool = [
"AAPL", "MSFT", "GOOGL", "AMZN", "TSLA",
"FB", "NVDA", "PYPL", "ADBE", "INTC"
]
self.current_prices = {stock: round(random.uniform(50, 500), 2) for stock in self.stock_pool}
def generate_random_trade(self, days=30):
start_date = datetime.now() - timedelta(days=days)
for i in range(days*3): # 3 trades per day on average
trade_date = start_date + timedelta(days=i//3, hours=random.randint(9, 15), minutes=random.randint(0, 59))
stock = random.choice(self.stock_pool)
action = random.choice(["BUY", "SELL"])
quantity = random.randint(1, 100)
price = self.current_prices[stock] * random.uniform(0.95, 1.05)
amount = round(quantity * price, 2)
if action == "BUY" and self.balance >= amount:
self.execute_trade(trade_date, stock, action, quantity, price)
elif action == "SELL" and stock in self.portfolio and self.portfolio[stock] >= quantity:
self.execute_trade(trade_date, stock, action, quantity, price)
# Update price randomly
self.current_prices[stock] *= random.uniform(0.98, 1.02)
self.current_prices[stock] = round(self.current_prices[stock], 2)
PortfolioVisualizer:
@staticmethod
def generate_holdings_chart(portfolio, prices):
if not portfolio:
print("Portfolio is empty")
return
stocks = list(portfolio.keys())
quantities = [portfolio[stock] for stock in stocks]
values = [portfolio[stock] * prices[stock] for stock in stocks]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
# Pie chart by value
ax1.pie(values, labels=stocks, autopct='%1.1f%%')
ax1.set_title('Portfolio Allocation by Value')
# Bar chart by quantity
ax2.bar(stocks, quantities)
ax2.set_title('Holdings by Quantity')
ax2.set_ylabel('Shares')
plt.tight_layout()
plt.savefig('portfolio_holdings.png')
plt.close()
return 'portfolio_holdings.png'
@staticmethod
def generate_performance_chart(history):
if not history:
print("No transaction history")
return
df = pd.DataFrame(history)
df['date'] = pd.to_datetime(df['date'])
df['cumulative'] = df['amount'].cumsum()
plt.figure(figsize=(12, 6))
plt.plot(df['date'], df['cumulative'])
plt.title('Account Performance Over Time')
plt.xlabel('Date')
plt.ylabel('Cumulative Value ($)')
plt.grid(True)
plt.savefig('performance_chart.png')
plt.close()
return 'performance_chart.png'