Python:实时查看股票账户

import time
import tushare as ts
from prettytable import PrettyTable
from colorama import init, Fore, Back, Style


class Colored(object):
    #  前景色:红色  背景色:默认
    def red(self, s):
        return Fore.LIGHTRED_EX + s + Fore.RESET
    #  前景色:绿色  背景色:默认
    def green(self, s):
        return Fore.LIGHTGREEN_EX + s + Fore.RESET
    def yellow(self, s):
        return Fore.LIGHTYELLOW_EX + s + Fore.RESET
    def white(self,s):
        return Fore.LIGHTWHITE_EX + s + Fore.RESET
    def blue(self,s):
        return Fore.LIGHTBLUE_EX + s + Fore.RESET


def func_stock(stock, num):
    df_stock = ts.get_realtime_quotes(stock)  # Single stock symbol
    df_stock[['code', 'name', 'pre_close', 'price',
              'bid', 'ask', 'volume', 'amount', 'time']]
    name = df_stock['name'][0]
    code = df_stock['code'][0]

    price = float(df_stock['price'][0])

    str_price = str(df_stock['price'][0])
    if price == 0:
        str_price = str(df_stock['pre_close'][0])

    curr = str(price)
    if price == 0:
        curr = str(df_stock['pre_close'][0])

    total = float(curr) / float(str(df_stock['pre_close'][0])) - 1
    total = round(total * 100, 2)

    shi_zi = round(float(curr) * num / 10000, 4)

    stock = [name, code, num, str_price, total, shi_zi]
    return stock


my_stock = [
    ['002882', 46100],
    ['601828', 12000],
    ['601155', 8800],
    ['000732', 0],
    ['300263', 0],
    ['600172', 0],
    ['002179', 0],
    ['300007', 0],
    ['300179', 0],
    ['601607', 0],
    ['002146', 0],
    ['000628', 0],
    ['603658', 0],
    ['000555', 20500],
    ['000885', 0],
    ['601360', 0]]


df_total = 0
table = PrettyTable(["名称", "代码", "持有", "当前价", "涨跌幅%", "市值(万元)"])
color = Colored()  #创建Colored对象

for i in my_stock:
    df = func_stock(i[0], i[1])
    if df[2]>0:
        df[0] = color.blue(df[0])
    if df[4] >= 0:
        df[4] = color.red(str(df[4]))
    else:
        df[4] = color.green(str(df[4]))
    table.add_row(df)
    df_total += df[5]

dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(Fore.MAGENTA + '账户市值(', dt, ')', end=' ')
print(Style.RESET_ALL)
print(table)

print(Fore.RED + '当前总市值:', round(df_total, 2), '万元。', end=' ')
print(Style.RESET_ALL)

测试脚本

(py3) [root@nginx ok]# python shizi.py

点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注