def buildHistory(codes=None, force_update=False): import pandas as pd if codes is None: codes = genStockList(force_update=force_update) stock = twstock.Stock(codes[0]) vols = pd.DataFrame({codes[0]: stock.capacity}, index=stock.date) for code in codes[1:]: stock = twstock.Stock(code) vols[code] = stock.capacity dump(vols, 'vol.pkl')
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) #←都不符合
def run(argv): for sid in argv: s = twstock.Stock(sid) print('-------------- %s ---------------- ' % sid) print('high : {:>5} {:>5} {:>5} {:>5} {:>5}'.format(*s.high[-5:])) print('low : {:>5} {:>5} {:>5} {:>5} {:>5}'.format(*s.low[-5:])) print('price: {:>5} {:>5} {:>5} {:>5} {:>5}'.format(*s.price[-5:]))
def getstockdata(code,year, month): import twstock stock = twstock.Stock(code) stock.fetch(year, month) # 獲取 2000 年 10 月至今日之股票資料 return stock
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)
def GetOneStock(self,StockCode): stock = twstock.Stock(StockCode) high = stock.high low = stock.low price = stock.price capacity = stock.capacity try: avg5_Price= stock.moving_average(stock.price,5) avg10_Price= stock.moving_average(stock.price,10) avg5_Cap= stock.moving_average(stock.capacity,5) avg10_Cap= stock.moving_average(stock.capacity,10) except: avg5_Price = None avg10_Price = None avg5_Cap = None avg10_Cap = None self.AllStockData[StockCode] = { 'high' : high, 'low' : low, 'price':price, 'capacity': capacity, 'avg5_Price' : avg5_Price, 'avg10_Price': avg10_Price, 'avg5_Cap' : avg5_Cap, 'avg10_Cap' : avg10_Cap } time.sleep(random.uniform(10,15))
def run(argv, initial_fetch: bool=True, proxies_list: list=[]): for sid in argv: s = twstock.Stock(sid, initial_fetch=initial_fetch, proxies_list=proxies_list) print('-------------- %s ---------------- ' % sid) print('high : {:>5} {:>5} {:>5} {:>5} {:>5}'.format(*s.high[-5:])) print('low : {:>5} {:>5} {:>5} {:>5} {:>5}'.format(*s.low[-5:])) print('price: {:>5} {:>5} {:>5} {:>5} {:>5}'.format(*s.price[-5:]))
def on_enter_show_price(self, event): global stock_number stock = twstock.Stock(stock_number) reply_token = event.reply_token if weekdays == 5 or weekdays == 6: send_text_message( reply_token, '今日為週末,未開盤 \n近5個開盤日股價為: \n' + str(stock.price[-5:]) + '\n輸入「早安」回到主選單') else: if hour_time < 900: send_text_message( reply_token, '今日尚未開盤\n近5個開盤日股價為: \n' + str(stock.price[-5:]) + '\n輸入「早安」回到主選單') elif hour_time >= 900 and hour_time < 1330: send_text_message( reply_token, '目前開盤中,查詢時間為:' + str(local_dt) + '\n 近4個開盤日股價及現在股價為: \n' + str(stock.price[-5:]) + '\n輸入「早安」回到主選單') elif hour_time >= 1330: send_text_message( reply_token, '今日已收盤\n近4個開盤日股價及今日收盤股價為: \n' + str(stock.price[-5:]) + '\n輸入「早安」回到主選單') self.go_back()
def fetch_data(year, month): data = twstock.Stock('0056') with open('0056.txt', 'a+') as fh: content = json.dumps(data.fetch(year, month), cls=RoundTripEncoder) #logger.info(f"Fetch {year} {month}") fh.write(content) fh.write('\n')
def get_all_this_month(): year = int(input('year:')) month = int(input('month:')) for root, dirs, files in os.walk(os.getcwd() + '\\StockList'): for f in files: if f[-5:] == '.xlsx': try: number = int(f[:4]) stock = twstock.Stock(str(number)) # if twstock.codes[str(number)].market == '上市': # time.sleep(Global.wait_time) # small delay for website block # Global.wait_time -= 1 # if Global.wait_time < 2: # Global.wait_time = 6 print(root, f) file = openpyxl.load_workbook(root + '\\' + f) sheet = file.get_sheet_by_name('Sheet1') handle_data(stock, year, month, root + '\\raw%d%02d' % (year, month), sheet) if Global.skip: error_file = open(root + '\\raw%d%02d.fail' % (year, month), 'w') error_file.close() else: if os.path.isfile(root + '\\' + '\\raw%d%02d.fail'): os.remove(root + '\\' + '\\raw%d%02d.fail') except: print('get_history: unknown connect error3 ...') time.sleep(60) file.save(root + '\\' + f) file.close()
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] = ""
def fix_history(): for root, dirs, files in os.walk(os.getcwd() + '\\StockList'): files.reverse() for f in files: if f[-5:] == '.fail': file = openpyxl.load_workbook(root + '\\' + files[-1]) sheet = file.get_sheet_by_name('Sheet1') print(root, files[-1], f) number = int(files[-1][:4]) fail_year = int(f[3:7]) fail_month = int(f[7:9]) print('Stock:%d Y:%d M:%02d' % (number, fail_year, fail_month)) start_date = twstock.codes[str(number)][4].split('/') start_date = datetime.date(int(start_date[0]), int(start_date[1]), int(start_date[2])) target_date = datetime.date(2002, 11, 1) if start_date > target_date: target_date = start_date year = fail_year month = fail_month stock = twstock.Stock(str(number)) i = 0 try: while True: # handle data print(' %d %d parsing...' % (year, month)) if not os.path.isfile(root +'\\raw%d%02d'%(year,month)): handle_history_data(stock, year, month, root + '\\raw%d%02d' % (year, month), sheet) if Global.skip: error_file = open(root +'\\raw%d%02d.fail'%(year,month), 'w') error_file.close() if year == datetime.date.today().year and month == datetime.date.today().month: break else: if os.path.isfile(root + '\\' + f): os.remove(root + '\\' + f) if target_date.year == year and target_date.month == month: print(target_date.year, target_date.month, ' end') break i += 1 month -= 1 if month == 0: year -= 1 month = 12 file.save(root + '\\' + files[-1]) file.close() except: file.save(root + '\\' + files[-1]) file.close() print('fix_history: unknown connect error ...') time.sleep(60) break # only scan once
def genLastDay(twStockList): allStock = [] for key in sorted(twStockList.keys()): stockInfo = twStockList[key] # 先只撈股票 if stockInfo.type == '\u80a1\u7968' or stockInfo.type == '股票': sleep(randint(8, 10)) eachStackData = {} eachStackData["type"] = stockInfo.type eachStackData["code"] = stockInfo.code eachStackData["name"] = stockInfo.name eachStackData["ISIN"] = stockInfo.ISIN eachStackData["start"] = stockInfo.start eachStackData["market"] = stockInfo.market eachStackData["group"] = stockInfo.group eachStackData["CFI"] = stockInfo.CFI eachStackData["id"] = key print("讀取中: " + stockInfo.name + "(" + stockInfo.code + ")") stock = twstock.Stock(str(stockInfo.code)) # 取得各股一個月內有開盤的資料 dataNear31 = stock.fetch_31() print(dataNear31) eachStackData["datas"] = [] # 一個月內只取最新三天 for i in dataNear31[-3:]: dayInfoTemp = {} dayInfoTemp["date"] = str(i.date) # capacity 總成交股數 (單位: 股) dayInfoTemp["capacity"] = i.capacity # turnover 總成交金額 (單位: 新台幣/元) dayInfoTemp["turnover"] = i.turnover # open 開盤價 dayInfoTemp["open"] = i.open # high 盤中最高價 dayInfoTemp["high"] = i.high # low 盤中最低價 dayInfoTemp["low"] = i.low # close 收盤價 dayInfoTemp["close"] = i.close # change 漲跌價差 dayInfoTemp["change"] = i.change # transaction 成交筆數 dayInfoTemp["transaction"] = i.transaction eachStackData["datas"].append(dayInfoTemp) print(eachStackData) allStock.append(eachStackData) # 寫檔案 stockDataFile = open("stock.json", "w") stockDataFile.write( json.dumps(allStock, sort_keys=True, indent=4, separators=(',', ':'))) stockDataFile.close() # genLast3Day(twStockList)
def __init__(self, twstock_id, start): self.stock = twstock.Stock(twstock_id) self.stock.fetch_from(start.year, start.month - 3) self.ID = twstock_id self.Name = twstock.codes[twstock_id].name self.RawData = None self.DataFrame = None self.PNGFilename = '['+ datetime.date.today().strftime("%Y.%m.%d") + '][' + twstock_id + '] Result.png' self.Result = None
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)
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)
def monthP(Snum): #month Price stockFig = "%s.png" % (Snum) stock = twstock.Stock(Snum) stockData = {"close": stock.close, "date": stock.date, "open": stock.open} df1 = pd.DataFrame.from_dict(stockData) df1.plot(x="date", y="close") #heroku底下中文字型會出現KeyError,待解決 #plt.xlabel("日期", fontproperties = fontprop) #plt.ylabel("股價", fontproperties = fontprop) plt.title("[%s]" % (stock.sid)) plt.savefig(stockFig) plt.close() respon = uploadFig(stockFig) return respon
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")
def download_today_prices(): gupiao_path = os.path.join(settings.BASE_DIR, 'static', 'goodadmin', 'gupiao.csv') stock_cache = {} #slist = load_stocks.read_stocklist('C:\\Study\\HTC\\Django\\tango_with_django_project\\static\\goodadmin\\gupiao.csv') print(gupiao_path) slist = load_stocks.read_stocklist(gupiao_path) tday = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC) tday_tw = Talk2twStocks.UTC_To_Taipei(tday) print(tday_tw) stock_price_path = os.path.join(settings.BASE_DIR, 'static', 'goodadmin', 'stocks_' + str(tday_tw.date()) + '.csv') stock_file = open(stock_price_path, 'w', newline='') stock_writer = csv.writer(stock_file) stock_writer.writerow(['code', 'price']) failcount = 0 for scode in slist: print('{0} processing...'.format(scode)) try: rt_stock = twstock.Stock(scode, initial_fetch=False) rt_stock.fetch_from(tday.year, tday.month) time.sleep(1) if rt_stock.close is not None and len(rt_stock.close) != 0: p = rt_stock.close[-1] stock_writer.writerow([scode, str(p)]) stock_cache[scode] = p print(str(p)) else: print('fails') failcount = failcount + 1 except Exception: print('something wrong happend with {0}'.format(scode)) continue print('fail num {0}'.format(failcount)) stock_file.close() return stock_cache, tday_tw
def buttonClicked(self): sid = self.ui.comboBox.currentText().split("-")[0].strip() days = int(self.ui.lineEdit.text().strip()) stockdata = twstock.realtime.get(sid) self.ui.label_3.setText(stockdata["info"]["name"] + "(" + sid + ")" + ":" + " 收盤價:" + \ stockdata["realtime"]["latest_trade_price"] + " 開盤價:" + stockdata["realtime"]["open"] + \ " 最高價:" + stockdata["realtime"]["high"] + " 最低價:" + stockdata["realtime"]["low"] + \ " 時間:" + stockdata["info"]["time"]) stock = twstock.Stock(sid) mean5 = stock.moving_average(stock.price, 5) mean20 = stock.moving_average(stock.price, 20) capacity = stock.capacity for j in range(len(capacity)): capacity[j] = int(capacity[j] / 1000) self.ui.label_4.setText("近" + str(days) + "日股價:" + str(stock.price[-days:]).strip("[]")) self.ui.label_5.setText("近" + str(days) + "日的五日均線" + str(mean5[-days:]).strip("[]")) self.ui.label_6.setText("近" + str(days) + "日的二十日均線" + str(mean20[-days:]).strip("[]")) self.ui.label_7.setText("近" + str(days) + "日的成交量(張)" + str(capacity[-days:]).strip("[]")) self.ui.label_8.setText("倒數第二天之五日均價:" + str(mean5[-2]).strip("[]") + "倒數第二天之二十日均價:" + str(mean20[-2]).strip("[]") + \ "最後一天之五日均價:" + str(mean5[-1]).strip("[]") + "最後一天之二十日均價:" + str(mean20[-1]).strip("[]")) if mean5[-2] < mean20[-2]: if mean5[-1]>mean20[-1]: self.ui.label_9.setText("五日均線突破二十日均線") else: self.ui.label_9.setText("五日均線仍然低於二十日均線") else: if mean5[-1] > mean20[-1]: self.ui.label_9.setText("五日均線仍大於二十日均線") else: self.ui.label_9.setText("五日均線跌破二十日均線") plt.cla() plt.clf() self.ui.figure.clf() ax = self.ui.figure.add_axes([0.1, 0.1, 0.8, 0.8]) ax.set_title(sid) ax.plot(range(1, 32), stock.price) ax.set_xlabel("日期") ax.set_ylabel("日股價") self.ui.canvas.draw()
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)
def handle_message(event): print(event) text=event.message.text if (text=="Hi"): reply_text = "Hello John" #Your user ID elif(text=="你好"): reply_text = "哈囉" elif(text=="機器人"): reply_text = "叫我嗎" 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') #my_datetime = dt.fromtimestamp(stock_rt['timestamp']+8*60*60) #my_time = my_datetime.strftime('%H:%M:%S') content += '%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+='====' 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.reply_message( event.reply_token, TextSendMessage(text=content) ) else: reply_text = text #message=TextSendMessage(text=event.message.text) message=TextSendMessage(reply_text) line_bot_api.reply_message(event.reply_token,message)
def long_strategy(stockid): stock = twstock.Stock(stockid) price20 = stock.price[-20:] #月 price100 = stock.price[-100:] #年 ma_p20 = np.mean(price20) ma_p100 = np.mean(price100) if ma_p20 >= ma_p100: #print("可觀察,建議靠近月均價買進較佳,月線價格:"+str(ma_p20)) str1 = "符合20週均線大於20日均線之策略,(建議價格靠近20週均價買進:" + str("%.2f" % ma_p20) + ")" return str1 else: #print("不符合上漲趨勢,不建議買進!") str1 = "不符合20週均線大於20日均線之策略,不建議買進" return str1
def main(): if len(sys.argv) != 2: print("Please run the script as:\n$python3 adam.py stock_num") exit(1) stock_num = sys.argv[1] stock = twstock.Stock(str(stock_num)) # Convert to ohlc data quotes = [] for i in range(len(stock.date)): quotes.append((mdates.date2num(stock.date[i]), stock.open[i], stock.high[i], stock.low[i], stock.price[i])) # Print candlestick fig, ax = plt.subplots() plt.title(str(stock_num)) weekday_candlestick(quotes, ax, width=0.5, colorup='r', colordown='k')
def GetDataByTry(strST_Number, intY, intM): lstST_Data = [] stock = "No connection" for i in range(100): #print("Count: "+str(i)) j = 10*i+160 try: stock = twstock.Stock(strST_Number) lstPrice = stock.fetch(intY, intM) print (lstPrice) if lstPrice!= []: #print(str(j) + " seconds: Get data") return lstPrice, stock except: strTxt = (str(j) + " seconds: No data") print (strTxt) time.sleep(j) return lstST_Data, stock
def getStockInfo(stock_code): LOGGER.info(f"Processing {stock_code} ...") retry = 0 stock = None while retry <= StockInfoSetting.RETRY_MAX_TIME and stock is None: try: stock = twstock.Stock(stock_code) break except ConnectionError: LOGGER.warning( f'Grab {stock_code} Fail, Retry ({retry}/{StockInfoSetting.RETRY_MAX_TIME})' ) except Exception: LOGGER.warning( f'Grab {stock_code} Fail, Retry ({retry}/{StockInfoSetting.RETRY_MAX_TIME})', exc_info=True) retry += 1 sleep(1) return stock
def stockRT(Snum): #Stock Number respon = "" stock_rt = twstock.realtime.get(Snum) cur_datetime = datetime.fromtimestamp(stock_rt["timestamp"] + 8 * 60 * 60) cur_time = cur_datetime.strftime("%H:%M:%S") respon += "%s (%s) %s\n" % (stock_rt["info"]["name"], stock_rt["info"]["code"], cur_time) respon += "現價: %s / 開盤: %s\n" % ( stock_rt["realtime"]["latest_trade_price"], stock_rt["realtime"]["open"]) respon += "最高: %s / 最低: %s\n" % (stock_rt["realtime"]["high"], stock_rt["realtime"]["low"]) respon += "量: %s\n" % (stock_rt["realtime"]["accumulate_trade_volume"]) #stock = twstock.Stock("2330") stock = twstock.Stock(Snum) respon += "-----\n" respon += "最近五日價格: \n" price5 = stock.price[-5:][::-1] date5 = stock.date[-5:][::-1] for i in range(len(price5)): respon += "[%s] %s\n" % (date5[i].strftime("%Y-%m-%d"), price5[i]) return respon
def get_stock(cls, year, month): path = get_h5_name(year, month) if not os.path.exists(path): stock_code_dtype = pd.CategoricalDtype(cls.get_twse().index) todo = set(cls.get_twse().index) if os.path.exists(f'{path}.done.pkl'): df_s, done = pickle.load(open(f'{path}.done.pkl', 'rb')) else: df_s = [] done = set() pickle.dump((df_s, done), open(f'{path}.done.pkl', 'wb')) todo = todo.difference(done) for i, stock_code in enumerate(todo): try: stock = ts.Stock(stock_code, initial_fetch=False).fetch(year, month) df_s.append(pd.DataFrame(stock)) df_s[-1]['code'] = pd.Series(stock_code, index=df_s[-1].index, dtype=stock_code_dtype) done.add(stock_code) print( f'{stock_code} -- {100*len(done)/len(cls.get_twse().index):g}%' ) pickle.dump((df_s, done), open(f'{path}.done.pkl', 'wb')) except ConnectionError as e: print(e) cls._change_vpn() except Exception as e: print(e) cls._change_vpn() df = pd.concat(df_s) df.set_index(['code', 'date']) df.to_hdf(path, get_h5_key_name(year, month)) else: df = pd.read_hdf(path, get_h5_key_name(year, month)) return df
def stock_pic(search_no): stock_real = twstock.realtime.get(search_no) stock_name = stock_real['info']['name'] stock_no = twstock.Stock(search_no) close_price, dates = [], [] for stock_duration in stock_no.fetch_from(2019, 6): close_price.append(stock_duration.close) dates.append(stock_duration.date) fig = plt.figure(dpi=80, figsize=(12, 8)) plt.plot(dates, close_price) fig.autofmt_xdate(rotation=60) plt.title( stock_name, fontproperties="simHei", fontsize=24, ) plt.xlabel("date", fontsize=14) plt.ylabel("close_price", fontsize=14) plt.tick_params(axis='both', labelsize=12, color='red') plt.show()