# 一、通过tushare接口实时监控股票价格

## 1. 通过get_realtime_quotes获得股票的开盘价与实时价格

def get_open_price(code): #获得开盘价
df = ts.get_realtime_quotes(code)
open_price=df['open'][0]
return float(open_price)
def get_price(code): #获得股票实时价格
df = ts.get_realtime_quotes(code)
price=df['price'][0]
return float(price)


## 2. 计算1min时间内的股价波动

def cal_fluctuation(price_1min_ago,cur_price): #计算股票每分钟浮动比例
fluctuation=float((cur_price-price_1min_ago)/price_1min_ago)
return fluctuation


## 3. 编写自动定时函数实现固定1min间隔循环

def runTask(code,name,day=0, hour=0, min=0, second=0):
# Init time
now = datetime.now()#获取当前时间
strnow = now.strftime('%Y-%m-%d %H:%M:%S')
#print("now:", strnow)
# First next run time
period = timedelta(days=day, hours=hour, minutes=min, seconds=second)#获取时间间隔
next_time = now + period
strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S')
#print("next run:", strnext_time)
price_1min_ago=get_price(code)
price_2min_ago = get_price(code)
open_price=get_open_price(code)
if open_price==0:
open_price=price_2min_ago
index_up = 0
index_down = 0
while True:
# Get system current time
iter_now = datetime.now()
iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S')
if str(iter_now_time) == str(strnext_time):
# Get every start work time
#print("start work: %s" % iter_now_time)
cur_price=get_price(code)
print(cur_price)
cur_fluctuation=cal_fluctuation(price_1min_ago,cur_price)
cur_fluctuation_2min = cal_fluctuation(price_2min_ago, cur_price)#计算前一分钟内的股价变化值
accumulated_fluctuation=cal_fluctuation(open_price,cur_price)#计算当前股价与开盘价的累计波动值
if cur_fluctuation>=0.002:
print('')
print("Now: %s" % iter_now_time)
content = '%s 当前1min内股价浮动为：+%.2f%% ,推荐减仓,%s' % (name, cur_fluctuation*100,iter_now_time)#自定义提醒内容
sendEmail(content)#发送提醒邮件
print(content)
elif cur_fluctuation<=-0.002:
print('????????????????????????????????????????')
print("Now: %s" % iter_now_time)
content='%s 当前1min内股价浮动为：%.2f%% ,推荐加仓，%s'%(name,cur_fluctuation*100,iter_now_time)
sendEmail(content)
print(content)

if cur_fluctuation_2min>=0.002:
print('')
print("Now: %s" % iter_now_time)
content = '%s 当前2min内股价浮动为：%.2f%% ,当前股价：%.2f,%s' % (name, cur_fluctuation_2min*100,cur_price,iter_now_time)
sendEmail(content)
print(content)
elif cur_fluctuation_2min<=-0.002:
print('????????????????????????????????????????')
print("Now: %s" % iter_now_time)
content='%s 当前2min内股价浮动为：%.2f%% ,当前股价：%.2f，%s'%(name,cur_fluctuation_2min*100,cur_price,iter_now_time)
sendEmail(content)
print(content)

if (accumulated_fluctuation>=0.008 and index_up==0) or (accumulated_fluctuation>=0.012 and index_up==1):
print('！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！')
print("Now: %s" % iter_now_time)
content = '%s 已经上涨：+%.2f%% ,请关注实时行情' % (name, accumulated_fluctuation*100)
print(content)
sendEmail(content)
index_up+=1
elif (accumulated_fluctuation<=-0.008 and index_down==0) or (accumulated_fluctuation<=-0.012 and index_up==1):
print('！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！')
print("Now: %s" % iter_now_time)
content='%s 已经下跌：%.2f%% ,请关注实时行情'%(name,accumulated_fluctuation*100)
print(content)
sendEmail(content)
index_down+=1

price_2min_ago = price_1min_ago
price_1min_ago = cur_price
# Get next iteration time
iter_time = iter_now + period
strnext_time = iter_time.strftime('%Y-%m-%d %H:%M:%S')
#print("next_iter: %s" % strnext_time)
# Continue next iteration
continue


# 二、邮件提示

## 1. 设置邮箱信息

# 第三方 SMTP 服务
mail_host = "smtp.126.com"  # SMTP服务器
mail_user = "modas_***@126.com"  # 用户名
mail_pass = "******"  # 授权密码，非登录密码

sender = 'modas_***@126.com'# 发件人邮箱(最好写全, 不然会失败)


## 2. 通过SMTP工具发送邮件

def sendEmail(title):
content='Stock market realtime notice:\nWish you making fucking much money!\n\n\nProduced by Modas Li'
message = MIMEText(content, 'plain', 'utf-8')  # 内容, 格式, 编码
message['From'] = "{}".format(sender)
message['Subject'] = title
try:
smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
print("notice mail has been send successfully.")
except smtplib.SMTPException as e:
print(e)


# 三、设置脚本运行时间范围

## 1. 根据交易时间设置脚本开始和结束时间

start_dt=datetime(datetime.today().year,datetime.today().month,datetime.today().day,hour=9,minute=28,second=0)
stop_dt=datetime(datetime.today().year,datetime.today().month,datetime.today().day,hour=15,minute=30,second=0)

now=datetime.now()#.strftime( '%Y-%m-%d %H:%M:%S')


## 2. 以上证指数为例实现自动化交易时间内股票盯盘与提醒

import tushare as ts
from datetime import *
import smtplib
from email.mime.text import MIMEText

if __name__ == '__main__':
stock=['sh','上证指数']
# open_price=get_open_price(code)
while True:
if now>start_dt and now<stop_dt:
print('Start')
print(datetime.now())