-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
193 lines (159 loc) · 6.22 KB
/
Copy pathmain.py
File metadata and controls
193 lines (159 loc) · 6.22 KB
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#/usr/local/bin/python3
from bs4 import BeautifulSoup
import requests
from terminaltables import AsciiTable
cash = 100000000
list_of_tickers = ["AMZN", "AAPL", "SNAP", "AMD", "LLY"]
def match_class(target):
def do_match(tag):
classes = tag.get('class', [])
return all(c in classes for c in target)
return do_match
def as_currency(amount):
if amount >= 0:
return '${:,.2f}'.format(amount)
else:
return '-${:,.2f}'.format(-amount)
def list_shares(trades):
# shares = 0
sorted_trades = sorted(trades, key=lambda x: x.postdate, reverse=True)
if len(sorted_trades) > 0:
for trade in sorted_trades:
print("-----------")
print("Side: "+str(trade.side))
print("Ticker: "+trade.symbol)
print("Quantity: "+str(trade.quantity))
print("Executed price: "+as_currency(trade.price))
print("Executed Timestamp: "+str(trade.postdate))
print("Money In/Out: "+as_currency(trade.price*float(trade.quantity.replace(',', ''))))
print("-----------")
else:
print("No trades yet.")
def num_shares(trades, symbol):
shares = 0
for trade in trades:
if trade.side == 'BUY' and trade.symbol == symbol:
shares += int(trade.quantity)
if trade.side == 'SELL' and trade.symbol == symbol:
shares -= int(trade.quantity)
return shares
def sold_shares(trades, symbol):
shares = 0
for trade in trades:
if trade.side == 'SELL' and trade.symbol == symbol:
shares += int(trade.quantity)
return shares
def pl(market, the_wap, shares):
return float((market-the_wap)*int(shares))
def wap(trades, symbol):
the_wap = 0
acum = 0
for trade in trades:
if trade.side == 'BUY' and trade.symbol == symbol:
the_wap += int(trade.quantity)*trade.price
acum += int(trade.quantity)
if acum > 0:
return float(the_wap/acum)
else:
return float(0.00)
def market(trades, symbol):
# market price is the latest price you buy or sell, if there's no orders, use the one in yahoo.
sorted_trades = sorted((t for t in trades if t.symbol == symbol), key=lambda x: x.postdate, reverse=True)
if len(sorted_trades)>0:
return float(sorted_trades[0].price)
else:
r = requests.get('https://finance.yahoo.com/quote/' + symbol)
soup = BeautifulSoup(r.content, 'html.parser')
return float(soup.findAll(match_class(["Trsdu(0.3s)"]))[0].text.replace(',', ''))
def market_ask(symbol):
r = requests.get('https://finance.yahoo.com/quote/' + symbol)
soup = BeautifulSoup(r.content, 'html.parser')
return float(soup.find("td", {"data-test": "ASK-value"}).text.split('x')[0].replace(',',''))
def market_bid(symbol):
r = requests.get('https://finance.yahoo.com/quote/' + symbol)
soup = BeautifulSoup(r.content, 'html.parser')
return float(soup.find("td", {"data-test": "BID-value"}).text.split('x')[0].replace(',',''))
def trade(trades):
global cash, list_of_tickers
import datetime
from order import Order
print ("available symbols: "+", ".join(list_of_tickers))
symbol = ""
the_type = ""
amount = 0
while symbol not in list_of_tickers:
symbol = input("please type a symbol")
while the_type not in ["BUY", "SELL"]:
the_type = input("Type of trade(BUY, SELL):")
try:
while int(amount) <= 0:
amount = input("number of shares:")
except ValueError:
print("Please insert a positive number of shares")
return None
if the_type == "BUY":
price = market_ask(symbol)
confirm = input("Please confirm if you want to buy " + amount + " shares at a price of " + as_currency(price) + " per share. (Y to confirm)")
if confirm == "Y":
total = float(amount) * price
if total <= cash:
the_order = Order(the_type, symbol, amount, price, datetime.datetime.now())
cash -= total
trades.append(the_order)
print("Success!")
return True
else:
print("Not enough money.")
return None
else:
print("transaction cancelled.")
return None
else:
price = market_bid(symbol)
confirm = input("Please confirm if you want to sell " + amount + " shares at a price of " + as_currency(price) + " per share. (Y to confirm)")
if confirm == "Y":
# check if you have enough shares to sell
if num_shares(trades, symbol) >= int(amount):
total = float(amount) * price
cash += total
the_order = Order(the_type, symbol, amount, price, datetime.datetime.now())
trades.append(the_order)
print("Success!")
return True
else:
print("Not enough shares to sell.")
return None
else:
print("transaction cancelled.")
return None
def show_pl(trades):
global cash, list_of_tickers
data = []
data.append(['Ticker', 'Position', 'Market', 'WAP', 'UPL', 'RPL'])
for the_trade in list_of_tickers:
ns = num_shares(trades, the_trade)
ss = sold_shares(trades, the_trade)
ma = market(trades, the_trade)
wap_price = wap(trades, the_trade)
upl = pl(ma, wap_price, ns) # here is not ma, but the price at BUY/SELL of the latest trade | video->17:50
rpl = pl(ma, wap_price, ss) # here is not ma, but the price at SELL of the latest trade | video->17:50
data.append([the_trade, ns, as_currency(ma), as_currency(wap_price), as_currency(upl), as_currency(rpl)])
table = AsciiTable(data)
print(table.table)
print("your cash is "+as_currency(cash))
def main():
global cash
res = 0
trades = list()
while res != '4':
res = input("---------------------\n1. Trade\n2. Show Blotter\n3. Show P/L\n4. Quit\n---------------------")
if res == '1':
trade(trades)
if res == '2':
list_shares(trades)
if res == '3':
show_pl(trades)
if res == '4':
print("Bye!")
if __name__ == "__main__":
main()