4
\$\begingroup\$

Introduction

Greetings fellow traders, you have just entered the Stack Exchange stock exchange. Here you will compete to earn the money by buying and selling shares (unfortunately, we only have the single market).

Gameplay

You will need to write a program that buys and sells shares. At the start, the market price is 200, you have $10000 and no shares. Each time you buy or sell a share, the market price goes up or down.

There will be ten games played, each game with fifty rounds. At the end, the person with the highest amount of money wins.

The first game will start with at least ten entrants

Information

Your program will be supplied with three arguments:

Your bank balance
Number of shares
Market value
Round number

And you can supply one of three commands:

Name  | Command
Buy:  | b [no. shares]
Sell: | s [no. shares]
Pass: | p

For example, if you were to run the program straight:

python testprog.py 10000 0 200 1

b 100

I would suggest recording change to see if people are buying or selling shares to prevent a crash.

If you try to spend money you don't have or sell stocks that you don't have, your request will be rejected.

You are allowed to have ONE text file for recording change in stock price.

The program will be run on Ubuntu Linux.

Controller program:

# Orchestration Program

from subprocess import Popen, PIPE
import time

class Program:
     money=None
     stocks=None
     command=None

# Define class instances here
programvars = {}
# Program names here
programs = []
leaderboard = {"1": 0,
               "2": 0,
               "3": 0,
               "4": 0,
               "5": 0,
               "6": 0,
               "7": 0,
               "8": 0,
               "9": 0,
               "10": 0}
scores = []

# Programs start in a different order each time
programs = sorted(programs, key=lambda k: random.random())

f = open("stockprice.txt", "r")
f = f.split('|')
stockprice = int(f[0])
roundnum = int(f[1])
f.close()

programsfifty = programs*50

# Initialising variables
for i in programsfifty:
    #try:
    g = open(i + "properties.txt", "r")
    print(i)
    properties = g.read()
    properties = properties.split("|")

    programvars[i].money = int(properties[0])
    programvars[i].stocks = int(properties[1])
    programvars[i].command = str(properties[2])

    g.close()

    #except:
    #    pass

# Main event loop
for j in programs:
    if stockprice < 0:
        stockprice = 0

    # Example: python3 test.py [money] [stocks] [price]
    command = programvars[j].command + ' ' + str(programvars[j].money) + ' ' + str(programvars[j].stocks) + ' ' + str(stockprice) + ' ' + str(roundnum)

    out = Popen(command, shell=True, stdout=PIPE).communicate()[0].decode('utf-8')
    out = out.replace('\n', '')
    # If run on Windows
    out = out.replace('\r', '')

    if out == 'p':
        pass

    else:
        action = out.split(' ')

        if action[0] == 'b':
            # Buying shares
            if programvars[j].money - int(action[1])*stockprice > -1:
                     programvars[j].money -= int(action[1])*stockprice
                     programvars[j].stocks += int(action[1])
                     stockprice += int(action[1])

        elif action[0] == 's':
             if programvars[j].stocks - int(action[1]) > -1:
                 # Selling shares
                 programvars[j].money += int(action[1])*stockprice
                 programvars[j].stocks -= int(action[1])
                 stockprice -= int(action[1])

for k in programs:
    # Writing properties to files
    n = open(k + "properties.txt", "w")
    n.write(str(programvars[k].money)+"|"+str(programvars[k].stocks)+"|"+str(programvars[k].command))
    n.flush()
    n.close

    # Add all scores to an array for sorting
    scores.append(programvars[k].money)

scores = sorted(scores, reverse=True)
print(scores)
# Find richest program
for l in programs:
    for m in range(0, len(scores)):
        if programs.index(l) == m:
            leaderboard[programs[m]] = leaderboard.pop(str(m+1))

scorekeys = sorted(leaderboard.keys(), reverse=True)
print(scorekeys)
# Write the leaderboard
s = open("leaderboard"+str(time.localtime()[0])+"-"+str(time.localtime()[1])+"-"+str(time.localtime()[2])+".txt", "w+")

# Some problems with this, but can be worked out manually
for n in scores:
    s.write(str(scores.index(n)+1) + ": " + scorekeys[scores.index(n)] + " " + str(n) + "\n")

s.flush()
s.close()

roundnum += 1

# Write the stockprice
b = open("stockprice.txt", "w")
b.write(str(stockprice) + '|' + str(roundnum))
b.flush()
b.close()

Good luck!

\$\endgroup\$

closed as unclear what you're asking by Martin Ender, plannapus, Peter Taylor, William Barbosa, rdans Aug 13 '14 at 12:46

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    \$\begingroup\$ "The scoring system is calculated by multiplying the amount of money you have by the number of shares you have and dividing that by zero.". So my score is always +Inf no matter what I do? \$\endgroup\$ – Philipp Aug 13 '14 at 11:22
  • \$\begingroup\$ @Philipp Ahh, that's supposed to be 200 \$\endgroup\$ – Beta Decay Aug 13 '14 at 11:25
  • \$\begingroup\$ I don't see any time loop in your program. Is each program called only once? And that in a deterministic order which depends on how you add them to the programs array at the top? \$\endgroup\$ – Martin Ender Aug 13 '14 at 11:28
  • 3
    \$\begingroup\$ The scoring system makes no sense. Surely the only reasonable way to score is money plus share value? \$\endgroup\$ – Peter Taylor Aug 13 '14 at 11:48
  • 2
    \$\begingroup\$ @BetaDecay your question has potential but it needs a lot more work before its ready for the site. Please post it on the question sandbox for more feedback: meta.codegolf.stackexchange.com/questions/1847/… \$\endgroup\$ – rdans Aug 13 '14 at 12:48
3
\$\begingroup\$

Short-Sighted Seller - Perl

This bot has the simple strategy of maximizing its score at the end of every trading opportunity. It acts as if every round were the last round.

($money,$stocks,$price) = @ARGV;
$value = $money + $stocks * $price;
if($price > 0){
 $optimal = $value / (2 * $price);
}
else{
 $optimal = 9x15 + $stocks; #suitably large number
}
$rounded = int($optimal + 0.5);
$delta = $rounded - $stocks;
if($delta > 0){
 print "b $delta";
}
elsif($delta < 0){
 $delta *= -1;
 print "s $delta";
}
elsif($delta == 0){
 print "p";
}

You can run it like so:

perl shortsightedseller.plx [money] [stocks] [price]
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.