Example #1
0
def get_best(stockid):  # 檢查是否符合四大買賣點
    stock = twstock.Stock(stockid)
    bp = twstock.BestFourPoint(stock).best_four_point()
    if (bp):
        return ('買進' if bp[0] else '賣出', bp[1])  #←傳回買進或賣出的建議
    else:
        return (False, False)  #←都不符合
Example #2
0
 def get_best(stockid):
     stock = twstock.Stock(str(stockid))
     bp = twstock.BestFourPoint(stock).best_four_point()
     if (bp):
         return (str(stockid), '買進' if bp[0] else '賣出', bp[1])
     else:
         return (False, False)
Example #3
0
def real_time_query_worker(realtime_list, bfp_list, idx, stock_id):
    realtime_list[idx] = float(
        twstock.realtime.get(stock_id)['realtime']['latest_trade_price'])
    bfp = twstock.BestFourPoint(twstock.Stock(stock_id)).best_four_point()
    if bfp:
        bfp_list[idx] = 'B' if bfp[0] else 'S'
    else:
        bfp_list[idx] = ""
Example #4
0
    def parse_data(self, data, stock):
        try:
            if not data['success']:
                return 'error'
            
            company_name = data['info']['name']
            company_code = data['info']['code']
            latest_trade_price = data['realtime']['latest_trade_price']
            open_price = data['realtime']['open']
            best_bid_price = data['realtime']['best_bid_price']
            best_bid_volume = data['realtime']['best_bid_volume']
            best_ask_price = data['realtime']['best_ask_price']
            best_ask_volume = data['realtime']['best_ask_volume']
        
            result = company_name + ' (' + company_code + ')\n'

            result = result + '即時價格: ' + latest_trade_price + '\n開盤價: ' + open_price + '\n'
            
            bfp = twstock.BestFourPoint(stock)
            strategy = bfp.best_four_point()
            
            if strategy != None:
                if strategy[0] == True:
                    result = result + '買,'
                else:
                    result = result + '賣, '
                
                result = result + strategy[1] + '\n'
            
            #result = result + '買'.center(PRICE_LENGTH + VOLUME_LEHGTH - 1, '-') + '\n'
            #for i in range(5):
            #    result = result + \
            #             best_bid_volume[i].ljust(PRICE_LENGTH, ' ') + \
            #             best_bid_price[i].rjust(VOLUME_LEHGTH, ' ') + \
            #             '\n'
            
            #result = result + '賣'.center(PRICE_LENGTH + VOLUME_LEHGTH - 1, '-') + '\n'
            #for i in range(5):
            #    result = result + \
            #             best_ask_volume[i].ljust(PRICE_LENGTH, ' ') + \
            #             best_ask_price[i].rjust(VOLUME_LEHGTH, ' ') + \
            #             '\n'            
            
            return result
            
            #print(company_name + ' (' + company_code + ')')
            #print('即時價格: ' + latest_trade_price + ', 開盤價: ' + open_price)
            
            #print('買'.center(PRICE_LENGTH + VOLUME_LEHGTH, '-') + '|' + '賣'.center(PRICE_LENGTH + VOLUME_LEHGTH, '-'))
            #for i in range(5):
            #    print(best_bid_price[i].ljust(PRICE_LENGTH, ' ') + \
            #          best_bid_volume[i].rjust(VOLUME_LEHGTH) + \
            #          '  ' + \
            #          best_ask_price[i].ljust(PRICE_LENGTH, ' ') + \
            #          best_ask_volume[i].rjust(VOLUME_LEHGTH, ' '))
            
        except:
            return 'data error'
Example #5
0
def stock_interest





if StockNews=="1":
    print(Stockdata.price)
elif StockNews=="2":
    print(Stockdata.high)
    # print(Stockdata.high[30:31])

    # one=Stockdata.price
    # one1=min(one)
    # print(one1)
elif StockNews=="3":
    averagedata=str(input("請輸入幾天內的平均交易量:"))
    print(Stockdata.moving_average(Stockdata.capacity,averagedata))
    # print(Stockdata.moving_average(Stockdata.capacity,5))
elif StockNews=="4":
    print(Stockdata.ma_bias_ratio(5,20))
elif StockNews=="5":
    print("\n穩定成長公司、ETF\n不適合長時間盤整\n適合多頭趨勢的股票\n當KD<20可買進,KD>80及賣出")
    TodayPrice=Stockdata.price[30:31]               #今日收盤
    TodayPrice0=TodayPrice[0]
    # print(TodayPrice0)

    NineDayLowList=Stockdata.price[23:31]           #近9天內最低價
    NineDayLowMin=min(NineDayLowList)
    # print(NineDayLowMin)

    NineDayLowList2=Stockdata.price[23:31]          #近9天最高價
    NineDayLowMax=max(NineDayLowList2)
    # print(NineDayLowMax)
    
    KD=((TodayPrice0)-(NineDayLowMin))/((NineDayLowMax)-(NineDayLowMin))*100
    print(data,"KD值為:",KD)
elif StockNews=="6":
    MACD0=Stockdata.price[26:31]
    MACD11=(sum(MACD0)/len(MACD0))
    # print(MACD11)
    MACD1=Stockdata.price[11:31]
    MACD31=(sum(MACD1)/len(MACD1))
    # print(MACD31)
    if MACD0>MACD1:
        print("弱勢盤;做空")
    elif MACD0==MACD1:
        print("平盤 ; 觀望")
    else: 
        print("起頭盤 ; 做多")
elif StockNews=="7":
    StockBFP=twstock.BestFourPoint(Stockdata)
    StockBFP_to_buy=StockBFP.best_four_point_to_buy()
    print("四大買點:量大收紅、量縮價不跌、三日均價由下往上、三日均價大於六日均價,符合: ",StockBFP_to_buy)
    StockBFP_to_sell=StockBFP.best_four_point_to_sell()
    print("四大賣點:量大收黑、量縮價跌、三日均價由上往下、三日均價小於六日均價,符合: ",StockBFP_to_sell)
else:
    print("無效輸入")
Example #6
0
def get_best(stockid):
    stock = twstock.Stock(stockid)
    bp = twstock.BestFourPoint(stock)
    if bp != None:
        if bp.best_four_point()[0] == True:
            return ('買進', bp.best_four_point()[1])
        else:
            return ('賣出', bp.best_four_point()[1])
    else:
        return (False, False)
Example #7
0
 def on_enter_show_technical(self, event):
     global stock_number
     stock = twstock.Stock(stock_number)
     bfp = twstock.BestFourPoint(stock)
     comment = bfp.best_four_point_to_buy()
     reply_token = event.reply_token
     send_text_message(
         reply_token,
         '請至以下網址查詢: \n' + 'https://tw.stock.yahoo.com/q/ta?s=' +
         str(stock_number) + '\n簡評:' + str(comment) + '\n\n輸入「早安」回到主選單')
     self.go_back()
def get_best(stock_id):  #參數:股票代碼 回傳:建議(買/賣)、建議資訊
    stock = twstock.Stock(stock_id)  #以股票代碼建立Stock物件
    bp = twstock.BestFourPoint(stock).best_four_point()
    '''回傳檢測四大買賣點資訊給bp
    bp為tuple型態,若適合買進bp[0]為True,否則為False
    bp[1]則是建議買/賣的原因(字串)'''

    if (bp):
        return ('買進' if bp[0] else '賣出', bp[1])
    else:
        return (False, False)
Example #9
0
def run(argv):
    print('四大買賣點判斷 Best Four Point')
    print('------------------------------')
    for sid in argv:
        bfp = twstock.BestFourPoint(twstock.Stock(sid))
        bfp = bfp.best_four_point()
        print('%s: ' % (sid), end='')
        if bfp:
            if bfp[0]:
                print('Buy  ', bfp[1])
            else:
                print('Sell ', bfp[1])
        else:
            print("Don't touch")
Example #10
0
def get_four_best(stockid):
    try:
        print("等個15秒鐘~泡杯咖啡")
        time.sleep(15)
        stock = twstock.Stock(stockid)
        best = twstock.BestFourPoint(stock).best_four_point()
        if best:
            if best[0]:
                info = "買進: "
            else:
                info = "賣出: "
            return (info, best[1])
        else:
            return (False, False)
    except Error:
        send_ifttt(stockid, "0.0", "程式出現錯誤")
        print(Error)
Example #11
0
def handle_message(event):

    #line_webhookverify
    if (event.reply_token == ("00000000000000000000000000000000"
                              or "ffffffffffffffffffffffffffffffff")):
        print("webhook verify")
        return

    if (event.message.text == '個股即時價格和最佳五檔'):
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="歡迎來到股票價格查詢\n請輸入股票代號(0~99999)"))
    elif (event.message.text == '個股健檢'):
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text="歡迎來到股票健檢\n請輸入股票正確名稱"))
    elif (event.message.text == '免責聲明'):
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text=
                "免責聲明: 投資涉及風險,證券價格有時會大幅波動,價格可升亦可跌,更可變 得毫無價值。投資未必一定能夠賺取利潤,反而可能會招致損失,往績數字並非 未來表現的指標。投資前應先閱讀有關產品的發售文件、財務及相關的風險聲明, 並應就本身的財政、其他狀況及需要詳細考慮並考慮決定投資是否切合本身特定 的投資需要。若有需要更應諮詢獨立之法律、稅務、財政及其他專業意見,方可 作出有關投資決定。"
            ))

    elif (event.message.text == '績效上傳區'):
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text="上傳績效圖幫你存起來"))

    #功能1即時報價
    #stock代號0~100000
    elif (event.message.text.isnumeric() and int(event.message.text) > 0
          and int(event.message.text) < 99999):
        #取得即時資料並檢查有無此股票
        realtime = twstock.realtime.get(event.message.text)
        if (realtime['success'] != True):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text="查無此股票"))
            return
        else:
            line_bot_api.reply_message(event.reply_token, [
                TextSendMessage(text=realtime['info']['name'] + "的即時報價:" +
                                realtime['realtime']['latest_trade_price']),
                TextSendMessage(text="最佳五檔\n" + "買價" +
                                str(realtime['realtime']['best_bid_price']) +
                                "\n賣價" +
                                str(realtime['realtime']['best_ask_price']))
            ])

    #功能2個股健檢
    elif (event.message.text in stock_list):
        stock_num = stock_list[event.message.text]
        #取得即時資料並檢查有無此股票
        realtime = twstock.realtime.get(stock_num)
        if (realtime['success'] != True):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text="查無此股票"))
            return

        #取得歷史資料和五日資料
        history = twstock.Stock(stock_num)
        bfp = list(twstock.BestFourPoint(history).best_four_point())

        if bfp[0] == True:
            bfp[0] = "推薦買多,原因:"
        elif bfp[0] == False:
            bfp[0] = "推薦放空,原因:"
        else:
            bfp[0] = ["不要動最好"]

        fiveprice = [str(history.price[i]) for i in range(-1, -6, -1)]
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=realtime['info']['name'] + "[" +
                            realtime['info']['channel'] + "]" + "近五日價格為\n" +
                            str(',\t'.join(fiveprice)) + "\n" + ' '.join(bfp)))
        return

    #功能3免責聲明
    #功能4績效上傳區
    elif event.message.text == "看看大家都傳了什麼圖片":
        client = ImgurClient(client_id, client_secret)
        images = client.get_album_images(album_id)
        index = random.randint(0, len(images) - 1)
        url = images[index].link
        image_message = ImageSendMessage(original_content_url=url,
                                         preview_image_url=url)
        line_bot_api.reply_message(event.reply_token, image_message)
        return
    #功能展開
    elif event.message.text == "開始玩":
        buttons_template = TemplateSendMessage(
            alt_text='目錄 template',
            template=ButtonsTemplate(
                title='選擇服務',
                text='請選擇',
                thumbnail_image_url='https://i.imgur.com/OwDxdjw.jpg',
                actions=[
                    MessageTemplateAction(label='個股即時價格和最佳五檔',
                                          text='個股即時價格和最佳五檔'),
                    MessageTemplateAction(label='個股健檢', text='個股健檢'),
                    MessageTemplateAction(label='免責聲明', text='免責聲明'),
                    MessageTemplateAction(label='看看大家都傳了什麼圖片',
                                          text='看看大家都傳了什麼圖片')
                ]))
        line_bot_api.reply_message(event.reply_token, buttons_template)

    #預設
    else:
        buttons_template = TemplateSendMessage(
            alt_text='目錄 template',
            template=ButtonsTemplate(
                title='選擇服務',
                text='請選擇',
                thumbnail_image_url='https://i.imgur.com/OwDxdjw.jpg',
                actions=[
                    MessageTemplateAction(label='開始玩', text='開始玩'),
                    URITemplateAction(label='影片介紹',
                                      uri='https://www.youtube.com'),
                    URITemplateAction(
                        label='github原始碼',
                        uri='https://github.com/markpengisme/Python'),
                    URITemplateAction(label='聯絡作者',
                                      uri='https://www.facebook.com/arrnoldc')
                ]))
        line_bot_api.reply_message(event.reply_token, buttons_template)
Example #12
0
import twstock

stock = twstock.Stock('2330')
bfp = twstock.BestFourPoint(stock)

#%%
print ('bfp.best_four_point_to_buy')
print (bfp.best_four_point_to_buy())

print ('bfp.best_four_point_to_sell')
print (bfp.best_four_point_to_sell())

print ('bfp.best_four_point')
print (bfp.best_four_point())
print (stock.moving_average(stock.price,3))
print ('--------')
print (stock.moving_average(stock.price,6))
#print (stock.price[-5:])   # 近五日之收盤價
Example #13
0
 def BestFourPoint(self):
     bfp = twstock.BestFourPoint(self.stock)
     self.Result = [bfp.best_four_point_to_buy()]
     self.Result.append(bfp.best_four_point_to_sell())
     self.Result.append(bfp.best_four_point())
Example #14
0
def callback_yangbot8():
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # parse webhook body
    try:
        events = parser_8.parse(body, signature)
    except InvalidSignatureError:
        abort(400)

    for event in events:
        if not isinstance(event, MessageEvent):  # 判斷是否為訊息事件
            continue
        if not isinstance(event.message, TextMessage):  # 判斷是否為文字
            continue

        text = event.message.text
        #userId = event['source']['userId']
        if (text.lower() == 'me'):
            content = str(event.source.user_id)

            line_bot_api_8.reply_message(event.reply_token,
                                         TextSendMessage(text=content))
        elif (text.lower() == 'profile'):
            profile = line_bot_api_8.get_profile(event.source.user_id)
            my_status_message = profile.status_message
            if not my_status_message:
                my_status_message = '-'
            line_bot_api_8.reply_message(event.reply_token, [
                TextSendMessage(text='Display name: ' + profile.display_name),
                TextSendMessage(text='picture url: ' + profile.picture_url),
                TextSendMessage(text='status_message: ' + my_status_message),
            ])

        elif (text.startswith('#')):
            text = text[1:]
            content = ''

            stock_rt = twstock.realtime.get(text)
            my_datetime = datetime.fromtimestamp(stock_rt['timestamp'] +
                                                 8 * 60 * 60)
            my_time = my_datetime.strftime('%H:%M:%S')

            content += '%s (%s) %s\n' % (stock_rt['info']['name'],
                                         stock_rt['info']['code'], my_time)
            content += '現價: %s / 開盤: %s\n' % (
                stock_rt['realtime']['latest_trade_price'],
                stock_rt['realtime']['open'])
            content += '最高: %s / 最低: %s\n' % (stock_rt['realtime']['high'],
                                              stock_rt['realtime']['low'])
            content += '量: %s\n' % (
                stock_rt['realtime']['accumulate_trade_volume'])

            stock = twstock.Stock(text)  # twstock.Stock('2330')
            content += '-----\n'
            content += '最近五日價格: \n'
            price5 = stock.price[-5:][::-1]
            date5 = stock.date[-5:][::-1]
            for i in range(len(price5)):
                #content += '[%s] %s\n' %(date5[i].strftime("%Y-%m-%d %H:%M:%S"), price5[i])
                content += '[%s] %s\n' % (date5[i].strftime("%Y-%m-%d"),
                                          price5[i])
            line_bot_api_8.reply_message(event.reply_token,
                                         TextSendMessage(text=content))

        elif (text.startswith('/')):
            text = text[1:]
            fn = '%s.png' % (text)
            stock = twstock.Stock(text)
            my_data = {
                'close': stock.close,
                'date': stock.date,
                'open': stock.open
            }
            df1 = pd.DataFrame.from_dict(my_data)

            df1.plot(x='date', y='close')
            plt.title('[%s]' % (stock.sid))
            plt.savefig(fn)
            plt.close()

            # -- upload
            # imgur with account: [email protected]
            client_id = os.environ.get("IMGUR_ID")
            client_secret = os.environ.get("IMGUR_SECRET")

            client = ImgurClient(client_id, client_secret)
            print("Uploading image... ")
            image = client.upload_from_path(fn, anon=True)
            print("Done")

            url = image['link']
            image_message = ImageSendMessage(original_content_url=url,
                                             preview_image_url=url)

            line_bot_api_8.reply_message(event.reply_token, image_message)

        elif (text.startswith('$')):
            text = text[1:]
            print(text)
            stock = twstock.Stock(text)
            bfp = twstock.BestFourPoint(stock)

            print(bfp.best_four_point())
            content = "建議做多,因為:\n" if bfp.best_four_point(
            )[0] else "建議放空,因為:\n"
            content += bfp.best_four_point()[1]

            line_bot_api_8.reply_message(event.reply_token,
                                         TextSendMessage(text=content))

        else:
            content = "歡迎使用STOCK股票小精靈!( ^ω^)\n基礎功能請輸入:\n#股票代號 查詢即時股價。\n/股票代號 觀看股票線圖。\n$股票代號 觀看簡單分析。"
            line_bot_api_8.reply_message(event.reply_token,
                                         TextSendMessage(text=content))

    return 'OK'