馬可維茲風險平均數平面
import csv #輸入csv套件comma separated value
f = open('200201to202505.csv','r', encoding="utf-8")#打開下載的檔案SPY.CSV,模式是r讀取,
csvreader = csv.reader(f) #將檔案讀入變數csvreader
header, rows = list(), list() #宣告空白串列(陣列,清單)
firms = set() #建構集合
header = next(csvreader) #串列header儲存檔案第一列
for record in csvreader: #檔案紀錄,逐列row檢視
rows.append(record) #第i筆附加append於rows串列成為rows[i]
firms.add(record[0]) #row[0]公司名稱
f.close() #關閉檔案
months = dict()
for year in range(2007,2026):
months[year]=[str(year*100+month) for month in range(1,13)]
count, sum, sumSq, mean, stdev = dict(), dict(), dict(), dict(), dict()
for firm in firms:
for year in range(2007, 2026):
t = (firm, year) #元組(公司,年)
count[t] = 0
sum[t] = 0.0
sumSq[t] = 0.0
for row in rows: #字典value增加append元素
for firm in firms:
if row[0] == firm:
for year in range(2007, 2026):
t = (firm, year)
for month in months[year]:
if row[1] == month:
count[t] +=1
temp = float(row[8])
sum[t] += temp
sumSq[t] += temp*temp
for firm in firms: #以下計算各年度月報酬率的平均數與標準差
for year in range(2007, 2026):
t = (firm, year)
temp1 = count[t]
temp2 = sum[t]
mean[t] = temp2 / temp1
temp2 = sumSq[t] - temp2 * temp2 / temp1
temp2 = temp2/(temp1-1)
stdev[t] = temp2 ** 0.5
from tkinter import *
tk = Tk()
tk.geometry('1000x600')
tk.title('上市金融控股公司股價報酬率標準差(X軸)與平均數(Y軸)')
canvas=Canvas(tk, width=1000,height=600,bg='white')
canvas.pack()
canvas.create_line(0,200,700,200,width=3,fill='black',arrow='last')
canvas.create_line(10,600,10,5,width=3,fill='black',arrow='last')
canvas.pack()
for firm in firms:
t=(firm, 2007)
x = 10+20*stdev[t]*2*3**0.5 #放大20
y = 200 - 10*mean[t]*12 #放大10
dot=canvas.create_oval(x-5,y-5,x+5,y+5,fill='blue')
lab=canvas.create_text(x+10,y,text=firm[4:7],anchor=W,font=('微軟中黑體', 16))
tk.mainloop()
隨便應付!https://kuanhtml-css-javascript-java.blogspot.com/2025/06/blog-post.html
回覆刪除