def dataloader(stock_name,
               start='1995-01-01 01:00:00',
               end='2018-12-31 04:00:00',
               verbose=True):

    my_share = share.Share(stock_name)
    symbol_data = None

    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_YEAR, 30,
                                              share.FREQUENCY_TYPE_DAY, 1)
        if verbose:
            print(stock_name + " has been downloaded")

    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)
    df = pd.DataFrame(symbol_data)

    df['timestamp'] = [
        datetime.fromtimestamp(t / 1000) for t in df['timestamp']
    ]

    # test = df[(df['timestamp'] >= '2016-1-1 01:00:00') & (df['timestamp'] <= '2018-12-31 04:00:00')]
    return df[(df['timestamp'] >= start) & (df['timestamp'] <= end)]
Пример #2
0
def gethourlydata(name):
    my_share = share.Share(name)
    symbol_data = None
    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_DAY, 30,
                                              share.FREQUENCY_TYPE_MINUTE, 60)
    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)
    goodhoursspot = []
    for i in range(len(symbol_data['timestamp'])):
        strdata = str(
            datetime.fromtimestamp(symbol_data['timestamp'][i] / 1000))
        checker = strdata[14]
        if checker == '3':
            goodhoursspot.append(i)
    # print(goodhoursspot)
    # print(symbol_data['open'][5])
    goodopenprices = []
    goodhighprices = []
    goodlowprices = []
    goodcloseprices = []
    goodhours = []
    goodvolumes = []
    for i in goodhoursspot:
        # print(str(datetime.fromtimestamp(symbol_data['timestamp'][i] / 1000)))
        goodopenprices.append(symbol_data['open'][i])
        goodhighprices.append(symbol_data['high'][i])
        goodlowprices.append(symbol_data['low'][i])
        goodcloseprices.append(symbol_data['close'][i])
        goodhours.append(symbol_data['timestamp'][i])
        goodvolumes.append(symbol_data['volume'][i])
    # print(goodopenprices, goodhighprices, goodlowprices, goodcloseprices)
    return goodopenprices, goodhighprices, goodlowprices, goodcloseprices, goodhours, name, goodvolumes
Пример #3
0
    def __init__(self, ticker, adj=True):
        self.ticker = ticker
        self.closing_price = []
        _data = None

        _share = share.Share(self.ticker)
        _data = _share.get_historical(share.PERIOD_TYPE_YEAR, 2,
                                      share.FREQUENCY_TYPE_MONTH, 1, adj)
        if not _data:
            raise ValueError("No data on stock {}".format(ticker))

        for i in range(0, len(_data["timestamp"])):
            date = datetime.fromtimestamp(int(_data["timestamp"][i]) / 1000)
            if date >= datetime(2018, 6, 1) and date <= datetime(2019, 6, 2):
                self.closing_price.append(_data["close"][i])

        self.returns = []
        for i in range(1, len(self.closing_price)):
            if not self.closing_price[i] or not self.closing_price[i - 1]:
                self.returns.append(0)
            else:
                self.returns.append(self.closing_price[i] /
                                    self.closing_price[i - 1] - 1)

        self.average = np.mean(self.get_returns())
        self.stddev = np.std(self.get_returns(), ddof=1) * np.sqrt(12)
        self.var = self.stddev**2
Пример #4
0
def __getLastPrices(share_name, days=1):
    """
   This function returns last values of a share

   Parameters
   ----------
   share_name: str
      Share name in yahoo format
   
   Returns
   -------
   A pandas with last share values and TA
   """
    my_share = share.Share(share_name)
    symbol_data = None
    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_DAY, days,
                                              share.FREQUENCY_TYPE_DAY, 1)
    except YahooFinanceError as e:
        print(e.message)
    finally:
        if symbol_data is None:
            return None
        else:
            df = pd.DataFrame(symbol_data)
            return df
Пример #5
0
def Obtain_price(symbol):
    my_share = share.Share(symbol)
    symbol_data = None

    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_DAY,
                                            50,
                                            share.FREQUENCY_TYPE_HOUR,
                                            1)
    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)

    openrate = symbol_data['open']
    closerate = symbol_data['close']
    highest = symbol_data['high']
    lowest = symbol_data['low']
    # plt.scatter(newTime, y, label= "dots", color= "green",  marker= ".", s=30) 
    # plt.xlabel('Epoch Time')
    # plt.ylabel('Open Rate')

    # plt.title("Stock Price")
    # plt.legend() 
    # plt.show()
    # return [datelist[len(datelist)-1], y[len(y)-1]]
    return  openrate[len(openrate)-1], closerate[len(closerate)-1], highest[len(highest)-1], lowest[len(lowest)-1]
Пример #6
0
def getStockData(Co_info):
    stockData = dict()
    errorIdx = []
    for i in range(len(Co_info)):
        #企業指定
        my_share = share.Share(Co_info[i][0] + '.T')
        tmpData = None
        tmpDf = None
        try:
            #取得期間、周期
            tmpData = my_share.get_historical(share.PERIOD_TYPE_MONTH, 120,
                                              share.FREQUENCY_TYPE_WEEK, 1)
            tmpData["timestamp"] = [
                datetime.fromtimestamp(i / 1000) for i in tmpData["timestamp"]
            ]
            tmpDf = pd.DataFrame(data=tmpData)
            tmpDf["code"] = Co_info[i][0]
            stockData[Co_info[i][0]] = tmpDf
            print(
                datetime.now(pytz.timezone('Asia/Tokyo')).strftime('%T'), i,
                Co_info[i][0], Co_info[i][1])
            time.sleep(5)
        except Exception as e:
            print(
                datetime.now(pytz.timezone('Asia/Tokyo')).strftime('%T'), i, e)
            errorIdx.append(i)
            time.sleep(10)
    return stockData, errorIdx
Пример #7
0
def get5minData(symbol,period,outname):
    my_share = share.Share(symbol)
    symbol_data = None

    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_DAY,
                                            period,
                                            share.FREQUENCY_TYPE_MINUTE,
                                            5)
    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)


    # %%
    datalist=[]
    dates = list(symbol_data["timestamp"])
    opens = list(symbol_data["open"])
    highs = list(symbol_data["high"])
    lows = list(symbol_data["low"])
    closes = list(symbol_data["close"])
    volumes = list(symbol_data["volume"])
    for i in range(len(dates)):
        
        d = [dates[i],spfloat(opens,i),spfloat(highs,i),spfloat(lows,i),spfloat(closes,i),spfloat(volumes,i)]
        d[0]=datetime.datetime.fromtimestamp(d[0]/1000)
        datalist.append(d)

    final_df = pd.DataFrame(datalist, columns=['date','open','high','low','close','volume'])
    final_df.set_index('date',inplace = True)


    # %%
    final_df.to_csv(outname+'.csv')
Пример #8
0
def Obtain_price(company_symbol):
    my_share = share.Share(company_symbol)
    symbol_data = None

    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_DAY, 50,
                                              share.FREQUENCY_TYPE_HOUR, 1)
    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)

    x = symbol_data['timestamp']
    newTime = [z / 1000 for z in x]
    datelist = []
    for x in newTime:
        datelist.append(str(time.strftime('%d-%m-%Y', time.localtime(x))))

    del symbol_data['volume']

    symbol_data['timestamp'] = newTime
    save_output(symbol_data, "{}.csv".format(company_symbol))

    openrate = symbol_data['open']
    closerate = symbol_data['close']
    highest = symbol_data['high']
    lowest = symbol_data['low']

    lastest_open_rate = openrate[len(openrate) - 1]
    latest_close_rate = closerate[len(closerate) - 1]
    highest_price_for_today = highest[len(highest) - 1]
    lowest_price_for_today = lowest[len(lowest) - 1]

    return lastest_open_rate, latest_close_rate, highest_price_for_today, lowest_price_for_today
Пример #9
0
def get_single_stock_yahoo(ticker):
    stock = share.Share(ticker)
    #    result_lst = stock.get_historical('2016-01-01', '2021-03-10')
    #    ticker_arr, date_arr, open_arr, high_arr, low_arr, close_arr, adj_arr, volume_arr = [], [], [], [], [], [], [], []
    #    for result in result_lst:
    #        date_arr.append(result['Date'])
    #        open_arr.append(result['Open'])
    #        high_arr.append(result['High'])
    #        low_arr.append(result['Low'])
    #        close_arr.append(result['Close'])
    #        adj_arr.append(result['Adj_Close'])
    #        volume_arr.append(result['Volume'])
    #        ticker_arr.append(ticker)
    #    return pd.DataFrame.from_dict({"Ticker": ticker_arr, "Date": date_arr, "Open": open_arr, "High": high_arr, "Low": low_arr, "Close": close_arr, "Adj.Close": adj_arr, "Volume": volume_arr})
    url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?symbol={ticker}&period1=1457568000&period2=1615334400&interval=1d&includePrePost=true&events=div%7Csplit%7Cearn&lang=en-US&region=US&crumb=t5QZMhgytYZ&corsDomain=finance.yahoo.com"
    #    data = stock.get_historical(share.PERIOD_TYPE_DAY, 1250, share.FREQUENCY_TYPE_DAY, 1)
    data = requests.get(url).json()
    data = data["chart"]["result"][0]
    date_arr = [
        datetime.fromtimestamp(x).strftime("%Y-%m-%d")
        for x in data["timestamp"]
    ]
    data = data["indicators"]["quote"][0]
    data["date"] = date_arr
    data["ticker"] = [ticker] * len(date_arr)
    data.pop("timestamp", None)
    return pd.DataFrame.from_dict(data)
Пример #10
0
def lineear_regression(symbol):
    my_share = share.Share(symbol)
    symbol_data = None

    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_YEAR,
                                            15,
                                            share.FREQUENCY_TYPE_DAY,
                                            1)
    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)

    x = symbol_data['timestamp']
    newTime = [z / 1000 for z in x]
    datelist = []
    for x in newTime:
        datelist.append(str(time.strftime('%Y-%m-%d', time.localtime(x))))
    tempopenrate = symbol_data['open']
    openrate = [round(x,2) for x in tempopenrate]
    tempcloserate = symbol_data['close']
    closerate = [round(x,4) for x in tempopenrate]
    volume = symbol_data['volume']
    low = symbol_data['low']
    high = symbol_data['high']
    return datelist,openrate, closerate, low, high
Пример #11
0
def get_price(symbol):
    my_share = share.Share(symbol)
    symbol_data = None

    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_DAY,
                                            50,
                                            share.FREQUENCY_TYPE_HOUR,
                                            1)
    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)

    x = symbol_data['timestamp']
    newTime = [z / 1000 for z in x]
    datelist = []
    for x in newTime:
        datelist.append(str(time.strftime('%d-%m-%Y', time.localtime(x))))
    tempopenrate = symbol_data['open']
    openrate = [round(x,2) for x in tempopenrate]


    # plt.scatter(newTime, y, label= "dots", color= "green",  marker= ".", s=30) 
    # plt.xlabel('Epoch Time')
    # plt.ylabel('Open Rate')

    # plt.title("Stock Price")
    # plt.legend() 
    # plt.show()
    return datelist, openrate
Пример #12
0
def main(code, company):
    code = str(code)
    my_share = share.Share(code + '.T')
    symbol_data = None

    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_YEAR, 2,
                                              share.FREQUENCY_TYPE_DAY, 1)
        df = pd.DataFrame(symbol_data.values(), index=symbol_data.keys()).T
        df.timestamp = pd.to_datetime(df.timestamp, unit='ms')
        df.index = pd.DatetimeIndex(df.timestamp, name='timestamp')

    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)

    after_covid19 = df[(df.index >= dt.datetime(2020, 11, 1)) & (df.index <= dt.datetime(2021, 4, 30))]
    after_covid19 = round(after_covid19.close.mean())
    before_covid19 = df[(df.index >= dt.datetime(2019, 6, 1)) & (df.index <= dt.datetime(2019, 12, 31))]
    before_covid19 = round(before_covid19.close.mean())
    ratio = round(after_covid19 / before_covid19, 2)

    print("code: {}. company: {}".format(code, company))
    print(before_covid19, after_covid19, ratio)
    stock_df.loc[i] = [code, company, before_covid19, after_covid19, ratio]
Пример #13
0
def get_data():
    global old_time, now_time, old_price, now_price, change_rate, data_volume, corona_date, corona_price, corona_time, corona_rate
    my_share = share.Share(row_str + '.T')
    symbol_data = None
    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_YEAR, 20,
                                              share.FREQUENCY_TYPE_MONTH, 1)
        #time.sleep(1)
        date = symbol_data["timestamp"]
        old_date = date[0]
        now_date = date[-1]
        corona_date = date[-6]
        old_time = datetime.utcfromtimestamp(old_date / 1000)
        now_time = datetime.utcfromtimestamp(now_date / 1000)
        corona_time = datetime.utcfromtimestamp(corona_date / 1000)
        price = symbol_data["close"]
        old_price = price[0]
        now_price = price[-1]
        corona_price = price[-6]
        change_rate = '{:.2f}'.format(now_price / old_price)
        corona_rate = '{:.2f}'.format(corona_price / old_price)
        data_volume = len(date)
    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)
Пример #14
0
def handle_one_stock(ticker, index):

    my_share = share.Share(ticker)
    symbol_data = None
    try:
        symbol_data_1y = my_share.get_historical(share.PERIOD_TYPE_YEAR, 1,
                                                 share.FREQUENCY_TYPE_DAY, 1)
        symbol_data_2y = my_share.get_historical(share.PERIOD_TYPE_YEAR, 2,
                                                 share.FREQUENCY_TYPE_DAY, 1)
        symbol_data_5y = my_share.get_historical(share.PERIOD_TYPE_YEAR, 5,
                                                 share.FREQUENCY_TYPE_DAY, 1)
        ### Convert from ms to min ###
        time_1y = pd.Series(symbol_data_1y['timestamp'])
        time_2y = pd.Series(symbol_data_2y['timestamp'])
        time_5y = pd.Series(symbol_data_5y['timestamp'])
        open_1y = pd.Series(symbol_data_1y['open'])
        open_1y = open_1y.fillna(method='ffill')
        open_1y = open_1y.interpolate(method='nearest')
        open_2y = pd.Series(symbol_data_2y['open'])
        open_2y = open_2y.fillna(method='ffill')
        open_2y = open_2y.interpolate(method='nearest')
        open_5y = pd.Series(symbol_data_5y['open'])
        open_5y = open_5y.fillna(method='ffill')
        open_5y = open_5y.interpolate(method='nearest')

        close_1y = pd.Series(symbol_data_1y['close'])
        close_1y = open_1y.fillna(method='ffill')
        close_1y = open_1y.interpolate(method='nearest')
        close_2y = pd.Series(symbol_data_2y['close'])
        close_2y = open_2y.fillna(method='ffill')
        close_2y = open_2y.interpolate(method='nearest')
        close_5y = pd.Series(symbol_data_5y['close'])
        close_5y = open_5y.fillna(method='ffill')
        close_5y = open_5y.interpolate(method='nearest')

    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)
    open_1y = np.array(open_1y.tolist())
    open_2y = np.array(open_2y.tolist())
    open_5y = np.array(open_5y.tolist())
    close_1y = np.array(close_1y.tolist())
    close_2y = np.array(close_2y.tolist())
    close_5y = np.array(close_5y.tolist())

    output = {
        'time_1y': time_1y,
        'time_2y': time_2y,
        'time_5y': time_5y,
        'open_1y': open_1y,
        'open_2y': open_2y,
        'open_5y': open_5y,
        'close_1y': close_1y,
        'close_2y': close_2y,
        'close_5y': close_5y
    }

    return output
Пример #15
0
def get_share_info_list(info_list, period_day, frequency_day):
    share_list = []
    symbol_data_list = []
    for code in info_list:
        share_list.append(share.Share(str(code) + '.T'))
    for share_info in share_list:
        symbol_data_list.append(
            get_share_info(share_info, period_day, frequency_day))
    return symbol_data_list
Пример #16
0
def download_symbol_data(selected_symbol, selected_period, selected_freqtype,
                         period_number, selected_freqnum):
    my_share = share.Share(selected_symbol)

    if selected_period == 'day':
        period_type = share.PERIOD_TYPE_DAY
    elif selected_period == 'week':
        period_type = share.PERIOD_TYPE_WEEK
    elif selected_period == 'month':
        period_type = share.PERIOD_TYPE_MONTH
    elif selected_period == 'year':
        period_type = share.PERIOD_TYPE_YEAR

    if selected_freqtype == 'min':
        freqtype = share.FREQUENCY_TYPE_MINUTE
    elif selected_freqtype == 'hour':
        freqtype = share.FREQUENCY_TYPE_HOUR
    elif selected_freqtype == 'day':
        freqtype = share.FREQUENCY_TYPE_DAY
    elif selected_freqtype == 'week':
        freqtype = share.FREQUENCY_TYPE_WEEK
    elif selected_freqtype == 'month':
        freqtype = share.FREQUENCY_TYPE_MONTH
    print(freqtype)

    if selected_freqnum == '1m':
        freqnum = 1
    elif selected_freqnum == '2m':
        freqnum = 3
    elif selected_freqnum == '5m':
        freqnum = 5
    elif selected_freqnum == '15m':
        freqnum = 15
    elif selected_freqnum == '30m':
        freqnum = 30
    elif selected_freqnum == '60m':
        freqnum = 60
    elif selected_freqnum == '90m':
        freqnum = 90
    elif selected_freqnum == '1h':
        freqnum = 1
    elif selected_freqnum == '1d':
        freqnum = 1
    elif selected_freqnum == '5d':
        freqnum = 5
    elif selected_freqnum == '1w':
        freqnum = 1
    elif selected_freqnum == '1mo':
        freqnum = 1
    elif selected_freqnum == '3mo':
        freqnum = 3

    result = None
    result = my_share.get_historical(period_type, int(period_number), freqtype,
                                     freqnum)
    return result
Пример #17
0
def company_stock(period_type, period, company_code):
    my_share = share.Share(company_code + '.T')
    symbol_data = None

    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_DAY,
                                            period_type,
                                            share.FREQUENCY_TYPE_MINUTE,
                                            period)
    except YahooFinanceError as e:
        logger.error(e.message)
        sys.exit(1)

    from datetime import datetime, timezone, timedelta

    date = symbol_data["timestamp"]

    old_datetime = datetime.fromtimestamp(date[0]/1000)
    now_datetime = datetime.fromtimestamp(date[len(date) - 1]/1000)

    old_date = old_datetime.strftime('%Y-%m-%d')
    now_date = now_datetime.strftime('%Y-%m-%d')

    old_time = old_datetime.strftime('%H:%M:%S')
    now_time = now_datetime.strftime('%H:%M:%S')

    

    price = symbol_data["close"]
    old_price = price[0]
    now_price = price[len(date) - 1]
    logger.info(str(old_time) + "の時の株価: " + str(old_price))
    logger.info(str(now_time) + "の時の株価: " + str(now_price))

    body = [
        [old_date, old_time, str(old_price)],
        [now_date, now_time, str(now_price)]
    ]

    df = pd.DataFrame(symbol_data.values(), index=symbol_data.keys()).T
    df.timestamp = pd.to_datetime(df.timestamp, unit='ms')
    df.index = pd.DatetimeIndex(df.timestamp, name='timestamp').tz_localize('UTC').tz_convert('Asia/Tokyo')

    plt.figure(figsize=(10 ,5))
    plt.title(company_code, color='black', size=15, loc='center') # title(タイトル, 線の色, 背景色, フォントサイズ, タイトル位置)
    plt.plot(df.index, price, label='close', color='blue')
    # plt.show()
    return body

# plt.figure(figsize=(10 ,5))

# import time

# company_stock(2, 1, '9201.T')
Пример #18
0
def getdailydata(name):
    stockname = name
    my_share = share.Share(stockname)
    symbol_data = None
    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_MONTH,3,share.FREQUENCY_TYPE_DAY,1)
    except YahooFinanceError as e:
        print(e.message)
        return('bad')
    #print(len(symbol_data['open']))
    return('cool')
Пример #19
0
def getdailydata(name):
    my_share = share.Share(name)
    symbol_data = None
    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_MONTH, 12, share.FREQUENCY_TYPE_DAY, 1)
    except YahooFinanceError as e:
        print(e.message)
        return 'bad'
    # print(len(symbol_data['open']))
    return (symbol_data['open'], symbol_data['high'], symbol_data['low'],
            symbol_data['close'], symbol_data['timestamp'], name, symbol_data['volume'])
Пример #20
0
    def get_historical(self, stock_name):
        my_share = share.Share(stock_name)
        symbol_data = None

        try:
            symbol_data = my_share.get_historical(share.PERIOD_TYPE_DAY, 0.01,
                                                  share.FREQUENCY_TYPE_MINUTE,
                                                  1)
        except YahooFinanceError as e:
            print(e.message)
            sys.exit(1)

        return pd.DataFrame.from_dict(symbol_data)
Пример #21
0
def open_file(stock):
    # stock_data = []

    stock_share = share.Share(stock)
    symbol_data = None

    try:
        symbol_data = stock_share.get_historical(share.PERIOD_TYPE_YEAR, 500,
                                                 share.FREQUENCY_TYPE_DAY, 1)
    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)

    return transform_symbol_data(symbol_data)
Пример #22
0
    def get_data(self,ticker):
        self.ticker = ticker
        if isinstance(self.ticker,str):
            print('took_str_option')
            self.my_share = share.Share(self.ticker)
            self.data = self.my_share.get_historical(share.PERIOD_TYPE_DAY,
                                                    100,
                                                    share.FREQUENCY_TYPE_MINUTE,
                                                    30)
            self.result = list(zip(self.data['timestamp'],self.data['open']))
            self.result = [(dt.datetime.fromtimestamp(x[0]/1000),x[1]) for x in self.result]  
            return self.result

        elif isinstance(self.ticker,list):
            print('took_list_option')
            self.my_share = share.Share(self.ticker)
            self.data = self.my_share.get_historical(share.PERIOD_TYPE_DAY,
                                                    1000,
                                                    share.FREQUENCY_TYPE_MINUTE,
                                                    50)
            self.result = list(zip(self.data['timestamp'],self.data['open']))
            self.result = [(dt.datetime.fromtimestamp(x[0]/1000),x[1]) for x in self.result]
            return self.result
def getData(dayLen=7):
    stock = share.Share("TSLA")
    weekData = dict(
        stock.get_historical(share.PERIOD_TYPE_DAY, dayLen,
                             share.FREQUENCY_TYPE_DAY, 1))
    for x in range(len(weekData["timestamp"])):
        timestamp = int(str(int(int((weekData["timestamp"][x])) / 1000)))
        dt_object = datetime.fromtimestamp(timestamp)
        dt_object = str(dt_object)
        dt_object = dt_object[:10]
        someDict = weekData
        weekData["timestamp"][x] = dt_object

    return dict(weekData)
Пример #24
0
def main(args):
    # default grab the last 75 days
    import datetime
    if args.csv:
        import pandas as pd
        data = pd.read_csv(args.csv)
    else:
        today = datetime.date.today()
        ticker = share.Share(args.ticker)
        data = ticker.get_historical(share.PERIOD_TYPE_DAY,args.start,share.FREQUENCY_TYPE_MINUTE,int(60/args.frequency))
    torch.save({
        'inputs':get_inputs(data),
        'targets':get_targets(data)
    },args.output_file)
Пример #25
0
def fetch_yahoo():
    my_share = share.Share('^HSI')
    symbol_data = None

    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_DAY, 0,
                                              share.FREQUENCY_TYPE_DAY, 5)
    except YahooFinanceError as e:
        print(e.message)
        sys.exit(1)

    new_x = {'Open': [], 'High': [], 'Low': []}
    new_x['Open'].append(symbol_data.get('open')[0])
    new_x['High'].append(symbol_data.get('high')[0])
    new_x['Low'].append(symbol_data.get('low')[0])
    return new_x
Пример #26
0
def get_ticker_data_1(ticker):
    my_share = share.Share(ticker)
    try:
        data = my_share.get_historical(share.PERIOD_TYPE_DAY,
                                                        100,
                                                        share.FREQUENCY_TYPE_MINUTE,
                                                        30)                                               
        if data is not None:
            res = list(zip(data['timestamp'],data['open'],data['high'],data['low'],data['close']))
            res = [(dt.datetime.fromtimestamp(x[0]/1000),x[1]) for x in res]   
            df = pd.DataFrame(res,columns=['time','open','high','low','close'])
            return df
        else:
            print('No Data from YahooFinance')     
            return None
    except exceptions.YahooFinanceError:
        pass
Пример #27
0
def getdailydata(name):
    my_share = share.Share(name)
    symbol_data = None
    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_MONTH, 10, share.FREQUENCY_TYPE_DAY, 1)
    except YahooFinanceError as e:
        print(e.message)
        return 'bad'
    # print(len(symbol_data['open']))
    try:
        if not symbol_data['open']:
            return 'bad'
        return (symbol_data['open'], symbol_data['high'], symbol_data['low'],
                symbol_data['close'], symbol_data['timestamp'], name, symbol_data['volume'])
    except TypeError:
        print(" non subscriptable: " + str(name), end=' ')
        return 'bad'
Пример #28
0
def getfourhourdata(name):
    my_share = share.Share(name)
    symbol_data = None
    try:
        symbol_data = my_share.get_historical(share.PERIOD_TYPE_DAY, 30,
                                              share.FREQUENCY_TYPE_MINUTE, 60)
    except YahooFinanceError as e:
        print(e.message)
        return 'bad'
    goodhoursspot = []
    for i in range(len(symbol_data['timestamp'])):
        strdata = str(
            datetime.fromtimestamp(symbol_data['timestamp'][i] / 1000))
        checker = strdata[14]
        if checker == '3':
            goodhoursspot.append(i)
    # print(goodhoursspot)
    # print(symbol_data['open'][5])
    goodopenprices = []
    goodhighprices = []
    goodlowprices = []
    goodcloseprices = []
    goodhours = []
    goodvolumes = []
    keep = 0
    for i in goodhoursspot:
        if keep == 7:
            keep = 0
        if keep == 0 or keep == 4:
            if keep == 0:
                high = max(symbol_data['high'][i:i + 4])
                low = min(symbol_data['low'][i:i + 4])
            if keep == 4:
                high = max(symbol_data['high'][i:i + 3])
                low = min(symbol_data['low'][i:i + 3])
            # print(str(datetime.fromtimestamp(symbol_data['timestamp'][i] / 1000)))
            goodopenprices.append(symbol_data['open'][i])
            goodhighprices.append(high)
            goodlowprices.append(low)
            goodcloseprices.append(symbol_data['close'][i])
            goodhours.append(symbol_data['timestamp'][i])
            goodvolumes.append(symbol_data['volume'][i])
        keep += 1
    # print(goodopenprices, goodhighprices, goodlowprices, goodcloseprices)
    return goodopenprices, goodhighprices, goodlowprices, goodcloseprices, goodhours, name, goodvolumes
Пример #29
0
def get_ticker_data(ticker):
    my_share = share.Share(ticker)
    try:
        data = my_share.get_historical(share.PERIOD_TYPE_DAY, 100,
                                       share.FREQUENCY_TYPE_MINUTE, 30)
        if data is not None:
            res = list(zip(data['timestamp'], data['open']))
            res = [(dt.datetime.fromtimestamp(x[0] / 1000), x[1]) for x in res]
            df = pd.DataFrame.from_dict({
                'value': [x[1] for x in res],
                'time': [x[0] for x in res]
            })
            return df
        else:
            print('No Data from YahooFinance')
            return None
    except exceptions.YahooFinanceError:
        pass
Пример #30
0
def get_stock_data(ticker):
    stock = share.Share(ticker)
    stock_info = stock.get_historical(share.PERIOD_TYPE_DAY, 1, share.FREQUENCY_TYPE_DAY, 1)
    open_value = None
    close_value = None
    try:
        for key, value in stock_info.items():
            if key == 'open':
                open_value = value[0]
            if key == 'close':
                close_value = value[0]
        current = close_value
        change = ((close_value - open_value) / open_value) * 100
        current_rounded = math.ceil(current * 100)/100
        change_rounded = math.ceil(change * 100)/100
        return {'ticker': ticker, 'current': current_rounded, 'change': change_rounded}
    except AttributeError:
        return {'ticker': ticker, 'current': '-', 'change': '-'}