Guest User

Untitled

a guest
Jun 9th, 2024
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. from sklearn import cluster, covariance
  2. import yfinance as yf
  3. import pandas as pd
  4. import numpy as np
  5. from sklearn import metrics
  6. from sklearn import preprocessing
  7.  
  8. # List of tickers
  9. cfdtickers = [
  10. 'AUDNZD=X', 'AUDCAD=X', 'AUDCHF=X', 'AUDJPY=X', 'CHFJPY=X',
  11. 'EURGBP=X', 'EURAUD=X', 'EURJPY=X', 'EURCHF=X', 'EURNZD=X',
  12. 'EURCAD=X', 'GBPCHF=X', 'GBPJPY=X', 'CADCHF=X', 'CADJPY=X',
  13. 'GBPAUD=X', 'GBPCAD=X', 'GBPNZD=X', 'NZDCAD=X', 'NZDCHF=X',
  14. 'NZDJPY=X', 'NZDUSD=X', 'USDSGD=X', 'EURUSD=X',
  15. ]
  16.  
  17. # Downloading data for each ticker and extracting the 'Close' column
  18. data = {ticker: yf.download(ticker, start="2023-01-01", end="2024-01-01")['Close'] for ticker in cfdtickers}
  19.  
  20. # Creating a DataFrame from the downloaded data
  21. df = pd.DataFrame(data)
  22. df = df.pct_change()
  23. df = df.ffill()
  24. df = df.bfill()
  25. df = df.dropna()
  26.  
  27. # Standardize the data
  28. X = df.copy()
  29. X = preprocessing.StandardScaler().fit_transform(X)
  30.  
  31. # Calculate the covariance matrix
  32. edge_model = covariance.GraphicalLassoCV(verbose=True)
  33. edge_model.fit(X)
  34. covariance_matrix = edge_model.covariance_
  35.  
  36. # Perform clustering using affinity propagation on the covariance matrix
  37. _, labels = cluster.affinity_propagation(covariance_matrix)
  38.  
  39. # Print the labels and the number of labels
  40. print("Labels:", labels)
  41. print("Number of clusters:", len(np.unique(labels)))
  42.  
  43. # Group tickers by clusters
  44. n_labels = labels.max()
  45. names = np.array(df.columns.tolist())
  46.  
  47. sectorTickers = {f'Cluster {i+1}': ', '.join(names[labels == i]) for i in range(n_labels + 1)}
  48. print("Sector Tickers:", sectorTickers)
  49.  
  50. # Calculate the silhouette score
  51. flattened_covariance_matrix = covariance_matrix.flatten().reshape(-1, 1)
  52. flattened_labels = np.repeat(labels, covariance_matrix.shape[0])
  53.  
  54. silhouette_score = metrics.silhouette_score(flattened_covariance_matrix, flattened_labels)
  55. print("Silhouette Score:", silhouette_score)
  56.  
Advertisement
Add Comment
Please, Sign In to add comment