-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmeans.py
44 lines (36 loc) · 1.03 KB
/
kmeans.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
from finviz import *
import pandas as pd
# sp500 = pd.read_csv('sp500.csv')
nyse = pd.read_csv('NYSE.csv')
df = pd.DataFrame()
for i,ticker in enumerate(nyse.Symbol):
# for i,ticker in enumerate(sp500.Ticker):
print ticker
try:
df = pd.concat([df, finviz(ticker)], 1)
except:
print 'Error :('
df = df.fillna(0).transpose()
df.to_csv('tmp.csv', index=None)
tmp = df.drop(['Ticker','Index','Optionable','Shortable','Earnings'], 1)
X = []
for i in range(len(tmp)):
X.append(tmp.iloc[i].tolist())
X = np.array(X)
kmeans = KMeans(n_clusters=3, random_state=0).fit(X)
output = list(kmeans.labels_)
pca = PCA(n_components=2).fit(X)
pca_2d = pca.transform(X)
plt.figure()
for i,ticker in enumerate(df.Ticker):
print ticker, output[i]
if output[i] == 0:
plt.plot(pca_2d[i,0], pca_2d[i,1], '+r')
elif output[i] == 1:
plt.plot(pca_2d[i,0], pca_2d[i,1], 'ok')
elif output[i] == 2:
plt.plot(pca_2d[i,0], pca_2d[i,1], '*b')
plt.show()