-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstock.py
71 lines (56 loc) · 2.07 KB
/
stock.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# coding: utf-8
import bs4 as bs
import requests
import pandas as pd
import pandas_datareader.data as pdr
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mpldates
import numpy as np
import datetime
from sklearn.ensemble import RandomForestRegressor
from sklearn import linear_model
from xgboost import XGBRegressor
def sp500_tickers():
resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
soup = bs.BeautifulSoup(resp.text, 'lxml')
table = soup.find('table', {'class': 'wikitable sortable'})
tickers = []
for row in table.findAll('tr')[1:]:
ticker = row.findAll('td')[0].find('a')['href']
tickers.append(ticker.rsplit('/', 1)[-1].replace("XNYS", "NYSE"))
print(tickers[:5])
return tickers
tickers = sp500_tickers()
start = datetime.datetime(2000, 1, 15)
end = datetime.datetime(2017, 5, 31)
def get_px(stock, start, end):
return pdr.DataReader(stock, 'google', start, end)
def predict_price(stock):
print(stock)
px = pd.DataFrame(get_px(stock, start, end))
if px.empty:
print('DataFrame is empty!')
return
px['100ma'] = px['Close'].rolling(window=100,min_periods=0).mean()
px = px.reset_index()
px['DateNUM'] = px['Date'].map(mpldates.date2num)
dates = px[['DateNUM', '100ma']]
prices = px['Close']
rfr = RandomForestRegressor(n_estimators=3, max_depth=10)
reg = linear_model.LinearRegression()
xgb = XGBRegressor()
rfr.fit(dates, prices)
reg.fit(dates, prices)
xgb.fit(dates, prices)
plt.scatter(px['Date'].values, prices, color='Black', label='Data')
plt.plot(px['Date'].values, rfr.predict(dates), color='red', label='RFC model')
plt.plot(px['Date'].values, reg.predict(dates), color='blue', label='BREG model')
plt.plot(px['Date'].values, xgb.predict(dates), color='green', label='XGB')
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Support Vector Regression/RFR for %s' % stock)
plt.legend()
plt.show()
for n in tickers[:10]:
predict_price(n)