Difference between revisions of "Programming performance/hay.steve Python"
Jump to navigation
Jump to search
(Implementation time: 2 hours. Python experience: 3 days.) |
m (Just some layout tweaks.) |
||
Line 1: | Line 1: | ||
+ | * '''Implementation time''': 2 hours. |
||
+ | * '''Experience''': 3 days. |
||
+ | |||
+ | === Code === |
||
+ | |||
+ | <code-python> |
||
from heapq import heappush, heappop, nsmallest |
from heapq import heappush, heappop, nsmallest |
||
Line 55: | Line 61: | ||
print "Percent Gain:", (cash-beginningBalance)/beginningBalance*100, "%." |
print "Percent Gain:", (cash-beginningBalance)/beginningBalance*100, "%." |
||
+ | </code-python> |
||
--[[User:Hay.steve|Hay.steve]] 01:53, 8 March 2007 (UTC) |
--[[User:Hay.steve|Hay.steve]] 01:53, 8 March 2007 (UTC) |
Revision as of 02:44, 8 March 2007
- Implementation time: 2 hours.
- Experience: 3 days.
Code
<code-python> from heapq import heappush, heappop, nsmallest
print "Implementation time: 2 hours. Python experience: 3 days."
filename = "gspc.txt"
days = []
for f in open(filename):
if f[0] == '#': continue linelist = f.split(' ') heappush( days, linelist )
cash = 10000
previousClose = -1.0
currentClose = 0
shares = []
beginningBalance = cash
print "Beginning Balance:", cash while days != []:
day = heappop( days ) i = day[0] currentClose = float( day[4] )
if previousClose != -1.0: percentGain = ( currentClose - previousClose ) / previousClose if percentGain < -0.03: numShares = 0.1 * cash / currentClose heappush( shares, (currentClose, numShares) ) cash = 0.9 * cash print "On", i, ", bought" , numShares , "shares at" , currentClose , "."
else : while shares != [] and nsmallest(1, shares)[0][0] <= currentClose / 1.06: sell = heappop( shares ) cash += sell[1] * currentClose print "On", i, "sold" , sell[1] , "shares at" , currentClose , "."
previousClose = currentClose
while shares != []:
sell = heappop( shares ) cash += sell[1] * currentClose print "Sold" , sell[1] , "shares at" , currentClose , "."
print "Beginning balance:", beginningBalance
print "Ending balance:", cash
print "Percent Gain:", (cash-beginningBalance)/beginningBalance*100, "%." </code-python>
--Hay.steve 01:53, 8 March 2007 (UTC)