生成可視化的止盈止損結果(圖片)
媽的,還是得用 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
?
?