MIT_股票市场仿真

## 调用包
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import random
import numpy as np

随机漫步的假设

  • 当前的价格包含了所有信息
  • 股票的波动不会超过市场基准表现

考虑到势头的影响可以加入 momentum 变量,第二天的变化会随机延续上一次的价格变化

class Stocks(object):
    def __init__(self, price, distribution):
        self.distribution = distribution
        self.history = []
        self.lastChange = 0
        self.setPrice(price)

    def setPrice(self, price):
        self.price = price
        self.history.append(price)
    
    def getPrice(self):
        return self.price
    
    def getTicker(self):
        return self.ticker
    
    def makeMove(self, mktBias, mo):
        """
        param mo: bool # momentum 
        Memoryless (Poisson)
        since all information is in the current price
        """
        old_price = self.price
        base_move = self.distribution() + mktBias
        self.price = self.price * (1.0 + base_move) # self price is also an influnence
        # print('now price is {}'.format(self.price))
        if mo: # if belevie momentum
            self.price += random.gauss(0.5, 0.5) * self.lastChange 
        if self.price < 0.01:
            self.price = 0
        self.history.append(self.price)
        self.lastChange = old_price - self.price
    
    def showHistory(self, flg_num):
        plt.plot(self.history)
        plt.title('Price influence of {}'.format(flg_num))
        plt.xlabel('Days')
        plt.ylabel('Price')

测试3只起始值为100的股票,两种分布的100天的走势 (带有趋势 mo = True # momentum

def unitTestStock(mo_in):
    def runSim(stks, flg, mo):
        mean = 0.0
        for s in stks:
            for d in range(numDays):
                s.makeMove(bias, mo)
                # print('now price is {}'.format(s.price))
            s.showHistory(flg)
            mean += s.getPrice()
            n = len(s.history)
        mean = mean / numStks
        
        plt.plot([mean] * n)
        plt.show()

    numStks = 3
    numDays = 100 
    stks1, stks2 = [], []
    bias = 0.0 
    mo = mo_in
    for i in range(numStks):
        volatility = random.uniform(0, 0.2)
        d1_ = lambda: random.uniform(-1 * volatility, volatility)
        d2_ = lambda: random.gauss(0, volatility / 2)
        stks1.append(Stocks(100, d1_))
        stks2.append(Stocks(100, d2_))
    runSim(stks1, 1, mo)
    runSim(stks2, 2, mo)


unitTestStock(True)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Scc_hy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值