def fetch(twid='2330', csv="", start_time=None, end_time=datetime.now()): if start_time == None: start_time = datetime.strptime(start, "2010-1-1") if csv == "": csv = twid + ".csv" stock = Stock(twid) stock.fetch_from(int(start_time.strftime("%Y")), int(start_time.strftime("%m"))) stock_to_googleCSV(stock, csv)
def get_data(ticker): stock = Stock(ticker) index = Stock('3056') data = stock.fetch_from(n_yrs_ago.year, n_yrs_ago.month) data_index = index.fetch_from(n_yrs_ago.year, n_yrs_ago.month) s_close = [] tpe_index = [] for i in range(len(data)): s_close.append(data[i][6]) tpe_index.append(data_index[i][6] * 500) df_close = pd.DataFrame(s_close) df_index = pd.DataFrame(tpe_index) df_close_index = pd.DataFrame(list(zip(s_close, tpe_index))) conv_to_csv(df_close, df_index, df_close_index, ticker) frame = [df_close, df_index] return frame
def complate_data(self, sid): ret = False last_date = self.date[-1] stock = Stock(sid, initial_fetch=False) fetch_from_date = mdates.num2date(last_date) + timedelta(-10) stock.fetch_from(fetch_from_date.year, fetch_from_date.month) col_num = len(self.raw[0]) # csv 檔的 column 數 append_str = "" for index in range(0, col_num - 5): append_str = append_str + ",0" for index in range(-len(stock.date), 0): d = stock.date[index] o = stock.open[index] h = stock.high[index] l = stock.low[index] c = stock.close[index] if (mdates.date2num(d) > last_date): str = "{0},{1},{2},{3},{4}".format(d.strftime('%Y/%m/%d'), o, h, l, c) print("資料回補:" + str) f = open(self.filename, 'a+') f.write(str + append_str + "\n") f.close() ret = True #return ret # no yahoo #yahoo 資料確認 # d,o,h,l,c = self.complete_data_yahoo(sid) # #print(d,o,h,l,c) # try: # if(mdates.date2num(d) > mdates.date2num(stock.date[-1]) and mdates.date2num(d) > last_date ): # str = "{0},{1},{2},{3},{4}".format(d.strftime('%Y/%m/%d'),o,h,l,c ) # print("資料回補 yahoo:" + str) # f = open(self.filename, 'a+') # f.write(str+append_str+"\n") # f.close() # ret = True # except: # print("Error 資料回補 yahoo:" + str) # pass # 有更新資料時,回傳True return ret
def dump_updated_sid(dir_path, codes): """ stock = Stock('2330') ma_p = stock.moving_average(stock.price, 5) # 計算五日均價 ma_c = stock.moving_average(stock.capacity, 5) # 計算五日均量 ma_p_cont = stock.continuous(ma_p) # 計算五日均價持續天數 ma_br = stock.ma_bias_ratio(5, 10) # 計算五日、十日乖離值 """ for sid in codes: print('code {}'.format(sid)) stock = Stock(sid) stock.fetch_from(2018, 8) # Data(date=datetime.datetime(2017, 5, 2, 0, 0), capacity=45851963, turnover=9053856108, open=198.5, high=199.0, low=195.5, close=196.5, change=2.0, transaction=15718) sid2date2data = {} for ins in stock.data: sys.stdout.write('.') date = ins.date.strftime('%Y%m%d') open_p = ins.open close_p = ins.close high = ins.high low = ins.low change = ins.change capacity = ins.capacity transaction = ins.transaction turnover = ins.turnover if sid not in sid2date2data: sid2date2data[sid] = {} data = (high, low, open_p, close_p, change, capacity, transaction, turnover) sid2date2data[sid][date] = data for sid in sid2date2data: file_path = os.path.join(dir_path, '{}.csv'.format(sid)) with open(file_path, 'w') as w: for date in sorted(sid2date2data[sid].keys()): high, low, open_p, close_p, change, capacity, transaction, turnover = sid2date2data[ sid][date] w.write(','.join( map(str, [ sid, date, open_p, close_p, high, low, change, capacity, transaction, turnover ])) + '\n') print('')
import DateAgoTest import pandas as pd import matplotlib.pyplot as plt from talib import abstract from twstock import Stock stockID = '2330' stock = Stock(stockID) total = [] DList = DateAgoTest('2019-07', 7) stockData = stock.fetch_from(2019, 7) head = ["date", "capacity", "turnover", "open", "high", "low", "close", "change", "transaction"] for value in stockData: day = str(value[0]).split() if day[0] in DList: total.append([day[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7], value[8]) df = pd.DataFrame(total, columns = head) df.set_index('date', inplace = True) df['close'].plot(figsize=(16, 8))
else: yrs = localtime.tm_year mon = localtime.tm_mon print(yrs, mon) stock_num = input("Enter Stock: ") for i in range(1, 6): time.sleep(1) print("Wait.... ", 5 - i, "second") stock = Stock(stock_num) print("First Stage complete ") data = pd.DataFrame(stock.fetch_from(yrs, mon)) data.set_index('date', inplace=True) data.index = data.index.format(formatter=lambda x: x.strftime('%Y-%m-%d')) print("Fetching complete") fig = plt.figure(figsize=(24, 16)) #用add_axes創建副圖框 ax = fig.add_axes([0.05, 0.25, 0.95, 0.75]) ax2 = fig.add_axes([0.05, 0.05, 0.95, 0.25]) ax.set_title(stock_num + "KChart", fontsize=12) ax2.set_xticks(range(0, len(data.index), 10)) ax2.set_xticklabels(data.index[::10], rotation=0) #使用mpl_finance套件 mpf.candlestick2_ochl(ax, data['open'], data['close'],
#!/usr/bin/env python3 import pandas as pd import matplotlib.pyplot as plt from talib import abstract from twstock import Stock stock = Stock('2330') df = pd.DataFrame(stock.fetch_from(2019, 7)) df.set_index('date', inplace=True) df['close'].plot(figsize=(16, 8)) plt.show()
import pandas as pd from datetime import datetime import twstock from twstock import Stock import time from tqdm import tqdm stock = Stock("2330") time.sleep(2) # 延遲兩秒 stock.fetch_from(2020, 5) date = stock.date #日期 high_price = stock.high #盤中最高價 low_price = stock.low # 盤中最低價 close_price = stock.close #收盤價 open_price = stock.open # 開盤價 capacity = stock.capacity # 總成總成交股數 turnover = stock.turnover # 總成交金額 change = stock.change # 漲跌價差 transaction = stock.transaction # 成交筆數 day_number = len(date) # 建立 和天數相符的 [0] list day_list = [] day_list = [0] * day_number #把取出的time 轉乘int 再存入day_list for i in tqdm(range(day_number)):