1. 程式人生 > >Python股票盯盤助手

Python股票盯盤助手

學習股票交易有一段時間了,還未逃脫盯盤的 初級階段,索性寫了一段微信盯盤指令碼,將賬戶資訊實時傳送到微信助手中

  • 先匯入需要的包
import tushare as ts
import itchat, time
from itchat.content import TEXT
import datetime
  • 登陸微信
itchat.logout()
itchat.auto_login(hotReload=True)
  • 編寫主要計算函式,通過給定的列表獲取實時行情資訊,並計算股票收益情況
#定義股票列表,格式為【‘股票名稱_股票程式碼_建倉價格_數量’】,可建多個倉位
#stock_list=['中科曙光_603019_44.836_200','大華股份_002236_12.830_100','掌閱科技_603533_19.370_100','紫光股份_000938_35.850_100']
#計算函式,通過給定的股票列表,獲取實時行情資訊,並計算收益情況
def earnings(stock_list):
    message=nowTime+"收益播報:\r\n"+"\n"
    #獲取上證指數
    sh=ts.get_realtime_quotes('sh')
    sh_pro=float(sh.to_dict()['price'][0])-float(sh.to_dict()['pre_close'][0])
    message+="{}\t{}\t{}\t{}".format("上證指數",str(round(float(sh.to_dict()['price'][0]),2)),str(round(sh_pro,3)),sh.to_dict()['time'][0])+"\r\n"
    #message+=sh.to_dict()['name'][0]+"\t"+sh.to_dict()['price'][0]+"\t"+str(round(sh_pro,4))+"\t"+sh.to_dict()['time'][0]+"\r\n"
    pro_sum=0.000
    #遍歷股票列表,分割出股票的名稱,程式碼,價格,數量
    for stock in stock_list:
        #名稱
        stock_name=stock.split("_")[0]
        #程式碼
        stock_code=stock.split("_")[1]
        #價格
        stock_price=stock.split("_")[2]
        #數量
        stock_num=stock.split("_")[3]
        
        #通過ts獲取股票實時資訊
        df = ts.get_realtime_quotes(stock_code)
        
        #計算收益
        profit=(float(df['price'])-float(stock_price))*int(stock_num)
        pro_sum+=profit
        
        #寫成txt
        str_pro="{}\t{}\t{}\t{}".format(stock_name,str(round(float(df.to_dict()['price'][0]),2)),str(round(profit,4)),df.to_dict()['time'][0])
        #str_pro=stock_name+"\t"+str(round(float(df.to_dict()['price'][0]),2))+"\t"+str(round(profit,4))+"\t"+df.to_dict()['time'][0]
        message+=str_pro+"\r\n"
    sh=ts.get_realtime_quotes('sh')
    
    message+='總盈虧為: '+str(round(pro_sum,4))
    return message
  
  • 通過while死迴圈不停的執行上文的函式,並將結果傳送到微信上
stock_list1=['中科曙光_603019_44.836_200','大華股份_002236_12.830_100','掌閱科技_603533_19.370_100','紫光股份_000938_35.850_100']
while True:
    nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#現在
    string = earnings(stock_list1)
    print(string)
    #通過微信助手傳送給自己
    itchat.send(msg=string, toUserName="filehelper")
    #設定間隔時間(秒)
    time.sleep(60)