Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bitbar Menubar script to track the daily performance and total worth of your stock portfolio.
#!/usr/bin/python
import urllib2
import json
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
RED = "#ff0000"
GREEN = "#00af00"
def bitbar_main(portfolio):
query = ','.join([k for k,v in portfolio.iteritems()])
url = "http://finance.google.com/finance/info?client=ig&q=" + query
response = urllib2.urlopen(url).read()
o = json.loads(response[4:-1])
today_change_total = 0.0
today_percent_total = 0.0
all_change_total = 0.0
all_percent_total = 0.0
total_investment = 0.0
total_inv_value = 0.0
results = { }
for ticker in o:
name = ticker["t"]
current = float(ticker["l"])
t_change = float(ticker["c"])
t_percent = float(ticker["cp"])
stock_value = 0.0
bought_at = 0.0
today_change_total += t_change
today_percent_total += t_percent
trades = portfolio[name.upper()]
for trade in trades:
stock_value += float(trade[0]) * current
bought_at += float(trade[0]) * float(trade[1])
total_investment += bought_at
total_inv_value += stock_value
profit_loss = stock_value - bought_at
profit_loss_percent = profit_loss / bought_at * 100
results[name] = (name, current, t_change, t_percent, stock_value, profit_loss, profit_loss_percent)
today_percent_total = today_percent_total / len(o)
all_change_total = total_inv_value - total_investment
all_percent_total = all_change_total / total_investment * 100
print "%.2f|color=%s" % (today_change_total, GREEN if today_change_total > 0 else RED)
print "---"
print "TOTAL: %s -> %s" % (intWithCommas(total_investment), intWithCommas(total_inv_value))
print "Hold ALT for all-time stats"
print "---"
print "Today"
print "All Time|alternate=true"
print "---"
print "%+.2f (%+.2f%%)|color=%s" % (today_change_total, today_percent_total, GREEN if today_change_total > 0 else RED)
print "%+.2f (%+.2f%%)|color=%s alternate=true" % (all_change_total, all_percent_total, GREEN if all_change_total > 0 else RED)
print "---"
# show individual stocks
for result in results.values():
print "%s %s (%+.2f, %+.2f%%)|color=%s" % (result[0], result[1], float(result[2]), float(result[3]), GREEN if float(result[2]) > 0 else RED)
print "%s %s (%+.2f, %+.2f%%)|color=%s alternate=true" % (result[0], float(result[4]), float(result[5]), float(result[6]), GREEN if float(result[5]) > 0 else RED)
print "---"
print "Refresh|refresh=true"
def intWithCommas(x):
return locale.format("%d", x, grouping=True)
## Define your portfolio manually:
## For example we bought 10 shares of AAPL at 100, and 3 at 101
## And 5 shares of GOOG at 123, and 13 more at 234
## {
## 'AAPL': [(10, 100), (3, 101)],
## 'GOOG': [(5, 123), (13, 234)]
## }
portfolio = {
'AAPL': [(10, 100), (3, 101)],
'GOOG': [(5, 123), (13, 234)]
}
bitbar_main(portfolio)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment