Guest User

Untitled

a guest
Feb 10th, 2024
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. #%%
  2. from sklearn import cluster, covariance, manifold
  3. import yfinance as yf
  4. import pandas as pd
  5. import numpy as np
  6. from sklearn import metrics
  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.  
  26.  
  27. pct_change_combined_stock_df = df
  28. pct_change_combined_stock_df = pct_change_combined_stock_df.dropna()
  29.  
  30. variation = pct_change_combined_stock_df
  31.  
  32. edge_model = covariance.GraphicalLassoCV(verbose=True)
  33. X = variation.copy()
  34. X /= X.std(axis=0)
  35. edge_model.fit(X)
  36.  
  37. _, labels = cluster.affinity_propagation(edge_model.covariance_)
  38.  
  39.  
  40.  
  41. n_labels = labels.max()
  42. names=[]
  43.  
  44. for stock in pct_change_combined_stock_df.columns.tolist():
  45. names.append(stock)
  46.  
  47. names = np.array(names)
  48.  
  49. sectorTickers = {f'Cluster {i+1}': ', '.join(names[labels == i]) for i in range(n_labels + 1)}
  50. print("sectorTickers",sectorTickers)
  51.  
  52. # Calculate silhouette score
  53. silhouette_score = metrics.silhouette_score(X, labels)
  54. print("Silhouette Score:", silhouette_score)
  55.  
  56.  
  57. # %%
  58.  
Advertisement
Add Comment
Please, Sign In to add comment