## 调用包
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)