mardi 15 décembre 2015

Why does my code not seem random?

I'm trying to create a basic code to simulate stock market behavior as an exercise in my programming class. It's based off of weighted randomness and is displayed through pylab. For the most part it looks good, but for no matter how many trials I run there seems to be a tad that does not look random. From 1-50 of each random update, there seems to be a definitive upwards trend that is not reflected anywhere else in the series. The weighted values are not altered anywhere else in the code, so this trend should be an aberration seeing that I make sure that the results given are the average of a great many trials. Would anyone know what's wrong with my code that causes this to happen? Thanks!

class Simulation(object):

    def __init__(self, netPos=300, downChance=.1, downTrend=.06, start = 1285.85, time = 0, recession = False):

        self.netPos = netPos
        self.downChance = downChance
        self.downTrend = downTrend
        self.value = start
        self.time = time
        self.recession = False

    def getValue(self):
        return self.value

    def update(self):
        if not self.recession:
            if random.random() < self.downTrend:
                self.recession = True
            if random.random() > self.downChance:
                self.value += random.random() * self.netPos 
            else:
                self.value -= random.random() * self.netPos 
        else:
            if random.random() < self.downTrend:
                self.recession = False
            if random.random() < self.downChance:
                self.value += random.random() * self.netPos 
            else:
                self.value -= random.random() * self.netPos 

times = 5000
values = []  
for i in range(1200):  
    values += [0]  
for x in range(times):  
    runOnce = Simulation()  
    for y in range(1200):  
        values[y] += runOnce.getValue()  
        runOnce.update()  
for i in range(1200):  
    values[i] = values[i] / times  
def plottem(x,y):  
    pylab.plot(range(1200), values[x:y-1], label="Trend")   
    pylab.title("Simulated Trend")  
    pylab.xlabel("Time")  
    pylab.ylabel("Relative Value")  
    pylab.legend(loc = 1)  
    pylab.show()  
def getChange(x,y):  
    print (values[x] - values[y-1])/(x-y-1)  

plottem(0,1999)  

Results:

the surprising results




Aucun commentaire:

Enregistrer un commentaire