欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > Flask发布一个及时止损(止盈)服务(二)

Flask发布一个及时止损(止盈)服务(二)

2025/5/12 23:06:37 来源:https://blog.csdn.net/turui/article/details/136518857  浏览:    关键词:Flask发布一个及时止损(止盈)服务(二)

生成可视化的止盈止损结果(图片)

妈的,还是得用 akshare,还需要指定python版本3.9以上

conda remove -n fonxsys --all
conda search pythonconda create -n fonxsys python=3.9
conda activate fonxsys
python.exe -m pip install --upgrade pip --userpip install --upgrade pip #失败,网络问题
pip install pip -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com --user --upgrade #失败python.exe -m pip install pip -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com --user --upgradeconda config --show channels 

安装AKShare 

使用阿里云安装 akshare基于 Python 的代码如下(不是本次重点)
pip install akshare -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com --upgrade基于 Anaconda 的代码如下,"pip install --user" 的意思是使用当前用户的权限安装 Python 包
pip install akshare -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com --user --upgrade

 安装spyder(不知道清华源的为啥又不行了)

conda install spyder

安装基本的一些包

conda install numpy pandas pyquery

  安装金融绘图库

pip install mplfinance --user

添加引用代码

import mplfinance as mpf
import matplotlib.pyplot as plt

函数,获取历史数据

def getdata_his(code,date_buy):df = pd.DataFrame(columns=['日期','开盘','收盘','最高','最低','成交量'])    #print(code)#print(date_buy)if (code[0] == '0' or code[0] == '3' or code[0] == '6'):        df = ak.stock_zh_a_hist(symbol=code, period="daily", start_date=date_buy.replace("-", ""), adjust="qfq")df = df[['日期','开盘','收盘','最高','最低','成交量']] df.columns = ['date', 'open','close','high','low','volume']      df['date'] = pd.to_datetime(df['date'])df.set_index('date', inplace=True)elif (code[0] == '1' or code[0]=='5'):#ETF基金的处理比较特殊,要分,历史行情,当前行情if code[0] == '1':symbol = "sz"+code        else:symbol = "sh"+code#历史行情        df = ak.fund_etf_hist_sina(symbol)df['date'] = pd.to_datetime(df['date'])df.set_index('date', inplace=True)df = df[df.index>= pd.Timestamp(date_buy)]    #当日行情df_today = ak.fund_etf_spot_em()    #print(df_today)df_today = df_today.loc[df_today['代码']==code] df_today = df_today[['名称','开盘价','最新价','最高价','最低价','成交量']]df_today.columns = ['date', 'open','close','high','low','volume']df_today.loc[df_today.index[0],'date']=dt.datetime.now().strftime("%Y-%m-%d")                      df_today['date'] = pd.to_datetime(df_today['date'])df_today.set_index('date', inplace=True)        #合并行情if df.index[-1] != pd.to_datetime(dt.datetime.now().strftime("%Y-%m-%d")):df = pd.concat([df,df_today],ignore_index = False)#df['ma5'] = df['close'].rolling(5).mean()print(df)return df

函数,获取当前信息(主要就是股票名称了)

def getdata_online(code):if code[0] == '0':symbol = "sz"+codeelif code[0] == '1':symbol = "s_sz"+codeelif code[0] == '3':symbol = "sz"+codeelif code[0] == '5':symbol = "s_sh"+codeelif code[0] == '6':symbol = "sh"+codeurl = "http://hq.sinajs.cn/list="+symbolheaders={'Referer':'https://finance.sina.com.cn/'}page = requests.get(url,headers=headers)stock_info = page.text#print(stock_info)mt_info = stock_info.split(",")#爬取到数据信息name    = mt_info[0].split("\"")[1]return name

函数 生成数据

code="002962"
price_buy=14.682
date_buy="2024-03-05"
price_stop_loss=14.40def make_data(code,price_buy,date_buy):#具体计算开始df_his = getdata_his(code,date_buy)    if len(df_his) <= 0 : return Nonename = getdata_online(code)if name == "" : return Nonereturn name,df_his

函数 图片绘制的一些初始化

def init_plt():'''# 设置mplfinance的蜡烛颜色,up为阳线颜色,down为阴线颜色my_color = plt.make_marketcolors(up='r',down='g',edge='inherit',wick='inherit',volume='inherit')# 设置图表的背景色my_style = plt.make_mpf_style(marketcolors=my_color,figcolor='(0.82, 0.83, 0.85)',gridcolor='(0.82, 0.83, 0.85)')plt.plot(df_his,type='candle',style=my_style,ylabel='price(RMB)')sys.exit()'''plt.figure(figsize=(8,4),  # inchesdpi=200, # dot-per-inchfacecolor='#BBBBBB',frameon=True, # 画布边框) # X轴范围#plt.xlim((2000,2010))  # X轴的起点和终点# Y轴范围#plt.ylim(6e9,7e9) # Y轴的起点和终点# X轴刻度#plt.xticks(df_his.index,df_his.index.strftime("%m-%d"))# X轴刻度#plt.yticks(np.arange(6e9,7e9+1e8,1e8))'''df.plot(kind = "line",figsize = (6, 4),title = "title",legend = True,ylim = [-20, 20], yticks = list(range(-20, 20, 10)),grid = False,style = "--g", colormap = "cool", alpha = 0.8,rot = 45,use_index = True,subplots = True)'''plt.rcParams['font.sans-serif'] = 'SimHei'  # 设置字体为简黑(SimHei)plt.rcParams['font.sans-serif'] = 'FangSong'  # 设置字体为仿宋(FangSong)plt.rcParams['axes.unicode_minus']=False

函数 生成可视化的图片

def makepic(code,price_buy,date_buy,name,df_his):now = df_his.iloc[-1,1]            price_stop_loss = df_his.min()['low']      price_high = df_his.max()['high']df_his['price_buy'] = price_buydf_his['price_high'] = price_highdf_his['price_stop_loss'] = price_stop_lossprofit_base = 0.618price_stop_surplus = price_buy+(price_high-price_buy)*profit_base;df_his['price_stop_surplus'] = price_stop_surplusprint("{} {}\n当前日期 {}\n购入日期 {}\n购入价格 {}\n止损价格 {:.3f}\n区间高价 {:.3f}\n当前价格 {:.3f}\n止盈价格 {:.3f}".format(\code,\name,\dt.datetime.now().strftime("%Y-%m-%d"),\date_buy,\price_buy,\price_stop_loss,\float(price_high),\float(now),\price_stop_surplus))plt.title("{} {} {} 止损止盈动态图".format(code,name,dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))plt.xlabel('日期')plt.ylabel('价格')plt.plot(df_his[['price_high']],linestyle='-',color='orange',label="最高(%.3f)" % (price_high))     plt.plot(df_his[['high']],linestyle='-',color='orange',label="每日最高")         plt.plot(df_his[['price_stop_surplus']],linestyle='--',color='red',label="止盈(%.3f)" % (price_stop_surplus))         plt.plot(df_his[['price_buy']],linestyle='-',color='blue',label="成本线(%.3f)" % (price_buy))#plt.plot(df_his[['close']],marker='o',color='blue',label="每日收盘" )              plt.scatter(df_his.index,df_his[['close']], marker='o',color='blue',label="每日收盘" )        plt.plot(df_his[['low']],linestyle='-',color='green',label="每日最低")plt.plot(df_his[['price_stop_loss']],linestyle='-',color='green',label="止损线(%.3f)" % (price_stop_loss)) legend = plt.legend(loc='best')

主函数

if __name__=='__main__':#三花智控code="002050"price_buy=24.222date_buy="2024-03-07"#长江电力code="600900"price_buy=24.83date_buy="2024-04-01"#五方光电code="002962"price_buy=14.682date_buy="2024-03-05"#天威视讯code="002238"price_buy=9.883date_buy="2024-04-18"#晋拓股份code="603211"price_buy=18.28date_buy="2024-03-13"#科力远code="600478"price_buy=4.4date_buy="2024-05-06"#太平洋code="601099"price_buy=3.591date_buy="2024-05-15"#一心堂code="002727"price_buy=20.57date_buy="2024-04-16"#我爱我家code="000560"price_buy=3.156date_buy="2024-05-27"#祥源文旅code="600576"price_buy=5.570date_buy="2024-05-09"    #卡倍亿code="300863"price_buy=48.905date_buy="2024-06-03"       #春秋电子code="603890"price_buy=11.39date_buy="2024-06-03"#蓝帆医疗code="002382"price_buy=5.073date_buy="2024-05-30"   #皖能电力code="000543"price_buy=8.041date_buy="2024-06-03"#处理数据name,df_his= make_data(code,price_buy,date_buy)#初始化绘图init_plt()makepic(code, price_buy, date_buy, name,df_his)# 新浪日K线图#http://image.sinajs.cn/newchart/daily/n/sh000001.gif

 

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词