python:以上证指数为例,随机漫步

python:以上证指数为例,随机漫步,随机游走。

stock_random_walk.py 不可相信随机数据。

# -*- coding: utf-8 -*-
""" 以上证指数为例,随机漫步,随机游走 """
import sys
from random import choice
import matplotlib.pyplot as plt
import pandas as pd

class RandomWalk():
    """A class to generate random walks."""
    
    def __init__(self, num=1000):
        """Initialize attributes of a walk."""
        self.num = num
        
        # 以上证指数为例,3200点/10 = 320 像素点
        self.x_values = [320] # 开盘价
        self.y_values = [321] # 收盘价

    def fill_walk(self):
        """计算 all the points in the walk."""
        
        # Keep taking steps until the walk reaches the desired length.
        while len(self.x_values) < self.num:
            
            # 假设上下浮动 10 像素点
            x_direction = choice([-1, 1])
            x_distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
            x_step = x_direction * x_distance
            
            y_direction = choice([-1, 1])
            y_distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
            y_step = y_direction * y_distance

            # 计算 the next x and y values. 总是以上日收盘价为基数
            next_x = self.y_values[-1] + x_step
            next_y = self.y_values[-1] + y_step
             
            # Reject moves that go nowhere.
            if next_x < 30 or next_y < 30:
                break
                        
            self.x_values.append(next_x)
            self.y_values.append(next_y)

# main()
if len(sys.argv) == 2:
    f1 = sys.argv[1] + '_walk.csv'
else:
    print('usage: python stock_random_walk.py shzs ')
    sys.exit(1)

rw = RandomWalk(num=1000)
rw.fill_walk()
n = len(rw.x_values)
fp = open(f1, 'w')
fp.write('xid,open,close\n')
for i in range(0, n):
    fp.write(f"{i},{rw.x_values[i]},{rw.y_values[i]}\n")
fp.close()
print(f1)
df = pd.read_csv(f1, index_col=0)
print(df.head())
# 计算30日移动均线 
df['ma30'] = df['close'].rolling(window=30).mean()
df[['open', 'close', 'ma30']].plot(grid=True)
plt.legend(loc='best', shadow=True)
plt.show()

运行 python stock_random_walk.py shzs

pylint stock_random_walk.py

以创业板指数为例,随机漫步,随机游走。

运行 python stock_random_walk2.py 000661  160 

# -*- coding: utf-8 -*-
import sys
from random import choice
import matplotlib.pyplot as plt
import pandas as pd

class RandomWalk():
    """A class to generate random walks."""
    
    def __init__(self, num=1000, start=100):
        """Initialize attributes of a walk."""
        self.num = num
        self.start = start
        # 初始 price
        self.x_values = [self.start] # 开盘价
        self.y_values = [self.start] # 收盘价

    def fill_walk(self):
        """计算 all the points in the walk."""
        clist = [x for x in range(0, self.y_values[-1]//10 +1)]
        print(clist)
        # Keep taking steps until the walk reaches the desired length.
        while len(self.x_values) < self.num:
            
            # 假设上下浮动 10%
            clist = [x for x in range(0, self.y_values[-1]//10 +1)]
            x_direction = choice([-1, 1])
            x_distance = choice(clist)
            x_step = x_direction * x_distance
            
            y_direction = choice([-1, 1])
            y_distance = choice(clist)
            y_step = y_direction * y_distance

            # 计算 the next x and y values. 总是以上日收盘价为基数
            next_x = self.y_values[-1] + x_step
            next_y = self.y_values[-1] + y_step
             
            # Reject moves that go nowhere.
            if next_x < 30 or next_y < 30:
                break
                        
            self.x_values.append(next_x)
            self.y_values.append(next_y)

# main()
if len(sys.argv) == 3:
    scode = sys.argv[1]
    begin = int(sys.argv[2])
else:
    print('usage: python stock_random_walk2.py stockcode begin ')
    sys.exit(1)

# 以长春高新为例,160元 = 160 像素点
rw = RandomWalk(num=1000, start=begin)
rw.fill_walk()
n = len(rw.x_values)
f1 = scode + '_walk.csv'
fp = open(f1, 'w')
fp.write('xid,open,close\n')
for i in range(0, n):
    fp.write(f"{i},{rw.x_values[i]},{rw.y_values[i]}\n")
fp.close()
print(f1)
df = pd.read_csv(f1, index_col=0)
# 计算30日移动均线 
df['ma30'] = df['close'].rolling(window=30).mean()
print(df.head())
df[['open', 'close', 'ma30']].plot(grid=True, title=scode)
plt.legend(loc='best', shadow=True)
plt.show()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值