def getStockInfo(self, id): ret = dict() output_meta = intraday.meta(apiToken=self.apiToken, output="dataframe", symbolId=id) output_chart = intraday.chart(apiToken=self.apiToken, output="dataframe", symbolId=id) ref_price = output_meta.iloc[ 0, output_meta.columns.get_loc("priceReference")] current_price = output_chart.iloc[ -1, output_chart.columns.get_loc("close")] if ref_price > current_price: graph = output_chart.plot(x="at", y='close', color='green') elif ref_price == current_price: graph = output_chart.plot(x="at", y='close', color='gray') else: graph = output_chart.plot(x="at", y='close', color='red') graph.axhline(ref_price, linestyle='dashed', color='xkcd:dark grey', alpha=0.6, label='參考價', marker='') graph.legend().set_visible(False) fig = graph.get_figure() buf = io.BytesIO() fig.savefig(buf, format='png') ret['Name'] = output_meta.iloc[0, output_meta.columns.get_loc("nameZhTw")] ret['RealPrice'] = current_price ret['ID'] = id ret['photo'] = buf return ret
def get_stock_info(self, num): data = intraday.meta(apiToken=self.config['FUGLE']['fugle_TOKEN'] , symbolId=num , output='raw') # data = intraday.meta(apiToken=Bot.config['FUGLE']['fugle_TOKEN'] , symbolId='0050', output='raw') df1 = intraday.chart(apiToken=self.config['FUGLE']['fugle_TOKEN'] , symbolId=num) # df1 = intraday.chart(apiToken=Bot.config['FUGLE']['fugle_TOKEN'] , symbolId='0050') if 'error' in df1.columns: return '請輸入正確的股票代碼:' elif df1.shape[0] == 0: if 'nameZhTw' not in data: text = 'api 無回應' elif 'industryZhTw' in data: text = "【{}({})】 \n⦁ 產業: {} \n⦁ 開盤股價: {} \n⦁ 昨日漲停價: {} \n⦁ 昨日跌停價: {} ".format( data['nameZhTw'], num, data['industryZhTw'], data['priceReference'], data['priceHighLimit'], data['priceLowLimit'] ) else: text = "【{}({})】 \n⦁ 開盤股價: {} \n⦁ 昨日漲停價: {} \n⦁ 昨日跌停價: {} ".format( data['nameZhTw'], num, data['priceReference'], data['priceHighLimit'], data['priceLowLimit'] ) return text else: df1 = df1.iloc[-1] if 'industryZhTw' in data: text = "【{}({})】 \n⦁ 產業: {} \n⦁ 當前股價: {} \n⦁ 今日漲跌: {}({}%) ".format( data['nameZhTw'], num, data['industryZhTw'], df1['close'], round(df1['close']-data['priceReference'], 2), round(((df1['close']-data['priceReference'])/data['priceReference'])*100, 2) ) else: text = "【{}({})】 \n⦁ 當前股價: {} \n⦁ 今日漲跌: {}({}%) ".format( data['nameZhTw'], num, df1['close'], round(df1['close']-data['priceReference'], 2), round(((df1['close']-data['priceReference'])/data['priceReference'])*100, 2) ) return text
def info(bot, update): global num num = update.message.text data = intraday.meta(apiToken=api_token, symbolId=num, output='raw') '''對話框按鈕''' global reply_markup reply_markup = InlineKeyboardMarkup([[ InlineKeyboardButton('基本資訊', callback_data='info'), InlineKeyboardButton('最新一筆交易', callback_data='trade'), ]]) '''輸入id,且判斷id是否存在''' if 'id' in num: if int(num[2:]) not in userdata().df['userid']: update.message.reply_text('ID%s 不存在' % (num[2:])) else: update.message.reply_text('登入成功 ID:%s,請輸入欲查詢的股票代碼:' % (num[2:])) userdata().write(update.message.chat.id, num[2:]) elif 'error' in intraday.chart(apiToken=api_token, symbolId='2330').columns: '''直接輸入股票代碼''' update.message.reply_text('請輸入正確的股票代碼:') else: df1 = intraday.chart(apiToken=api_token, symbolId=num) df1 = df1.iloc[-1] text = ('•' + data['nameZhTw'] + '(' + num + ')\t\t' + '股價:' + str(df1['close']) + '\t\t' + '漲跌:' + str(data['priceReference'] - df1['close']) + '\t(' + str( round(((data['priceReference'] - df1['close']) / data['priceReference']) * 100, 2)) + '%)') bot.send_message( update.message.chat.id, text + '\n\n' + '{} 您還可以查詢:'.format(update.message.from_user.first_name), reply_to_message_id=update.message.message_id, reply_markup=reply_markup)
def serv_share_num(self, keyword, msg_received): """ To find out the latest price by share number. """ print('【serv_share_num】') # Check whether is previous action if msg_received == None: share_no = keyword else: share_no = msg_received.split('{}'.format(keyword))[1] # Collect data from FUGLE API share_data = intraday.chart(apiToken=FUGLE_API_TOKEN, symbolId='{}'.format(share_no), output='raw') # Template for Share detail try: share_date_time = list(share_data.keys())[-1] share_res = share_data[share_date_time] share_res_date_time = share_date_time.split('T') text = "【{} 最新資訊】\n\ 🔺行業類別:{}\n\ 🔺日期:{}\n\ 🔺時間:{}\n\ 🔺開盤價:{}\n\ 🔺收盤價:{}\n\ 🔺最高價:{}\n\ 🔺最低價:{}\n\ 🔺交易張數:{}\n\ 🔺交易量:{}\n " .format(share_no, \ self.share_db[share_no], \ share_res_date_time[0], \ share_res_date_time[1].split('.')[0], \ share_res['open'], \ share_res['close'], \ share_res['high'], \ share_res['low'], \ share_res['unit'], \ share_res['volume']) except: text = "非常抱歉,菜雞能力不及 😥,請重新輸入有效股票代號!" self.prev_action = "serv_share_num" self.out_msg = self.temp_msg = text self.temp_share_no = share_no success = self.send_message() return success
def get_chart_data(self, n, symbol_id): # Last Friday # now = datetime.datetime.now() + relativedelta(weekday=FR(-1)) now = datetime.datetime.now() today = now.strftime('%Y-%m-%d') close_time = datetime.datetime(now.year, now.month, now.day, 12, 00) time_index = pd.date_range(start=f'{today} 09:00:00', end=f'{today} 12:00:00', freq=f'{n}T', closed='right') df_time = pd.DataFrame(time_index, columns=['at']) df = intraday.chart(symbolId=symbol_id, apiToken=self.api_token, output='dataframe') df['at'] = df['at'].apply( lambda x: x.astimezone(None) + datetime.timedelta(hours=8)) df = df.set_index('at') df = df.asfreq('1T') df['close'] = df['close'].fillna(method='ffill') df['volume'] = df['volume'].fillna(0) df = df.fillna(axis=1, method='ffill') df = df[['open', 'high', 'low', 'close', 'volume']] df_ohlc = df.resample(f'{n}T', kind='period').agg({ 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum' }) df_ohlc.index = df_ohlc.index + datetime.timedelta(minutes=n - 1) df_ohlc = df_ohlc.to_timestamp().reset_index() df_ohlc = pd.merge(df_time, df_ohlc, on='at', how='outer') df_ohlc['at'] = df_ohlc['at'].apply(lambda x: x if x <= close_time else close_time) return df_ohlc
def open_close(bot, update): a_data = intraday.chart(apiToken=api_token, symbolId=str(aa[0])) aaa = str(a_data.tail(1)["open"]) bb = aaa.split(sep=' ')[1] o = bb.split(sep="N")[0] aab = str(a_data.tail(1)["close"]) bb1 = aab.split(sep=' ')[1] o1 = bb.split(sep="N")[0] oc = "開盤價:" + o oc1 = "收盤價:" + o1 print(oc) print(oc1) update.message.reply_text(oc) update.message.reply_text(oc1)
def fugle_realtime(api_token, twii, model, ss, freq="15T", lookback=10000): from fugle_realtime import intraday if twii.index.tzinfo is None: twii.index = twii.index.tz_localize("Asia/Taipei") df = intraday.chart(apiToken=api_token, output="dataframe", symbolId="TWSE_SEM_INDEX_1") df.index = df['at'] df.index = df.index.tz_convert("Asia/Taipei") df = df.resample(freq).first() twii_temp = twii.append(df.close).iloc[-lookback:] features = create_features(twii_temp).dropna() if len(features) == 0: print("fail! please increase lookback period") y = model.predict(ss.transform(features)) return pd.DataFrame({ 'twii': twii_temp.loc[features.index].values, 'model': y.reshape(1, len(y))[0] })
# external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # app.layout = html.Div(children=[ # html.Div(id='quote_table'), # dcc.Interval( # id='interval-component', # interval=5000, # n_intervals=1 # ), # ]) # @app.callback( # Output('quote_table', 'children'), # [Input('interval-component', 'n_intervals')]) # def table(interval_component): # fugle.update_data() # return html.Div([ # fugle.message_table() # ]) # if __name__ == '__main__': # app.run_server() from fugle_realtime import intraday intraday.chart(apiToken="demo", output="dataframe", symbolId="2884")
print(df) FUGLE_API_TOKEN = os.environ.get('FUGLE_API_TOKEN') sender = TelegramSender() buy_list = [] while True: for index, row in df.iterrows(): time.sleep(1.2) sid = df.at[index, 'sid'] name = df.at[index, 'name'] ma_5 = df.at[index, '5ma'] ma_10 = df.at[index, '10ma'] ma_20 = df.at[index, '20ma'] try: print("Checking {} {}".format(sid, name)) stock_df = intraday.chart(symbolId=sid, apiToken=FUGLE_API_TOKEN) price = stock_df['close'].values[-1] if price > max([ma_5, ma_10, ma_20]): if sid not in buy_list: buy_list.append(sid) text = "突破均線糾結: {} {} price now: {}".format(sid, name, price) sender.send_message(text) except KeyError: print("An error occur: {} {}".format(sid, name)) continue
def test_intraday_chart(): chart = intraday.chart() assert type(chart) is DataFrame
def test_intraday_chart_output_raw(): chart = intraday.chart(output="raw") assert type(chart) is dict
def test_intraday_chart_output_dataframe(): chart = intraday.chart(output="dataframe") assert type(chart) is DataFrame
def test_intraday_chart_output(): with raises(ValueError) as excinfo: intraday.chart(output="") assert excinfo.type is ValueError assert str(excinfo.value) == 'output must be one of ["dataframe", "raw"]'