-
Notifications
You must be signed in to change notification settings - Fork 4
/
randomExample.py
97 lines (76 loc) · 2.8 KB
/
randomExample.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
#sequence of events
#for every loop:
#picks a random stock
#buys it immediately
#sells it at a random price
# import sys
import random
# sys.path.insert(0, '../')
from traderbot import TraderBot
#riskFactor represents how risky the bot is in general
#it affects both how much money it's willing to wager, and how long it'll wait
#before giving up
riskFactor = .05 #fraction of original price
riskFactorMultiplier = 3
robot = TraderBot()
stockArray = robot.getSymbols()
startingPrice = -1
while (True):
#checks if portfolio is empty
portfolio = robot.getPortfolio()
currentlyOwnedStock = ""
stockQuantity = -1
empty = True
for stock in stockArray:
if portfolio[stock] != 0:
empty=False
currentlyOwnedStock = stock
stockQuantity=portfolio[stock]
if empty:
print "portfolio is empty, picking a stock to buy"
#buy algorithm
#picks random stock
tickerNumber = random.randint(0, len(stockArray) -1)
ticker = stockArray[tickerNumber]
print "decided to buy stock with ticker :", ticker
startingPrice = robot.getPrice(ticker)
print "price of stock: $", startingPrice, "per share"
#determines how much money it's willing to wager at once
money = robot.getFunds()
maxMoney = money*riskFactor*riskFactorMultiplier
print "bot is willing to risk $" , maxMoney
shares = (int)(maxMoney/startingPrice)
print "purchasing", shares, "shares at $" , startingPrice, "per share"
#ourchases stock
result = robot.bid(shares, startingPrice, ticker)
if result == 'Accepted':
print "trade accepted"
elif result == 'Unsuccesful':
print "trade declined"
elif result == 'Pending':
print "trade pending"
else:
print "not a recognizable order state"
if not empty:
#sell algorithm
currentPrice = robot.getPrice(currentlyOwnedStock)
priceDifference = (currentPrice - startingPrice)/startingPrice
print "percentage difference between purchasing price and current price: ", priceDifference
#price has gone down too much, give up and sell
result = ""
if priceDifference < 0.05:
print "price too low, giving up and selling at a loss"
result = robot.ask(stockQuantity, currentPrice, currentlyOwnedStock)
print "selling", stockQuantity, "shares at $" , currentPrice, "per share"
elif priceDifference > 0.05:
"price increased sufficiently, selling for a profit"
result = robot.ask(stockQuantity, currentPrice, currentlyOwnedStock)
print "selling", stockQuantity, "shares at $" , currentPrice, "per share"
if result == 'Accepted':
print "trade accepted"
elif result == 'Unsuccesful':
print "trade declined"
elif result == 'Pending':
print "trade pending"
else:
print "not a recognizable order state"