[TQC+][Python][PML3]人工智慧:機器學習-205.股票分群

文、意如

題目:
  1. 請使用affinity propagation分群(Clustering)撰寫程式,讀取symbol_map.json,這個資料包含所有股票代號以及對應名稱。
  2. 在特定時間內的某支股票市場變化情形則是以股票代號的csv的格式儲存。例如:AMZN.csv儲存Amazon在2003-2007的股價變動,其中包含序號、date(日期)、open(開盤價)、close(收盤價)等四個欄位。
  3. 請根據每日股價波動(收盤價-開盤價)找出公司行為的相似性,印出同屬一類的公司名稱。

(三)、 請依序回答下列問題:

1.請填入分群數量?

2.下列哪一選項的公司與Cisco同群,請填入選項?

( A ) Dell, HP, IBM ( B ) General Dynamics, General Electrics, Goldman Sachs ( C ) ConocoPhillips, Chevron ( D ) CVS

3.下列哪一選項的公司與AIG同群,請填入選項?

( A ) American express, Bank of America ( B ) Apple, Amazon, Yahoo ( C ) Comcast, Cablevision ( D ) Colgate-Palmolive, Kimberly-Clark

4.下列哪一選項的公司與Boeing同群,請填入選項?

( A ) American express, Bank of America, DuPont de Nemours ( B ) GlaxoSmithKline, Home Depot, Kellogg ( C ) Home Depot, Kellogg ( D ) Canon, Caterpillar, Ford, Honda

MLD02.py:
import json
import pandas as pd
import numpy as np
# TODO
symbol_file = 'symbol_map.json'

# TODO



for symbol in symbols:
# TODO
    

# The daily fluctuations of the quotes 報價的每日波動
# TODO

# Build a graph model from the correlations 根據相關性建立圖模型
# TODO

# Standardize the data 標準化資料
# TODO

# Train the model 訓練模型
# TODO

# Build clustering model using affinity propagation 用相似性傳播構建分群模型
# TODO

# Print the results of clustering 列印分群結果
# TODO
    print("Cluster", i+1, "-->"                   )
    

參考解答:
import json
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')

with open('symbol_map.json') as fp:
    json = json.load(fp)
symbols = pd.DataFrame(sorted(json.items()))[0]
names = pd.DataFrame(sorted(json.items()))[1]

stocks = []
for symbol in symbols:
    stocks.append(pd.read_csv(f"{symbol}.csv"))
# The daily fluctuations of the quotes 報價的每日波動
open_price = pd.DataFrame([stock['open'] for stock in stocks], index=symbols)
close_price = pd.DataFrame([stock['close'] for stock in stocks], index=symbols)
daily_var_price = open_price - close_price
# Build a graph model from the correlations 根據相關性建立圖模型
from sklearn.covariance import GraphicalLassoCV
model = GraphicalLassoCV()
# Standardize the data 標準化資料
X = pd.DataFrame(daily_var_price).T
X /= X.std()
# Train the model 訓練模型
model.fit(X)
# Build clustering model using affinity propagation 用相似性傳播構建分群模型
from sklearn.cluster import affinity_propagation
_, labels = affinity_propagation(model.covariance_, random_state=0)
num_labels = len(set(labels))
print(f'num_labels: {num_labels}')
# Print the results of clustering 列印分群結果
for i in range(len(set(labels))):
    print("Cluster", i+1, "-->" ,','.join(names[labels==i]))
程式解析:
# 導入必要的庫
import json  # 用於處理JSON格式數據
import pandas as pd  # 數據處理和分析庫
import numpy as np  # 數值計算庫
import warnings  # 警告處理
warnings.filterwarnings('ignore')  # 忽略所有警告信息

# 從JSON文件加載股票代碼映射關係
with open('symbol_map.json') as fp:
    json = json.load(fp)  # 讀取並解析JSON文件

# 將JSON數據轉換為DataFrame格式
symbols = pd.DataFrame(sorted(json.items()))[0]  # 提取股票代碼列
names = pd.DataFrame(sorted(json.items()))[1]  # 提取股票名稱列

# 讀取每個股票的CSV數據
stocks = []
for symbol in symbols:
    stocks.append(pd.read_csv(f"{symbol}.csv"))  # 讀取每個股票代碼對應的CSV文件

# 計算每日開盤價與收盤價的波動
open_price = pd.DataFrame([stock['open'] for stock in stocks], index=symbols)  # 所有股票的開盤價
close_price = pd.DataFrame([stock['close'] for stock in stocks], index=symbols)  # 所有股票的收盤價
daily_var_price = open_price - close_price  # 計算每日價格波動(開盤價-收盤價)

# 使用GraphicalLassoCV建立圖模型
from sklearn.covariance import GraphicalLassoCV  # 導入圖形套索交叉驗證模型
model = GraphicalLassoCV()  # 創建模型實例

# 數據標準化處理
X = pd.DataFrame(daily_var_price).T  # 轉置數據,使每行代表一個時間點,每列代表一個股票
X /= X.std()  # 使用標準差進行標準化

# 訓練圖模型
model.fit(X)  # 擬合模型

# 使用親和力傳播算法進行聚類
from sklearn.cluster import affinity_propagation  # 導入親和力傳播聚類算法
_, labels = affinity_propagation(model.covariance_, random_state=0)  # 應用於協方差矩陣,獲取聚類標籤
num_labels = len(set(labels))  # 計算聚類數量
print(f'num_labels: {num_labels}')  # 打印聚類數量

# 打印每個聚類中的股票名稱
for i in range(len(set(labels))):  # 遍歷每個聚類
    print("Cluster", i+1, "-->" ,','.join(names[labels==i]))  # 打印聚類編號和對應的股票名稱

Yiru@Studio - 關於我 - 意如