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

时间:2024-07-11 14:04:17

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

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

conda remove -n fonxsys --all
conda search python

conda create -n fonxsys python=3.9
conda activate fonxsys
python.exe -m pip install --upgrade pip --user



pip 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 --upgrade

conda 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"+code
    elif code[0] == '1':
        symbol = "s_sz"+code
    elif code[0] == '3':
        symbol = "sz"+code
    elif code[0] == '5':
        symbol = "s_sh"+code
    elif code[0] == '6':
        symbol = "sh"+code
    
    
    url = "http://hq.sinajs.cn/list="+symbol
    headers={'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.40


def make_data(code,price_buy,date_buy):
    
    #具体计算开始
    df_his = getdata_his(code,date_buy)    
    if len(df_his) <= 0 : return None
    
    name = getdata_online(code)
    if name == "" : return None
    
    return 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),  # inches
                     dpi=200, # dot-per-inch
                     facecolor='#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_buy
    df_his['price_high'] = price_high
    df_his['price_stop_loss'] = price_stop_loss
    
    profit_base = 0.618
    price_stop_surplus = price_buy+(price_high-price_buy)*profit_base;
    df_his['price_stop_surplus'] = price_stop_surplus

    
    
    
    print("{} {}\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.222
    date_buy="2024-03-07"
    
    #长江电力
    code="600900"
    price_buy=24.83
    date_buy="2024-04-01"
    
    #五方光电
    code="002962"
    price_buy=14.682
    date_buy="2024-03-05"
    
    #天威视讯
    code="002238"
    price_buy=9.883
    date_buy="2024-04-18"

    #晋拓股份
    code="603211"
    price_buy=18.28
    date_buy="2024-03-13"
    
    #科力远
    code="600478"
    price_buy=4.4
    date_buy="2024-05-06"
    
    
    #太平洋
    code="601099"
    price_buy=3.591
    date_buy="2024-05-15"
    
    #一心堂
    code="002727"
    price_buy=20.57
    date_buy="2024-04-16"
    
    #我爱我家
    code="000560"
    price_buy=3.156
    date_buy="2024-05-27"
        
    #祥源文旅
    code="600576"
    price_buy=5.570
    date_buy="2024-05-09"    


     #卡倍亿
    code="300863"
    price_buy=48.905
    date_buy="2024-06-03"       
    #春秋电子
    code="603890"
    price_buy=11.39
    date_buy="2024-06-03"
    
    #蓝帆医疗
    code="002382"
    price_buy=5.073
    date_buy="2024-05-30"   
    
    #皖能电力
    code="000543"
    price_buy=8.041
    date_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