-
Notifications
You must be signed in to change notification settings - Fork 1
/
milestone.py
executable file
·160 lines (149 loc) · 5.09 KB
/
milestone.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#!/usr/bin/env python3
import json, re, sys
from itertools import groupby
from lib.config import *
from lib import sharesight
from lib import webhook
from lib import util
from lib import yahoo
# BUGS:
# - need to handle stock splits: flush cache if we see a split in the data
# https://finance.yahoo.com/quote/TSLA/history?period1=0&period2=1707609600&filter=split
def lambda_handler(chat_id=config_telegramChatID, specific_stock=None, service=None, interactive=False):
def prepare_milestone_payload(service, market_data):
emoji = '⭐'
payload = []
payloadhigh = []
payloadlow = []
payloadprofit = []
payloadcashflow = []
payloadprofitneg = []
payloadcashflowneg = []
oldhigh = float()
oldlow = float()
records = util.json_load('finbot_milestone.json', persist=True)
if records is None:
records = {}
for ticker in tickers:
try:
oldhigh = records[ticker]['high']
oldlow = records[ticker]['low']
except (KeyError, TypeError):
records[ticker] = {}
records[ticker]['high'] = float()
records[ticker]['low'] = float()
try:
oldhigh, oldlow = yahoo.historic_high(ticker) # first run to prime cache file
except (KeyError, TypeError):
continue
try:
newhigh = round(market_data[ticker]['fiftyTwoWeekHigh'], 2)
newlow = round(market_data[ticker]['fiftyTwoWeekLow'], 2)
except (KeyError, ValueError):
continue
newprofit = False
newcashflow = False
detail = yahoo.fetch_detail(ticker)
if ticker in detail:
if 'net_income' in detail[ticker] and detail[ticker]['net_income'] > 0:
newprofit = True
if 'free_cashflow' in detail[ticker] and detail[ticker]['free_cashflow'] > 0:
newcashflow = True
try:
oldprofit = records[ticker]['profit']
oldcashflow = records[ticker]['cashflow']
except (KeyError, TypeError):
oldprofit = newprofit
oldcashflow = newcashflow
title = market_data[ticker]['profile_title']
ticker_link = util.finance_link(ticker, market_data[ticker]['profile_exchange'], service)
emoji = util.flag_from_ticker(ticker)
records[ticker]['high'] = newhigh
records[ticker]['low'] = newlow
records[ticker]['profit'] = newprofit
records[ticker]['cashflow'] = newcashflow
if newhigh > oldhigh:
print("DEBUG", ticker, newhigh, "is higher than", oldhigh) if debug else None
payloadhigh.append(f"{emoji} {title} ({ticker_link})")
if newlow < oldlow:
print("DEBUG", ticker, newlow, "is lower than", oldlow) if debug else None
payloadlow.append(f"{emoji} {title} ({ticker_link})")
if oldprofit != newprofit:
print("DEBUG", ticker, "profitability changed", oldprofit, newprofit) if debug else None
if newprofit:
payloadprofit.append(f"{emoji} {title} ({ticker_link})")
else:
payloadprofitneg.append(f"{emoji} {title} ({ticker_link})")
if oldcashflow != newcashflow:
print("DEBUG", ticker, "cashflow changed", oldcashflow, newcashflow) if debug else None
if newcashflow:
payloadcashflow.append(f"{emoji} {title} ({ticker_link})")
else:
payloadcashflowneg.append(f"{emoji} {title} ({ticker_link})")
payloadlow.sort()
payloadhigh.sort()
payloadprofit.sort()
payloadcashflow.sort()
payloadprofitneg.sort()
payloadcashflowneg.sort()
if payloadhigh:
message = 'Record high:'
message = webhook.bold(message, service)
payload.append(message)
payload = payload + payloadhigh
if payloadlow:
payload.append("")
message = 'Record low:'
message = webhook.bold(message, service)
payload.append(message)
payload = payload + payloadlow
if payloadprofit:
payload.append("")
message = 'Became profitable'
message = webhook.bold(message, service)
payload.append(message)
payload = payload + payloadprofit
if payloadcashflow:
payload.append("")
message = 'Became cashflow positive'
message = webhook.bold(message, service)
payload.append(message)
payload = payload + payloadcashflow
if payloadprofitneg:
payload.append("")
message = 'Became unprofitable'
message = webhook.bold(message, service)
payload.append(message)
payload = payload + payloadprofitneg
if payloadcashflowneg:
payload.append("")
message = 'Became cashflow negative'
message = webhook.bold(message, service)
payload.append(message)
payload = payload + payloadcashflowneg
payload = [i[0] for i in groupby(payload)] # de-dupe white space
return payload, records
# MAIN #
market_data = {}
if specific_stock:
ticker = util.transform_to_yahoo(specific_stock)
tickers = [ticker]
else:
tickers = util.get_holdings_and_watchlist()
market_data = yahoo.fetch(tickers)
# Prep and send payloads
if not webhooks:
print("Error: no services enabled in .env", file=sys.stderr)
sys.exit(1)
else:
for service, url in webhooks.items():
payload, records = prepare_milestone_payload(service, market_data)
if service == "telegram":
url = url + "sendMessage?chat_id=" + str(chat_id)
webhook.payload_wrapper(service, url, payload, chat_id)
if records:
util.json_write('finbot_milestone.json', records, persist=True)
# make google cloud happy
return True
if __name__ == "__main__":
lambda_handler()