Last active
October 3, 2018 02:40
-
-
Save lazear/55d5c0c169ed051180d58c05e23005c3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import requests | |
import pandas as pd | |
import numpy as np | |
import operator | |
import base64 | |
import matplotlib.pyplot as plt | |
import matplotlib.dates as mdates | |
import dateutil | |
from datetime import datetime, timezone | |
from io import BytesIO | |
from mpl_finance import candlestick_ohlc | |
from matplotlib import rcParams | |
from typing import List | |
plt.style.use('ggplot') | |
rcParams["font.family"] = "sans-serif" | |
rcParams["font.sans-serif"] = ["DejaVu Sans"] | |
rcParams["figure.dpi"] = 144 | |
BASE_URL = "https://api.iextrading.com/1.0/" | |
mondays = mdates.WeekdayLocator(byweekday=mdates.MO) | |
days = mdates.DayLocator() | |
years = mdates.YearLocator() # every year | |
months = mdates.MonthLocator() # every month | |
weekFormatter = mdates.DateFormatter('%D') | |
def moving_average(x, n, type='simple'): | |
""" | |
compute an n period moving average. | |
type is 'simple' | 'exponential' | |
""" | |
x = np.asarray(x) | |
if type == 'simple': | |
weights = np.ones(n) | |
else: | |
weights = np.exp(np.linspace(-1., 0., n)) | |
weights /= weights.sum() | |
a = np.convolve(x, weights, mode='full')[:len(x)] | |
a[:n] = a[n] | |
return a | |
class Stock: | |
def __init__(self, symbol: str): | |
self.symbol = symbol | |
def __make_request__(self, str): | |
return json.loads(requests.get(BASE_URL + str).text) | |
def historical(self, duration: str): | |
c = requests.get(BASE_URL + "stock/{}/chart/{}".format(self.symbol, duration)).text | |
df = pd.DataFrame(json.loads(c)) | |
df['date']= pd.to_datetime(df['date']) | |
return df.set_index("date") | |
def company(self): | |
return self.__make_request__("stock/{}/company".format(self.symbol)) | |
def financials(self): | |
return self.__make_request__("stock/{}/financials".format(self.symbol)) | |
def news(self): | |
return self.__make_request__("stock/{}/news".format(self.symbol)) | |
def price(x): | |
return '${:2.2f}'.format(x) | |
def plot(self, duration: str): | |
fig, ax = plt.subplots() | |
df = self.historical(duration) | |
candlestick_ohlc(ax, zip(mdates.date2num(df.index.to_pydatetime()), df['open'], df['high'], df['low'], df['close']), width=0.6, colorup='green', colordown='red') | |
ax.xaxis.set_major_locator(mondays) | |
ax.xaxis.set_major_formatter(weekFormatter) | |
ax.xaxis.set_minor_locator(days) | |
ax.grid(True) | |
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d') | |
ax.format_ydata = Stock.price | |
fig.autofmt_xdate() | |
plt.title(self.symbol.upper()) | |
image = BytesIO() | |
plt.savefig(image, format='png') | |
return base64.encodestring(image.getvalue()).decode() | |
def write_report(output: str, positions: List[str]): | |
row = open("templates/row.html").read() | |
table = open("templates/table.html", "r").read() | |
stock = open("templates/stock.html", "r").read() | |
report = open("templates/report.html").read() | |
with open(output, "w+") as f: | |
output = "" | |
for s in positions: | |
news = Stock(s).news() | |
image = Stock(s).plot("3m") | |
t = "\n".join([row.format(date= "{0:%Y-%m-%d %H:%M%p}".format(dateutil.parser.parse(item["datetime"]).replace(tzinfo=timezone.utc).astimezone(tz=None)), | |
source="""<a href="{}">{}</a>""".format(item["url"], item["source"]), | |
headline=item["headline"], | |
summary=item["summary"],) for item in news]) | |
output += stock.format(image=image, table=table.format(rows= t)) | |
f.write(report.format(output)) | |
if __name__ == "__main__": | |
default_positions = ["msft", "aapl", "amd", "mu", "gld", "ewz", "iq", "cron", "nflx"] | |
write_report("report.html", default_positions) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A | |
AAL | |
AAP | |
AAPL | |
ABBV | |
ABC | |
ABMD | |
ABT | |
ACN | |
ADBE | |
ADI | |
ADM | |
ADP | |
ADS | |
ADSK | |
AEE | |
AEP | |
AES | |
AET | |
AFL | |
AGN | |
AIG | |
AIV | |
AIZ | |
AJG | |
AKAM | |
ALB | |
ALGN | |
ALK | |
ALLE | |
ALXN | |
AMAT | |
AMD | |
AME | |
AMG | |
AMGN | |
AMP | |
AMT | |
AMZN | |
ANDV | |
ANET | |
ANSS | |
ANTM | |
AON | |
AOS | |
APA | |
APC | |
APD | |
APH | |
APTV | |
ARE | |
ARNC | |
ATVI | |
AVB | |
AVGO | |
AVY | |
AWK | |
AXP | |
AZO | |
BA | |
BAC | |
BAX | |
BBT | |
BBY | |
BDX | |
BEN | |
BF.B | |
BHF | |
BHGE | |
BIIB | |
BK | |
BKNG | |
BLK | |
BLL | |
BMY | |
BR | |
BRK.B | |
BSX | |
BWA | |
BXP | |
C | |
CA | |
CAG | |
CAH | |
CAT | |
CB | |
CBOE | |
CBRE | |
CBS | |
CCI | |
CCL | |
CDNS | |
CELG | |
CERN | |
CF | |
CFG | |
CHD | |
CHRW | |
CHTR | |
CI | |
CINF | |
CL | |
CLX | |
CMA | |
CMCSA | |
CME | |
CMG | |
CMI | |
CMS | |
CNC | |
CNP | |
COF | |
COG | |
COL | |
COO | |
COP | |
COST | |
COTY | |
CPB | |
CPRT | |
CRM | |
CSCO | |
CSX | |
CTAS | |
CTL | |
CTSH | |
CTXS | |
CVS | |
CVX | |
CXO | |
D | |
DAL | |
DE | |
DFS | |
DG | |
DGX | |
DHI | |
DHR | |
DIS | |
DISCA | |
DISCK | |
DISH | |
DLR | |
DLTR | |
DOV | |
DRE | |
DRI | |
DTE | |
DUK | |
DVA | |
DVN | |
DWDP | |
DXC | |
EA | |
EBAY | |
ECL | |
ED | |
EFX | |
EIX | |
EL | |
EMN | |
EMR | |
EOG | |
EQIX | |
EQR | |
EQT | |
ES | |
ESRX | |
ESS | |
ETFC | |
ETN | |
ETR | |
EVHC | |
EVRG | |
EW | |
EXC | |
EXPD | |
EXPE | |
EXR | |
F | |
FAST | |
FB | |
FBHS | |
FCX | |
FDX | |
FE | |
FFIV | |
FIS | |
FISV | |
FITB | |
FL | |
FLIR | |
FLR | |
FLS | |
FLT | |
FMC | |
FOX | |
FOXA | |
FRT | |
FTI | |
FTV | |
GD | |
GE | |
GILD | |
GIS | |
GLW | |
GM | |
GOOG | |
GOOGL | |
GPC | |
GPN | |
GPS | |
GRMN | |
GS | |
GT | |
GWW | |
HAL | |
HAS | |
HBAN | |
HBI | |
HCA | |
HCP | |
HD | |
HES | |
HFC | |
HIG | |
HII | |
HLT | |
HOG | |
HOLX | |
HON | |
HP | |
HPE | |
HPQ | |
HRB | |
HRL | |
HRS | |
HSIC | |
HST | |
HSY | |
HUM | |
IBM | |
ICE | |
IDXX | |
IFF | |
ILMN | |
INCY | |
INFO | |
INTC | |
INTU | |
IP | |
IPG | |
IPGP | |
IQV | |
IR | |
IRM | |
ISRG | |
IT | |
ITW | |
IVZ | |
JBHT | |
JCI | |
JEC | |
JEF | |
JNJ | |
JNPR | |
JPM | |
JWN | |
K | |
KEY | |
KHC | |
KIM | |
KLAC | |
KMB | |
KMI | |
KMX | |
KO | |
KORS | |
KR | |
KSS | |
KSU | |
L | |
LB | |
LEG | |
LEN | |
LH | |
LKQ | |
LLL | |
LLY | |
LMT | |
LNC | |
LNT | |
LOW | |
LRCX | |
LUV | |
LYB | |
M | |
MA | |
MAA | |
MAC | |
MAR | |
MAS | |
MAT | |
MCD | |
MCHP | |
MCK | |
MCO | |
MDLZ | |
MDT | |
MET | |
MGM | |
MHK | |
MKC | |
MLM | |
MMC | |
MMM | |
MNST | |
MO | |
MOS | |
MPC | |
MRK | |
MRO | |
MS | |
MSCI | |
MSFT | |
MSI | |
MTB | |
MTD | |
MU | |
MYL | |
NBL | |
NCLH | |
NDAQ | |
NEE | |
NEM | |
NFLX | |
NFX | |
NI | |
NKE | |
NKTR | |
NLSN | |
NOC | |
NOV | |
NRG | |
NSC | |
NTAP | |
NTRS | |
NUE | |
NVDA | |
NWL | |
NWS | |
NWSA | |
O | |
OKE | |
OMC | |
ORCL | |
ORLY | |
OXY | |
PAYX | |
PBCT | |
PCAR | |
PCG | |
PEG | |
PEP | |
PFE | |
PFG | |
PG | |
PGR | |
PH | |
PHM | |
PKG | |
PKI | |
PLD | |
PM | |
PNC | |
PNR | |
PNW | |
PPG | |
PPL | |
PRGO | |
PRU | |
PSA | |
PSX | |
PVH | |
PWR | |
PX | |
PXD | |
PYPL | |
QCOM | |
QRVO | |
RCL | |
RE | |
REG | |
REGN | |
RF | |
RHI | |
RHT | |
RJF | |
RL | |
RMD | |
ROK | |
ROP | |
ROST | |
RSG | |
RTN | |
SBAC | |
SBUX | |
SCG | |
SCHW | |
SEE | |
SHW | |
SIVB | |
SJM | |
SLB | |
SLG | |
SNA | |
SNPS | |
SO | |
SPG | |
SPGI | |
SRCL | |
SRE | |
STI | |
STT | |
STX | |
STZ | |
SWK | |
SWKS | |
SYF | |
SYK | |
SYMC | |
SYY | |
T | |
TAP | |
TDG | |
TEL | |
TGT | |
TIF | |
TJX | |
TMK | |
TMO | |
TPR | |
TRIP | |
TROW | |
TRV | |
TSCO | |
TSN | |
TSS | |
TTWO | |
TWTR | |
TXN | |
TXT | |
UA | |
UAA | |
UAL | |
UDR | |
UHS | |
ULTA | |
UNH | |
UNM | |
UNP | |
UPS | |
URI | |
USB | |
UTX | |
V | |
VAR | |
VFC | |
VIAB | |
VLO | |
VMC | |
VNO | |
VRSK | |
VRSN | |
VRTX | |
VTR | |
VZ | |
WAT | |
WBA | |
WDC | |
WEC | |
WELL | |
WFC | |
WHR | |
WLTW | |
WM | |
WMB | |
WMT | |
WRK | |
WU | |
WY | |
WYNN | |
XEC | |
XEL | |
XL | |
XLNX | |
XOM | |
XRAY | |
XRX | |
XYL | |
YUM | |
ZBH | |
ZION | |
ZTS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment