设计一个名为Stock的类来表示一个公司的股票,包括以下内容:
1)一个名为no的私有字符串数据域表示股票的符号(代码)
2)一个名为name的私有字符串数据域表示股票的名称
3)私有浮点数openPrice,closePrice,highPrice,lowPrice分别表示开盘价,收盘价,最高价,最低价
4)一个名为day的数据域,表示股票的日期
5)一个构造方法创建一支具有特定代码、名字、各种价格,发生日期的股票
6)一个返回股票名字的get方法
7)一个返回股票代码的get方法
8)获取和设置股票各种价格的get和set方法
9)一个名为getChangePercent()方法返回从openPrice到closePrice变化的百分比。
11)编写一个程序,创建一个Stock类,它的代码是601318,名字是中国平安,前一天的价格是63.21,收盘价格是64.39,显示该股票的相关信息及价格改变百分比。
12)连续随机生成10天股票价格(价格区间50~80,每天涨停跌停10%),并用turtle库画出10天的股票K线图
import random
import turtle
class Stock:
def __init__(self, no, name, openPrice, closePrice, highPrice, lowPrice, day):
self.__no = no
self.__name = name
self.__openPrice = openPrice
self.__closePrice = closePrice
self.__highPrice = highPrice
self.__lowPrice = lowPrice
self.__day = day
def getName(self):
return self.__name
def getNo(self):
return self.__no
def getOpenPrice(self):
return self.__openPrice
def setOpenPrice(self, openPrice):
self.__openPrice = openPrice
def getClosePrice(self):
return self.__closePrice
def setClosePrice(self, closePrice):
self.__closePrice = closePrice
def getHighPrice(self):
return self.__highPrice
def setHighPrice(self, highPrice):
self.__highPrice = highPrice
def getLowPrice(self):
return self.__lowPrice
def setLowPrice(self, lowPrice):
self.__lowPrice = lowPrice
def getDay(self):
return self.__day
def getChangePercent(self):
return (self.__closePrice - self.__openPrice) / self.__openPrice * 100
# 创建一个Stock对象
stock = Stock('601318', '中国平安', 63.21, 64.39, 65.8, 62.8, '2023-06-23')
# 打印股票信息及价格变化百分比
print('股票名称:', stock.getName())
print('股票代码:', stock.getNo())
print('开盘价:', stock.getOpenPrice())
print('收盘价:', stock.getClosePrice())
print('最高价:', stock.getHighPrice())
print('最低价:', stock.getLowPrice())
print('日期:', stock.getDay())
print('价格变化百分比:{:.2f}%'.format(stock.getChangePercent()))
# 生成10天随机股票价格
prices = []
price = 65
for i in range(10):
change = random.uniform(-0.1, 0.1)
price += price * change
if price > 80:
price = 80
elif price < 50:
price = 50
prices.append(price)
# 使用turtle库画出K线图
t = turtle.Turtle()
t.color('red')
t.speed(0)
t.penup()
t.goto(-400, 0)
t.pendown()
for i in range(len(prices)):
t.left(90)
t.forward(prices[i] * 10)
t.right(90)
t.forward(10)
t.right(90)
t.forward(prices[i] * 10)
t.left(90)
t.penup()
t.forward(20)
t.pendown()
turtle.done()