def animate(ival): if (20 + ival) > len(df): print('no more data to plot') ani.event_source.interval *= 3 if ani.event_source.interval > 12000: exit() return data = df.iloc[0:(30 + ival)] exp12 = data['Close'].ewm(span=12, adjust=False).mean() exp26 = data['Close'].ewm(span=26, adjust=False).mean() macd = exp12 - exp26 signal = macd.ewm(span=9, adjust=False).mean() histogram = macd - signal apds = [ mpf.make_addplot(exp12, color='lime', ax=ax_emav), mpf.make_addplot(exp26, color='c', ax=ax_emav), mpf.make_addplot(histogram, type='bar', width=0.7, color='dimgray', alpha=1, ax=ax_hisg), mpf.make_addplot(macd, color='fuchsia', ax=ax_macd), mpf.make_addplot(signal, color='b', ax=ax_sign), ] for ax in axes: ax.clear() mpf.plot(data, type='candle', addplot=apds, ax=ax_main, volume=ax_volu)
def test_addplot03(bolldata): df = bolldata fname = base + '03.png' tname = os.path.join(tdir, fname) rname = os.path.join(refd, fname) tcdf = df[['LowerB', 'UpperB']] # DataFrame with two columns low_signal = percentB_belowzero(df['PercentB'], df['Close']) high_signal = percentB_aboveone(df['PercentB'], df['Close']) apds = [ mpf.make_addplot(tcdf), mpf.make_addplot(low_signal, scatter=True, markersize=200, marker='^'), mpf.make_addplot(high_signal, scatter=True, markersize=200, marker='v'), mpf.make_addplot((df['PercentB']), panel='lower', color='g') ] mpf.plot(df, addplot=apds, figscale=1.3, volume=True, savefig=tname) tsize = os.path.getsize(tname) print(glob.glob(tname), '[', tsize, 'bytes', ']') rsize = os.path.getsize(rname) print(glob.glob(rname), '[', rsize, 'bytes', ']') result = compare_images(rname, tname, tol=IMGCOMP_TOLERANCE) if result is not None: print('result=', result) assert result is None
def animate(ival): global df, rs nxt = rtapi.fetch_next() if nxt is None: print('no more data to plot') exit() df = df.append(nxt) rs = df.resample(resample_period).agg(resample_map).dropna() if len(rs) > 90: rs = rs[-90:] data = rs exp12 = data['Close'].ewm(span=12, adjust=False).mean() exp26 = data['Close'].ewm(span=26, adjust=False).mean() macd = exp12 - exp26 signal = macd.ewm(span=9, adjust=False).mean() histogram = macd - signal apds = [ mpf.make_addplot(exp12, color='lime', ax=ax_emav), mpf.make_addplot(exp26, color='c', ax=ax_emav), mpf.make_addplot(histogram, type='bar', width=0.7, color='dimgray', alpha=1, ax=ax_hisg), mpf.make_addplot(macd, color='fuchsia', ax=ax_macd), mpf.make_addplot(signal, color='b', ax=ax_sign), ] for ax in axes: ax.clear() mpf.plot(data, type='candle', addplot=apds, ax=ax_main, volume=ax_volu)
def draw_MACD(table): global panelCount panelCount = panelCount + 1 macd, macdsignal, macdhist = talib.MACD(table['Close']) PICS.append(mpf.make_addplot(macd,panel = panelCount,ylabel = 'MACD',color='blue')) PICS.append(mpf.make_addplot(macdsignal,panel = panelCount,color='red')) PICS.append(mpf.make_addplot(macdhist,type = 'bar',panel = panelCount))
def generate_macd_reports(ticker_df, ticker_symbol, reports_path): output_dir = f'{reports_path}{ticker_symbol.lower()}/' if not os.path.exists(os.path.dirname(output_dir)): try: os.makedirs(os.path.dirname(output_dir)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise macd_obj = ta.trend.MACD(close=ticker_df['Close']) macd = macd_obj.macd() macd_signal = macd_obj.macd_signal() macd_plot = mpl.make_addplot(macd, panel='lower') macd_signal_plot = mpl.make_addplot(macd_signal, panel='lower') mpl.plot(ticker_df, type='candle', volume=True, style='yahoo', addplot=[macd_plot, macd_signal_plot], savefig=f'{output_dir}Daily_MACD.svg', figscale=1.2, closefig=True)
def control_test(): x = get_candles("NOG", 10000, 0) x_ = to_dataframe(x) rsi_ = rsi(x) control, generated = get_control(x) # NOG first three samples session = [0] * len(x) for i in range(14,68): session[i] = 50 session[14] = 25 session[60] = 75 for i in range(250,312): session[i] = 50 session[255] = 25 session[301] = 75 for i in range(373,404): session[i] = 50 session[376] = 25 session[398] = 75 apds = [ make_addplot(rsi_, panel = 1), make_addplot([70] * len(x), panel = 1), make_addplot([30] * len(x), panel = 1), make_addplot(session, panel = 2) #make_addplot([ r["close"] for r in generated ], panel = 2), #make_addplot(control, panel = 3), #make_addplot([70] * len(x), panel = 3), #make_addplot([30] * len(x), panel = 3) ] plot(x_, type = "candle", addplot = apds)
def test_addplot08(bolldata): df = bolldata fname = base+'08.png' tname = os.path.join(tdir,fname) rname = os.path.join(refd,fname) tcdf = df[['LowerB','UpperB']] # DataFrame with two columns low_signal = percentB_belowzero(df['PercentB'], df['Close']) high_signal = percentB_aboveone(df['PercentB'], df['Close']) import math new_low_signal = [x*20.*math.sin(x) for x in low_signal] apds = [ mpf.make_addplot(tcdf,linestyle='dashdot'), mpf.make_addplot(new_low_signal,scatter=True,markersize=200,marker='^'), mpf.make_addplot(high_signal,scatter=True,markersize=200,marker='v'), mpf.make_addplot((df['PercentB']),panel='lower',color='g',linestyle='dotted') ] mpf.plot(df,addplot=apds,figscale=1.5,volume=True, mav=(15,30,45),style='default',savefig=tname) tsize = os.path.getsize(tname) print(glob.glob(tname),'[',tsize,'bytes',']') rsize = os.path.getsize(rname) print(glob.glob(rname),'[',rsize,'bytes',']') result = compare_images(rname,tname,tol=IMGCOMP_TOLERANCE) if result is not None: print('result=',result) assert result is None
def draw_ADLs(table): global panelCount panelCount = panelCount + 1 table_fast = tools.smooth_Data(table,10) table_slow = tools.smooth_Data(table,30) PICS.append(mpf.make_addplot(table_fast,panel = panelCount,color='red')) PICS.append(mpf.make_addplot(table_slow,panel = panelCount,color='blue',ylabel = "ADLs"))
def show_stock_chart2(df, title='', figpath=None): # 日付で昇順ソース df_sort = df.sort_index() # MACDを追加 df_macd = add_macd(df_sort) print('==========') print(df_macd) # MACDとシグナルのプロット作成 add_plot = [ mpf.make_addplot(df_macd['MACD'], color='m', panel=1, secondary_y=False), mpf.make_addplot(df_macd['Signal'], color='c', panel=1, secondary_y=False), mpf.make_addplot(df_macd['Hist'], type='bar', color='g', panel=1, secondary_y=True) ] # ローソク足チャートを表示 mpf.plot(df_sort, type='candle', mav=(5, 25, 75), volume=True, addplot=add_plot, volume_panel=2, savefig=figpath)
def generate_on_balance_volume_reports(ticker_df, ticker_symbol, reports_path): output_dir = f'{reports_path}{ticker_symbol.lower()}/' if not os.path.exists(os.path.dirname(output_dir)): try: os.makedirs(os.path.dirname(output_dir)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise on_balance_volume = ta.volume.OnBalanceVolumeIndicator( close=ticker_df['Close'], volume=ticker_df['Volume']).on_balance_volume() obv_sma = ta.trend.SMAIndicator(close=on_balance_volume, n=20).sma_indicator() obv_plot = mpl.make_addplot(on_balance_volume) obv_sma_plot = mpl.make_addplot(obv_sma) mpl.plot(ticker_df, type='candle', volume=True, style='yahoo', addplot=[obv_plot, obv_sma_plot], savefig=f'{output_dir}On_Balance_Volume.svg', figscale=1.2, closefig=True)
def plotResults(data, addings, adding_types, addings_colors, sizes, within_data, legend, names): if len(addings) == len(adding_types) == len(addings_colors): apdict = [] #if within_data is True, then the addings will be a list of column names to add to the plot if within_data: for i in range(len(addings)): apdict.append( mpf.make_addplot(data[addings[i]], type=adding_types[i], color=addings_colors[i], markersize=sizes[i])) #if within_data is False, then the addings will be a list of dataframes to add to the plot else: for i in range(len(addings)): apdict.append( mpf.make_addplot(addings[i], type=adding_types[i], color=addings_colors[i], markersize=sizes[i])) if legend: fig, ax = plt.subplots(1) fig, ax = mpf.plot(data, type='candle', block=False, addplot=apdict, returnfig=True) ax.legend(names) fig.show() #return ax else: mpf.plot(data, type='candle', block=False, addplot=apdict)
def plot_stock_sig_back(pddatas, datal, sigs): "datas标准数据,sigs(trade_sig,up_buy,up_sell,down_buy,down_sell)" # https://blog.csdn.net/weixin_42524945/article/details/112187912 # https://blog.csdn.net/xingbuxing_py/article/details/109379080 # 1. 添加额外线 add_plot = mpf.make_addplot(datal[['High', 'MidValue', 'Low']]) mpf.plot(pddatas, type='candle', addplot=add_plot) # 2. 添加额外点 a_list = datal.High.tolist() b_list = datal.Low.tolist() c_list = datal.Low.tolist() add_plot = [ mpf.make_addplot(datal['MidValue']), mpf.make_addplot(a_list, scatter=True, markersize=100, marker='v', color='g'), mpf.make_addplot(b_list, scatter=True, markersize=100, marker='^', color='r'), mpf.make_addplot(c_list, scatter=True, markersize=100, marker='o', color='y'), ] mpf.plot(pddatas, type='candle', addplot=add_plot)
def animate(self, ival): if (20 + ival) > len(self.df): print('no more data to plot') return data = self.df.iloc[0:(30 + ival)] self.exp12 = data['Close'].ewm(span=12, adjust=False).mean() self.exp26 = data['Close'].ewm(span=26, adjust=False).mean() self.macd = self.exp12 - self.exp26 self.signal = self.macd.ewm(span=9, adjust=False).mean() self.histogram = self.macd - self.signal self.apds = [ mpf.make_addplot(self.exp12, color='lime', ax=self.ax_emav), mpf.make_addplot(self.exp26, color='c', ax=self.ax_emav), mpf.make_addplot(self.histogram, type='bar', width=0.7, color='dimgray', alpha=1, ax=self.ax_hisg), mpf.make_addplot(self.macd, color='fuchsia', ax=self.ax_macd), mpf.make_addplot(self.signal, color='b', ax=self.ax_sign), ] for ax in self.axes: ax.clear() mpf.plot(data, type='candle', addplot=self.apds, ax=self.ax_main, volume=self.ax_volu)
def plot_j2(pdata, sma9, sma20, lowerbb, upperbb, numofdays, ticker, defining_ma): sma9dict = mpf.make_addplot(sma9['data'][-numofdays:], color='#c87cff', width=1) sma20dict = mpf.make_addplot(sma20['data'][-numofdays:], color='#f28c06', width=1) lowerbbdict = mpf.make_addplot(lowerbb['data'][-numofdays:], color='#b90c0c', width=1) upperbbdict = mpf.make_addplot(upperbb['data'][-numofdays:], color='#b90c0c', width=1) mpf.plot( pdata[-numofdays:], type='candle', style='charles', addplot=[sma9dict, sma20dict, lowerbbdict, upperbbdict], # figscale=.9, tight_layout=False, ylabel='', savefig= f'''/Users/mike/Desktop/ib_insync-MovingAverageChartGen/9-200SMA_{today_date}/{ticker}_{defining_ma}_{today_date}.pdf''' ) chartFilePath = f'''/Users/mike/Desktop/ib_insync-MovingAverageChartGen/9-200SMA_{today_date}/{ticker}_{defining_ma}_{today_date}.pdf''' chartFileTitle = f'''{ticker}_{defining_ma}_{today_date}.pdf'''
def show_adv(self, ftitle="Stock", **kwargs): """ 顯示進階K線圖,K線搭配一主圖指標與兩個副圖指標 使用mplfinance實現之(panel method) 已定義的作圖參數: ti_main = "SMA" / "VWMA" ti_sub1 = "KD" / "MACD" / "STD" / "VIX" / "CVOL" ti_sub2 = "KD" / "MACD" / "STD" / "VIX" / "CVOL" """ self._setrun(**kwargs) # 進行參數驗證與指標計算 dest = Dpath + '\\' + ftitle + ".png" mc = mpf.make_marketcolors(up='r', down='g', inherit=True) ms = mpf.make_mpf_style(base_mpf_style = "yahoo", \ marketcolors = mc, y_on_right = True) # 不支援中文字型,圖表文字需為英文 mfargs = dict(type = "candle", volume = True, \ columns = ("O", "H", "L", "C", "V"), \ show_nontrading = False, returnfig = True, \ figsize = (self.fx, self.fy), \ title = ftitle, style = ms, ylabel = "Price", \ ylabel_lower = "Volume in shares", \ panel_ratios = (1, 1)) aps = [] if "ti_main" in kwargs: tidf = self.val_main.copy() isma = False if kwargs["ti_main"] == "SMA" or kwargs["ti_main"] == "VWMA": isma = True # 主圖技術指標為均線類型 for i in range(0, tidf.shape[1]): aps.append(mpf.make_addplot(tidf.iloc[:, i], \ color = MA_Colors[i])) if isma: # 補均線扣抵記號,配色同均線 aps.append(mpf.make_addplot(self.sig_main.iloc[:, i], \ type = "scatter", \ markersize = 200, \ marker = '^', \ color = MA_Colors[i])) pid = 1 # Panel ID = 0 for candlestick, 1 for volume if "ti_sub1" in kwargs: # pid = 2 pid += 1 ap2 = self._setsubti(self.val_sub1, kwargs["ti_sub1"], pid) for item in ap2: aps.append(item) if "ti_sub2" in kwargs: # pid = 3 (or 2 if ti_sub1 is not assigned) pid += 1 ap3 = self._setsubti(self.val_sub2, kwargs["ti_sub2"], pid) for item in ap3: aps.append(item) if len(aps) > 0: if pid == 2: mfargs["panel_ratios"] = (2, 1, 1) elif pid == 3: mfargs["panel_ratios"] = (3, 1, 1, 1) fig, axes = mpf.plot(self.df, addplot=aps, **mfargs) else: fig, axes = mpf.plot(self.df, **mfargs) mpf.show() fig.savefig(dest) return None
async def candle(message: types.Message, regexp_command): chat_id = message.chat.id try: coin = regexp_command.group(1) trades = get_ohcl_trades(coin, 180) trades = trades[-60:] df = pd.DataFrame( trades, columns='time open high low close volume amount'.split()) df['time'] = pd.DatetimeIndex(df['time'] * 10**9) df.set_index('time', inplace=True) df['MA20'] = df['close'].rolling(window=20).mean() df['20dSTD'] = df['close'].rolling(window=20).std() df['Upper'] = df['MA20'] + (df['20dSTD'] * 2) df['Lower'] = df['MA20'] - (df['20dSTD'] * 2) rsi_df = get_rsi_df(df) df = df.tail(30) rsi_df = rsi_df.tail(30) apd = [ mpf.make_addplot(df['Lower'], color='#EC407A', width=0.9), mpf.make_addplot(df['Upper'], color='#42A5F5', width=0.9), mpf.make_addplot(df['MA20'], color='#FFEB3B', width=0.9) ] if rsi_df is not None: apd.append( mpf.make_addplot(rsi_df, color='#FFFFFF', panel=1, ylabel='RSI', ylim=[0, 100])) kwargs = dict(type='candle', ylabel=coin.upper() + ' Price in $', volume=True, figratio=(3, 2), figscale=1.5, addplot=apd) mpf.plot(df, **kwargs, style='nightclouds') mc = mpf.make_marketcolors(up='#69F0AE', down='#FF5252', inherit=True) s = mpf.make_mpf_style(base_mpf_style='nightclouds', facecolor='#121212', edgecolor="#131313", gridcolor="#232323", marketcolors=mc) mpf.plot(df, **kwargs, style=s, scale_width_adjustment=dict(volume=0.55, candle=0.8), savefig=coin + '-mplfiance.png') await bot.send_photo(chat_id=chat_id, photo=InputFile(coin + '-mplfiance.png')) except Exception as e: logging.error("ERROR Making chart:" + str(e)) await bot.send_message(chat_id=chat_id, text="Failed to create chart", parse_mode="HTML")
def draw_KD(table,stockInfo):#table = 表 stockInfo = 股票資訊結構 table['k'],table['d'] = talib.STOCH(table['High'],table['Low'],table['Close']) table['k'].fillna(value=0,inplace = True) table['d'].fillna(value=0,inplace = True) global panelCount panelCount = panelCount + 1 PICS.append(mpf.make_addplot(table['k'],panel = panelCount,ylabel = "KD",color='red')) PICS.append(mpf.make_addplot(table['d'],panel = panelCount,color='blue'))
def __init__(self, parent=None, width=5, height=5, dpi=100): idf = pd.read_csv('datas/SPY_20110701_20120630_Bollinger.csv', index_col=0, parse_dates=True) idf.shape idf.head(3) idf.tail(3) self.df = idf.loc['2011-07-01':'2011-12-30', :] self.df = self.df.iloc[0:30] self.exp12 = self.df['Close'].ewm(span=12, adjust=False).mean() self.exp26 = self.df['Close'].ewm(span=26, adjust=False).mean() self.macd = self.exp12 - self.exp26 self.signal = self.macd.ewm(span=9, adjust=False).mean() self.histogram = self.macd - self.signal self.apds = [ mpf.make_addplot(self.exp12, color='lime'), mpf.make_addplot(self.exp26, color='c'), mpf.make_addplot(self.histogram, type='bar', width=0.7, panel=1, color='dimgray', alpha=1, secondary_y=False), mpf.make_addplot(self.macd, panel=1, color='fuchsia', secondary_y=True), mpf.make_addplot(self.signal, panel=1, color='b', secondary_y=True), ] s = mpf.make_mpf_style(base_mpf_style='starsandstripes', rc={'figure.facecolor': 'lightgray'}) self.fig, self.axes = mpf.plot(self.df, type='candle', addplot=self.apds, figscale=1.5, figratio=(7, 5), title='\n\nMACD', style=s, volume=True, volume_panel=2, panel_ratios=(6, 3, 2), returnfig=True) FigureCanvas.__init__(self, self.fig) self.setParent(parent) self.ax_main = self.axes[0] self.ax_emav = self.ax_main self.ax_hisg = self.axes[2] self.ax_macd = self.axes[3] self.ax_sign = self.ax_macd self.ax_volu = self.axes[4] self.df = idf.loc['2011-07-01':'2011-12-30', :] self.ani = animation.FuncAnimation(self.fig, self.animate, interval=250)
def ChartOrder_MA(KBar,TR): # 將K線轉為DataFrame Kbar_df=KbarToDf(KBar) # 定義指標副圖 addp=[] addp.append(mpf.make_addplot(Kbar_df['MA_long'],color='red')) addp.append(mpf.make_addplot(Kbar_df['MA_short'],color='yellow')) # 繪製指標、下單圖 ChartOrder(KBar,TR,addp)
def plot_image(df_): my_color = mpf.make_marketcolors(up="red", down="green", edge="inherit", volume="inherit") my_style = mpf.make_mpf_style(marketcolors=my_color) add_plot = [mpf.make_addplot(df_[['ma_short', 'ma_long']]), mpf.make_addplot(df_['signal_long'], scatter=True, marker="^", color="r"), mpf.make_addplot(df_['signal_short'], scatter=True, marker="v", color="g")] mpf.plot(df_, type="line", ylabel="price(usdt)", style=my_style, volume=True, ylabel_lower="vol", addplot=add_plot)
def plot_signal(df, signal, position=False, lines=False): name = (df.reset_index())['symbol'].iloc[0] buys = df[df[signal] > 0].index sells = df[df[signal] < 0].index fechas = [] colores = [] Trades = [] for trade in buys: fechas.append(trade) colores.append('g') for trade in sells: fechas.append(trade) colores.append('r') df_trades = pd.DataFrame({'colors': colores}, index=fechas) df = df.join(df_trades) df['buy_price'] = np.where(df['colors'] == 'g', df['Close'], math.nan) df['sell_price'] = np.where(df['colors'] == 'r', df['Close'], math.nan) if position: lines = True if lines: marker = 0.1 if position: width = 0.3 alpha = 0.1 else: width = 0.5 alpha = 0.7 else: width = 0.01 alpha = 0.01 marker = 70 if df['buy_price'].notnull().sum().sum() > 0: trades_buy = mpf.make_addplot(df['buy_price'], type='scatter', markersize=marker, marker='^', color='g') Trades.append(trades_buy) if df['sell_price'].notnull().sum().sum() > 0: trades_sell = mpf.make_addplot(df['sell_price'], type='scatter', markersize=marker, marker='v', color='r') Trades.append(trades_sell) mpf.plot(df, type='candle', style='charles', figratio=(16, 8), addplot=Trades, vlines=dict(vlines=fechas, colors=colores, linewidths=width, alpha=alpha), title=name + ' daily chart' + ' signal:' + signal, ylabel='price')
def send_monthly_data(): ''' Send the long term data as a nice chart :s ''' econ_data = pd.read_sql(f'''SELECT * FROM forecast''', ECON_CON) econ_data.datetime = pd.to_datetime(econ_data.datetime) econ_data = econ_data.set_index('datetime', drop=True).replace('', np.nan) # I need to get the sum of the most recent values from each event. I can # filter for where long_term.notna(), but my rolling window is unknown # because not all currencies have the same number of long term events. data = {} for ccy in econ_data.ccy.unique(): temp = econ_data[ (econ_data.ccy == ccy) & (econ_data.long_term.notna()) ] # Get the window sized based on number of unique values found roll_window = len(temp.ccy_event.unique()) final_data = temp.long_term.rolling(roll_window).sum() / roll_window # The data needs to get aligned to whatever timeframe of ohlc it will be plotted on # Since there is sometimes multiple releases on a given day, group by day final_data.index = final_data.index.date data[ccy] = final_data.groupby([final_data.index]).sum() # data[ccy].index = pd.to_datetime(data[ccy].index) # data[ccy] = data[ccy].resample('1W') # my daily candles from IC Markets have the hours at 16:00 so add that lest you want funkydata # These long term data items were really only applicable to the currencies # with lots of unique events (E,U,G). timeframe = 'D1' symbols = ['EURUSD', 'GBPUSD', 'EURGBP', 'USDCHF', 'NZDUSD', 'USDCAD', 'USDJPY'] for symbol in symbols: df = mt5_ohlc_request(symbol, timeframe, num_candles=270) df.index = df.index.date df['long_term1'] = data[symbol[:3]] df['long_term2'] = data[symbol[3:]] df.long_term1 = df.long_term1.fillna(method='ffill') df.long_term2 = df.long_term2.fillna(method='ffill') df.index = pd.to_datetime(df.index) plots = [] plots.append(mpf.make_addplot(df.long_term1, color='r', panel=1, width=2, secondary_y=True)) plots.append(mpf.make_addplot(df.long_term2, color='b', panel=1, width=1, secondary_y=True)) mpf.plot(df, type='candle', tight_layout=True, addplot=plots, show_nontrading=False, volume=True, title=f'{symbol} {timeframe}', # style='classic', ## black n white savefig=f'{symbol}_longterm.png' )
def showCompare(self, bars: [], code: str): from earnmi.data.MarketImpl import MarketImpl market = MarketImpl() market.addNotice(code) today: datetime = bars[-1].datetime market.setToday(today + timedelta(days=1)) start: datetime = bars[0].datetime baseBars = market.getHistory().getKbarFrom( code, datetime(start.year, start.month, start.day)) #baseBar = mainBar ### 初始化columns columns = ['Open', 'High', 'Low', 'Close', "Volume", "Close2"] data = [] index = [] bars1 = baseBars bars2 = bars size1 = len(bars1) size2 = len(bars2) rate = bars1[0].close_price / bars2[0].close_price bar_pre_2 = bars2[0] i2 = 0 for i1 in range(size1): bar1 = bars1[i1] index.append(bar1.datetime) list = [ bar1.open_price, bar1.high_price, bar1.low_price, bar1.close_price, bar1.volume ] if i2 < size2: bar2 = bars2[i2] if utils.is_same_day(bar1.datetime, bar2.datetime): list.append(bar2.close_price * rate) bar_pre_2 = bar2 i2 = i2 + 1 else: ##bar2缺少今天数据。 list.append(bar_pre_2.close_price * rate) ##保证i2要大于大 while (i2 < size2): bar2 = bars2[i2] days = (bar2.datetime - bar1.datetime).days if days > 0: break i2 = i2 + 1 else: list.append(bar_pre_2.close_price * rate) data.append(list) trades = pd.DataFrame(data, index=index, columns=columns) apds = [] apds.append(mpf.make_addplot(trades['Close'], color='gray')) apds.append(mpf.make_addplot(trades['Close2'], color='r')) mpf.plot(trades, type='line', figscale=1.3, addplot=apds) pass
def ChartOrder_BBANDS(KBar,TR): # 將K線轉為DataFrame Kbar_df=KbarToDf(KBar) # 將副圖繪製出來 addp=[] addp.append(mpf.make_addplot(Kbar_df['Upper'],color='yellow')) addp.append(mpf.make_addplot(Kbar_df['Middle'],color='grey')) addp.append(mpf.make_addplot(Kbar_df['Lower'],color='yellow')) # 開始繪圖 ChartOrder(KBar,TR,addp,True)
def ChartOrder_RSI_2(KBar,TR): # 將K線轉為DataFrame Kbar_df=KbarToDf(KBar) # 將副圖繪製出來 addp=[] addp.append(mpf.make_addplot(Kbar_df['RSI'],panel='lower',color='black',secondary_y=False)) addp.append(mpf.make_addplot(Kbar_df['Ceil'],panel='lower',color='red',secondary_y=False)) addp.append(mpf.make_addplot(Kbar_df['Floor'],panel='lower',color='red',secondary_y=False)) # 開始繪圖 ChartOrder(KBar,TR,addp,False)
def ChartOrder_RSI_1(KBar,TR): # 將K線轉為DataFrame Kbar_df=KbarToDf(KBar) # 將副圖繪製出來 addp=[] addp.append(mpf.make_addplot(Kbar_df['RSI_long'],panel='lower',color='red',secondary_y=False)) addp.append(mpf.make_addplot(Kbar_df['RSI_short'],panel='lower',color='green',secondary_y=False)) addp.append(mpf.make_addplot(Kbar_df['Middle'],panel='lower',color='black',secondary_y=False)) # 開始繪圖 ChartOrder(KBar,TR,addp,False)
def create_addplots(df, mpl): """ """ adps, hlines = [], { 'hlines': [], 'colors': [], 'linestyle': '--', 'linewidths': 0.75 } # Add technical feature data (indicator values, etc). for col in list(df): if (col != "Open" and col != "High" and col != "Low" and col != "Close" and col != "Volume"): adps.append(mpl.make_addplot(df[col])) # Add entry marker color = 'limegreen' if trade['direction'] == "LONG" else 'crimson' adps.append( mpl.make_addplot(entry_marker, type='scatter', markersize=200, marker='.', color=color)) # Plotting Stop and TP levels cause incorrect scaling when stop/TP are # far away from entry. Fix later. Not urgent or required # # Add stop and TP levels. # o_ids = [i for i in trade['orders'].keys()] # for o_id in o_ids: # if trade['orders'][o_id]['metatype'] == "STOP": # hlines['hlines'].append(trade['orders'][o_id]['price']) # hlines['colors'].append('crimson') # elif trade['orders'][o_id]['metatype'] == "TAKE_PROFIT": # hlines['hlines'].append(trade['orders'][o_id]['price']) # hlines['colors'].append('limegreen') # elif trade['orders'][o_id]['metatype'] == "FINAL_TAKE_PROFIT": # hlines['hlines'].append(trade['orders'][o_id]['price']) # hlines['colors'].append('limegreen') # # Add an invisible hline to re-scale, in case stop/TP is far away. # difference = max([abs(trade['entry_price'] - i) for i in hlines['hlines']]) # if max(hlines['hlines']) > difference: # hlines['hlines'].append(trade['entry_price'] - difference) # hlines['colors'].append('white') # elif max(hlines['hlines']) < differe7nce: # hlines['hlines'].append(trade['entry_price'] + difference) # hlines['colors'].append('white') return adps, hlines
def ChartKBar_MA(KBar,longPeriod=20,shortPeriod=5): # 計算移動平均線(長短線) KBar['MA_long']=SMA(KBar,timeperiod=longPeriod) KBar['MA_short']=SMA(KBar,timeperiod=shortPeriod) # 將K線轉為DataFrame Kbar_df=KbarToDf(KBar) # 將副圖繪製出來 addp=[] addp.append(mpf.make_addplot(Kbar_df['MA_long'],color='red')) addp.append(mpf.make_addplot(Kbar_df['MA_short'],color='yellow')) # 開始繪圖 ChartKBar(KBar,addp,True)
def ChartKBar_BBANDS(KBar,BBANDSPeriod): # 計算布琳通道 KBar['Upper'],KBar['Middle'],KBar['Lower']=BBANDS(KBar,timeperiod=BBANDSPeriod) # 將K線轉為DataFrame Kbar_df=KbarToDf(KBar) # 將副圖繪製出來 addp=[] addp.append(mpf.make_addplot(Kbar_df['Upper'],color='yellow')) addp.append(mpf.make_addplot(Kbar_df['Middle'],color='grey')) addp.append(mpf.make_addplot(Kbar_df['Lower'],color='yellow')) # 開始繪圖 ChartKBar(KBar,addp,True)
def create_summary(self): """Creates a csv file and image showing all positions taken.""" # csv file summary = pd.DataFrame.from_dict(self.equity) summary = summary.set_index('datestamp') summary['Buy Orders'] = np.nan summary['Sell Orders'] = np.nan for trade in self.all_positions: open_time = dt.datetime.strptime(trade['Open Time'], '%d-%m-%Y %H:%M:%S') close_time = dt.datetime.strptime(trade['Close Time'], '%d-%m-%Y %H:%M:%S') if trade['Direction'] == 'BUY': summary.loc[open_time, 'Buy Orders'] = trade['Open Price'] summary.loc[close_time, 'Sell Orders'] = trade['Close Price'] else: summary.loc[open_time, 'Sell Orders'] = trade['Open Price'] summary.loc[close_time, 'Buy Orders'] = trade['Close Price'] curr_dir = os.path.dirname(os.path.realpath(__file__)) save_path = os.path.join(curr_dir, 'summary') summary.to_csv(f'{save_path}/summary.csv') # image data = self.data.symbol_data plots = [ mpf.make_addplot(summary['Buy Orders'], type='scatter', color='green', marker='^', markersize=40), mpf.make_addplot(summary['Sell Orders'], type='scatter', color='red', marker='v', markersize=40), mpf.make_addplot(summary['balance'], panel=1, color='fuchsia') ] mpf.plot(data, type='candlestick', figratio=(18, 10), panel_ratios=(8, 2), addplot=plots, style='sas', savefig=f'{save_path}/summary.png', tight_layout=True)