Skip to content

Instantly share code, notes, and snippets.

@zweizeichen
Created October 3, 2012 12:03
Show Gist options
  • Save zweizeichen/3826585 to your computer and use it in GitHub Desktop.
Save zweizeichen/3826585 to your computer and use it in GitHub Desktop.
Element43 margin script
- extends "base.haml"
- load cache
- load humanize
- block title
element43 - Station - Best Margins
- block content
%h1
{{station.name}}
.row-fluid
.span12
%table.table.table-striped.table-condensed
%thead
%tr
%th
%th
Daily Volume
%th
Best Ask
%th
Best Bid
%th
Margin
%tbody
- for item in top_margins
%tr
%td
%a{'href':'/market/region/{{station.region.id}}/{{item.type.id}}/'}
{{item.type.name}}
%td
{{item.volume|intcomma}}
%td
{{item.top_ask|intcomma}} ISK
%td
{{item.top_bid|intcomma}} ISK
%td
{{item.margin|floatformat:2}} %
def margins(request, station_id = 60003760):
"""
Generates a list like http://goonmetrics.com/importing/
"""
# Get station object - default to CNAP if something goes wrong
try:
station = StaStation.objects.get(id = station_id)
except:
station_id = 60003760
station = StaStation.objects.get(id = station_id)
# Get all orders grouped by type
top_ask = Orders.objects.filter(stastation = station, is_bid = False).values('invtype').annotate(min_price=Min('price'))
top_bid = Orders.objects.filter(stastation = station, is_bid = True).values('invtype').annotate(max_price=Max('price'))
# Get re-structured dicts and sets
ask = {}
bid = {}
for item in top_ask:
ask[item['invtype']] = item['min_price']
ask_set = set(ask)
for item in top_bid:
bid[item['invtype']] = item['max_price']
bid_set = set(bid)
# Get types with both buy and sell orders
types = ask_set.intersection(bid_set)
# Store margins
top_margins = []
for invtype in types:
margin = ((ask[invtype] / bid[invtype]) * 100)
try:
volume = ast.literal_eval(History.objects.get(mapregion = station.region, invtype_id = invtype).history_data).itervalues().next()[4]
except:
volume = 0
score = volume * margin
# Filter Junk
if (margin > 0) and (margin < 10000):
top_margins.append({'type': invtype, 'margin': margin, 'score': score, 'volume':volume})
# Sort margins
top_margins = sorted(top_margins, key=lambda k: k['score'])
top_margins.reverse()
del top_margins[100:]
# Take top 50 margins
for margin in top_margins:
margin['type'] = InvType.objects.get(id = margin['type'])
margin['top_ask'] = Orders.objects.filter(stastation = station, is_bid = False, invtype_id = margin['type']).aggregate(Min('price'))['price__min']
margin['top_bid'] = Orders.objects.filter(stastation = station, is_bid = True, invtype_id = margin['type']).aggregate(Max('price'))['price__max']
rcontext = RequestContext(request, {'station':station, 'top_margins':top_margins})
return render_to_response('trading/station/station.haml', rcontext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment