Пример #1
0
def get_company_daily_price(symbol):
	ts = TimeSeries(key='GU7Q0FX7R704IRRZ')
	company_all_data, company_meta = ts.get_daily(symbol=symbol, outputsize='full')
	index_all_data, index_data = ts.get_daily(symbol='IVV', outputsize='full')
	keys_company = sorted(company_all_data.keys())[-1261:]
	keys_index = sorted(index_all_data.keys())[-1261:]
	differences = []
	dates = []
	for i in range(len(keys_company)-1):
		company_previous_day_close = float(company_all_data[keys_company[i]][_close])
		company_next_day_close = float(company_all_data[keys_company[i+1]][_close])

		index_previous_day_close = float(index_all_data[keys_company[i]][_close])
		index_next_day_close = float(index_all_data[keys_company[i+1]][_close])

		company_percent_change = utils.get_percent_change(company_previous_day_close, company_next_day_close)
		index_percent_change = utils.get_percent_change(index_previous_day_close, index_next_day_close)

		diff = company_percent_change - index_percent_change
		differences.append(diff)
	data = {
		'dates': keys_company[:-1],
		'percent_difference': differences
	}
	data_df = pd.DataFrame(data)
	data_df = data_df.set_index('dates')
	return data_df
Пример #2
0
def graph():
    api_key = 'MWDBRJVDC3PYQZEC'
    stock = request.form.get("stock")
    choice = request.form.get("features")
    title = "Richard's App"
    ts = TimeSeries(key=api_key, output_format='pandas')

    p = figure(width=600, height=400, x_axis_type='datetime')
    #Collect data depending on user's stock and price choices
    if choice == 'close':
        data, meta_data = ts.get_daily(symbol=stock, outputsize='full')
        data['date_time'] = data.index
        p.line(data['date_time'], data['4. close'], line_width=2)
    elif choice == 'adj_close':
        data, meta_data = ts.get_daily_adjusted(symbol=stock,
                                                outputsize='full')
        data['date_time'] = data.index
        p.line(data['date_time'], data['5. adjusted close'], line_width=2)
    elif choice == 'open':
        data, meta_data = ts.get_daily(symbol=stock, outputsize='full')
        data['date_time'] = data.index
        p.line(data['date_time'], data['1. open'], line_width=2)

    script, div = components(p)

    return render_template("graph.html",
                           div=div,
                           script=script,
                           stock=stock,
                           choice=choice)
Пример #3
0
def get_data(company):
    """ The data is retrieved from the API based on teh stock symbol supplied by the user
        and run through the Preprocessor. If it all goes successfully, the user is directed
        to the load webpage. If not, they are returned to the home page.
        
        Parameters:
            company(str): stock symbol of the stock that the model analyzed
    """

    # if the user selected a stock that doesn't exist, they will be redirected back to
    # the start page and prompted to enter a stock symbol again
    try:
        ts = TimeSeries(key='ENTERAPIKEYHERE', output_format='pandas')
        data, __ = ts.get_daily(symbol=company, outputsize='full')
        index_data, __ = ts.get_daily(symbol='INX', outputsize='full')
    except KeyError:
        return redirect('/')

    prep = Preprocessor(data, index_data)
    prep.append_SP_data()
    prep.remove_nulls()
    prep.split_date_features()
    prep.convert_data_types()

    X_pred = prep.remove_current_data()
    x, y = prep.get_data()

    # We store this data locally because it is too big to be stored as a browser cookie
    X_pred.to_csv('prediction_data.csv', index=False)
    x.to_csv('x.csv', index=False)
    y.to_csv('y.csv', index=False)

    return render_template('load.html', company=company)
Пример #4
0
 def getDailyDataFromAlpha(self, company, numDays):
     print(company, numDays)
     ts = TimeSeries(key='7ERSLTME9P4Q0F6V', output_format = 'pandas')
     if numDays < 100:
         df = ts.get_daily(symbol=company, outputsize='compact')[0][-1-numDays:-1]
     else:
         df = ts.get_daily(symbol=company, outputsize='full')[0][-1-numDays:-1]
     df.columns = self.dataColumns
     return df
Пример #5
0
def bubble(account, key, groupkey='Category', days_past=60):
    ts = TimeSeries(key=key, output_format='pandas')
    df = account.portfolio
    if groupkey == 'Category':
        df_columns = ['Return', 'Risk', 'Value']
        new_df = pd.DataFrame(columns=df_columns)
        catdf = df.Value.groupby([df.Cat, df.Ticker]).sum()
        #Calculate the risk (Volatility)
        for cat in catdf.index.get_level_values(0).unique().tolist():
            if (cat == 'Bond' or cat == 'Cash'):
                treturn = 0.0
                vol = 0.0
                total_value = catdf[cat].sum()
            else:
                total_value = catdf[cat].sum()  #To be used in weighted sums
                treturn = 0.0
                vol = 0.0
                for ticker in catdf[cat].index:
                    print(ticker)
                    weight = catdf[cat][ticker] / total_value
                    if ticker == 'Principal':
                        history = ts.get_daily(
                            symbol='SCHX')[0].loc[:, '4. close']
                    else:
                        history = ts.get_daily(
                            symbol=ticker)[0].loc[:, '4. close']
                    history = history.iloc[-days_past:]
                    vol = weight * Volatility(history).std() + vol
                    treturn = weight * (history.iloc[-1] /
                                        history.iloc[0]) + treturn

            tempdf = pd.DataFrame.from_records(data=[(treturn, vol,
                                                      total_value)],
                                               columns=df_columns,
                                               index=[cat])
            new_df = new_df.append(tempdf)
    new_df.drop(['Bond', 'Cash'], inplace=True)
    fig, ax = plt.subplots(figsize=(30, 30))
    new_df.plot.scatter(x='Return',
                        y='Risk',
                        s=new_df['Value'] / 8,
                        ax=ax,
                        alpha=.5)
    for cat in new_df.index:
        ax.text(new_df.loc[cat, 'Return'],
                new_df.loc[cat, 'Risk'],
                cat,
                fontsize=20)

    return new_df
Пример #6
0
def download_alpha(ticker: str, base_dir: str = default_data_dir) -> pd.DataFrame:
    data = None
    global alpha_count

    try:
        ts = TimeSeries(key=ALPHA_KEY, retries=0)
        data, meta_data = ts.get_daily(ticker, outputsize='full')
    except Exception as err:
        if 'Invalid API call' in str(err):
            print(f'AlphaVantage: ticker data not available for {ticker}')
            return pd.DataFrame({})
        elif 'TimeoutError' in str(err):
            print(f'AlphaVantage: timeout while getting {ticker}')
        else:
            print(f'AlphaVantage: {err}')

    if data is None or len(data.values()) == 0:
        print('AlphaVantage: no data for %s' % ticker)
        return pd.DataFrame({})

    prices = {}
    for key in sorted(data.keys(), key=lambda d: datetime.strptime(d, '%Y-%m-%d')):
        secondary_dic = data[key]
        date = datetime.strptime(key, '%Y-%m-%d')
        dic_with_prices(prices, ticker, date, secondary_dic['1. open'], secondary_dic['2. high'],
                        secondary_dic['3. low'], secondary_dic['4. close'], secondary_dic['5. volume'])

    frame = pd.DataFrame.from_dict(prices, orient='index', columns=['Open', 'High', 'Low', 'Close', 'Volume'])
    save_csv(base_dir, ticker, frame, 'alpha')
    time.sleep(15 if alpha_count != 0 else 0)
    alpha_count += 1
Пример #7
0
 def get_time_series(
     self,
     yahoo_ticker: str,
     start_date: date = default_start_date,
     end_date: date = date.today()
 ) -> TimeSeries:
     """
     Returns time series for given ticker in Yahoo finance format (e.g. HSBA.L)
     :param yahoo_ticker:
     :param start_date:
     :param end_date:
     :return:
     """
     ts = AlphaVantageTimeSeries(key=self.api_key, output_format='pandas')
     data, meta_data = ts.get_daily(symbol=yahoo_ticker, outputsize='full')
     data.index = to_datetime(data.index)
     data_truncated = data.truncate(before=start_date, after=end_date)
     return [
         HistoricDataPoint(time=dt.to_pydatetime(),
                           open=row['1. open'],
                           high=row['2. high'],
                           low=row['3. low'],
                           close=row['4. close'],
                           volume=row['5. volume'])
         for dt, row in data_truncated.iterrows()
     ]
Пример #8
0
def get_stock_price(df_excld):
    """
    Retrieves the daily stock price from a dataframe of stocks and their
    respective tickers

    args:
    ------
        df_excld: (pd.DataFrame) filtered dataframe of stocks containing only
                  stocks from selected industries
    Return:
    ------
        info: (list) a complete history of stocks' pricing/volume information 
        symbols: (list) stock tickers
    """

    ts = TimeSeries(os.environ['ALPHA_VANTAGE_KEY'])

    info = []
    symbols = []
    counter = 0

    for t in df_excld['Ticker']:

        if counter % 5 == 0:
            time.sleep(65)

        i, m = ts.get_daily(symbol=t, outputsize='full')
        info.append(i)
        symbols.append(m['2. Symbol'])
        counter += 1

    return info, symbols
Пример #9
0
def get_historical_data(stock):
  # Your key here
  key = os.getenv("ALPHA_VANTAGE_API_KEY")
  # Chose your output format, or default to JSON (python dict)
  ts = TimeSeries(key, output_format='pandas')
  ti = TechIndicators(key)

  # Get the data, returns a tuple
  # stock_data is a pandas dataframe, stock_meta_data is a dict
  stock_data, stock_meta_data = ts.get_daily(symbol=stock, outputsize='full')
  # stock_data, stock_meta_data = ts.get_intraday(symbol='TSLA',interval='60min', outputsize='full')

  # stock_sma is a dict, stock_meta_sma also a dict
  # stock_sma, stock_meta_sma = ti.get_sma(symbol='TSLA')

  stock_data['same_day_change'] = stock_data['4. close'] - stock_data['1. open']
  stock_data['same_day_percentage_change'] = stock_data['same_day_change'] / stock_data['1. open']

  stock_data['1_day_change'] = stock_data['4. close'].diff()
  stock_data['1_day_percentage_change'] = stock_data['4. close'].pct_change()

  # embed()


  stock_data.index = stock_data.index.astype('datetime64[ns, UTC]')
  # stock_data = stock_data.shift(1)

  # embed()

  print (stock_data)
  return stock_data
Пример #10
0
 def getDataFrameData(self):
     # Pass in personal API key, initialize Alpha Vintage time series object.  Here we choose to display the self.data using a Pandas-style
     # dataframe, though JSON is an alternative choice.
     ts = TimeSeries(key=self.alpha_key, output_format='pandas')
     # Get 1.) json object with interday self.data and 2.) json object with the call's metadata
     self.data, self.meta_data = ts.get_daily(self.name)
     return self.data, self.meta_data
Пример #11
0
    def save_data(self, dir="."):
        # Initialize time series object
        timeSeries = TimeSeries(key=self.AV_API_KEY, output_format='pandas')

        # Create directory if it doesn't exist
        if not os.path.exists(dir):
            os.mkdir(dir)

        # Save each symbol
        for symbol in self.symbols:
            try:
                # Get data
                data, meta = timeSeries.get_daily(symbol=symbol,
                                                  outputsize='full')
                # Name file
                ofile = os.path.join(
                    dir,
                    symbol + "_" + str(datetime.today().strftime('%Y-%m-%d')))
                # Save pandas data
                data.to_csv(ofile)
                # Print some info
                print("Saved data for symbol {} to {}".format(symbol, ofile))
                print("-- standing by for 15 seconds")
                time.sleep(15)
            except Exception as e:
                print("-- error: could not access/save data for {}".format(
                    symbol))
Пример #12
0
def get_data(symbol):
    print 'Getting data'
    # Technical Indicators
    ti = TechIndicators(key='4BTFICZGTPWZRRQS', output_format='pandas')
    sma, _ = ti.get_sma(symbol=symbol, interval='daily')
    wma, _ = ti.get_wma(symbol='SPX', interval='daily')
    ema, _ = ti.get_ema(symbol=symbol, interval='daily')
    macd, _ = ti.get_macd(symbol=symbol, interval='daily')
    stoch, _ = ti.get_stoch(symbol=symbol, interval='daily')
    rsi, _ = ti.get_rsi(symbol=symbol, interval='daily')
    adx, _ = ti.get_adx(symbol=symbol, interval='daily')
    cci, _ = ti.get_cci(symbol=symbol, interval='daily')
    aroon, _ = ti.get_aroon(symbol=symbol, interval='daily')
    bbands, _ = ti.get_bbands(symbol='SPX', interval='daily')
    ad, _ = ti.get_ad(symbol='SPX', interval='daily')
    obv, _ = ti.get_obv(symbol='SPX', interval='daily')
    mom, _ = ti.get_mom(symbol='SPX', interval='daily')
    willr, _ = ti.get_willr(symbol='SPX', interval='daily')
    tech_ind = pd.concat([sma, ema, macd, stoch, rsi, adx, cci, aroon, bbands, ad, obv, wma, mom, willr], axis=1)

    print 'Getting time series'
    ts = TimeSeries(key='4BTFICZGTPWZRRQS', output_format='pandas')
    close = ts.get_daily(symbol=symbol, outputsize='full')[0].rename(columns={'4. close': 'close'})['close']
    direction = (close > close.shift()).astype(int)
    target = direction.shift(-1).fillna(0).astype(int)
    target.name = 'target'

    data = pd.concat([tech_ind, close, target], axis=1)

    return data
Пример #13
0
def dailyOnClose(symbol):
    ts = TimeSeries(key=KEY, output_format='pandas')
    try:
        dataframe,meta_data = ts.get_daily(symbol,outputsize='full')
        dataframe = dataframe.rename(columns={
        '1. open':'Open',
        '2. high':'High',
        '3. low':'Low',
        '4. close':'Close',
        '5. volume':'Volume'
    })
        dataframe = dataframe[['Open','High','Low','Close','Volume']]
        dataframe = dataframe.dropna()
        print('DATA INSIGHT \n')
        print(dataframe.head())
        print(dataframe.shape)
        print('MEAN CLOSE: ',dataframe['Close'].mean())
        print('MAX CLOSE: ',dataframe['Close'].max())
        print('MIN CLOSE: ',dataframe['Close'].min())
        print('/n')
        print('PREPROCESSING...')
        close_price = dataframe.reset_index()['Close']
        close_price = scaler.fit_transform(np.array(close_price).reshape(-1,1))
        train_size = int(len(close_price)*0.70)
        test_size = int(len(close_price*0.30))
        train_data = close_price[0:train_size,:]
        test_data = close_price[train_size:len(close_price),:1]
        return train_data,test_data
    except ValueError:
        print('Try a different scrip')
Пример #14
0
class ApiConnector:
    """
    Responsability: To connecto to the alpha vantage api.
    """

    def __init__(self, api_key):
        """Api objects instanciated with api_key"""
        self.key = api_key
        self.time_app = TimeSeries(api_key)
        # can change the output_format to json which is default
        self.tech_app = TechIndicators(api_key, output_format="json")

    def get_macd(self, stock, time_interval, fastperiod, slowperiod, signalperiod):
        """
        Returns macd_signal, macd, macd_hist
        Interval: '1min', '5min', '15min', '30min', '60min', 'daily',
            'weekly', 'monthly'
        """
        return self.tech_app.get_macd(stock, interval=time_interval, fastperiod=fastperiod, slowperiod=slowperiod, signalperiod=signalperiod, series_type="close")

    def get_days(self, stock):
        """Returns timeseries with close-value each day (20 years back)"""
        return self.time_app.get_daily(stock)

    def get_intraday(self, stock):
        """"interval: '1min', '5min', '15min', '30min', '60min'"""
        return self.time_app.get_intraday(stock, '1min', outputsize="full")
Пример #15
0
def add(stock_name, start_date):
    ts = TimeSeries(
        key=api_key, output_format='pandas', indexing_type='integer'
    )  #this is some rando's wrapper, eventually want to replace
    data = ts.get_daily(symbol=stock_name)  #this is the api call
    df = data[
        0]  #data returns a dataframe and metadata, dataframe is [0] and metadata is [1]
    df['stock_name'] = stock_name  #create a column called stock_name that is a fixed value
    close_price = df[['date', 'stock_name', '4. close']]
    close_price = close_price[(close_price['date'] >= start_date)]
    st_records = list(close_price.itertuples(index=False, name=None))
    sp_records = (stock_name, start_date, 'null')
    print("\n")
    print("Loading {} into the stock_tracker database at {}".format(
        stock_name, start_date))
    print("\n")
    c.executemany('INSERT INTO stock_tracker VALUES (?,?,?)', st_records)
    print("Loading of {} into stock_tracker complete".format(stock_name))
    print("\n")
    print("Loading {} into the stock_portfolio database at {}".format(
        stock_name, start_date))
    print("\n")
    c.execute('INSERT INTO stock_portfolio VALUES (?,?,?)', sp_records)
    print("Loading of {} into stock_portfolio complete".format(stock_name))
    print("\n")
Пример #16
0
def query():
    ts = TimeSeries(key='G89M0HECMYPKA46T', output_format='pandas')
    data, meta_data = ts.get_daily('TSLA', outputsize='full')
    pprint(data)  # prints the most recent 100 points
    data['4. close'].plot()
    plt.title('Daily TSLA')
    plt.show()
Пример #17
0
 def __init__(self, id):
     self.id = id
     key = 'YNER5OQ3FMOTFGFM'
     ts = TimeSeries(key)
     self.total = ts.get_daily(self.id, outputsize='full')[0]
     self.time = list(self.total.keys())[-1]
     self.fund = self.time.split('-')
Пример #18
0
def export_data(request, api_detail, parent_symbol, symbol, data_type):
    # print('Request Data: ', api_detail, parent_symbol, symbol, data_type)
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment;filename=av_data.csv'

    # opts = queryset.model._meta
    field_names = ['Time Series', 'Open', 'High', 'Low', 'Close', 'Volume']

    writer = csv.writer(response)
    writer.writerow(field_names)

    if api_detail == '1':
        ts = TimeSeries(key=settings.API_KEY, output_format='json')
        if data_type == 'Intraday':
            api_data, meta_data = ts.get_intraday(symbol=symbol,
                                                  interval='1min',
                                                  outputsize='full')
        elif data_type == 'Weekly':
            api_data, meta_data = ts.get_weekly(symbol=symbol)
        elif data_type == 'Daily':
            api_data, meta_data = ts.get_daily(symbol=symbol)
        else:
            api_data, meta_data = ts.get_monthly(symbol=symbol)

    for key, value in api_data.items():
        csv_list = [key]
        for k, v in value.items():
            csv_list.append(v)
        writer.writerow(csv_list)

    return response
Пример #19
0
def show_stocks(message):
    try:
        ts = TimeSeries(key='ZBRM5PCHPIYQV8BY', output_format='pandas')
        x = 0
        for x in items:
            data, meta_data = ts.get_intraday(x,
                                              interval='1min',
                                              outputsize='full')
            dat, meta_dat = ts.get_daily(x, outputsize='full')
            now = pd.DataFrame(data.tail(1))
            now1 = now['4. close']
            nw = str(now1)
            nw1 = nw[28:34]
            nw2 = float(nw1)
            openn = pd.DataFrame(dat.tail(2))
            openn1 = openn['4. close']
            op = str(openn1)
            op1 = op[19:23]
            op2 = float(op1)
            if nw2 >= op2:
                proc = round(100 - ((op2 / nw2) * 100), 2)
                proc1 = str(proc)
                bot.send_message(message.chat.id,
                                 x + " - $" + nw1 + ' +' + proc1 + '%')
            elif nw2 < op2:
                proc = round(100 - ((nw2 / op2) * 100), 2)
                proc1 = str(proc)
                bot.send_message(message.chat.id,
                                 x + " - $" + nw1 + ' -' + proc1 + '%')
    except Exception as e:
        markup = types.ReplyKeyboardMarkup()
        markup.row('get back')
        bot.send_message(message.chat.id,
                         "ooops... something got wrong",
                         reply_markup=markup)
Пример #20
0
def get_data_from_web(tickers, start, end, source = 'yahoo', redownload = False):
    
    if not os.path.exists(source):
        os.makedirs(source)
        
    yf.pdr_override() # <== that's all it takes :-)
    apiKey = '9ODDY4H8J5P847TA'
    filepath = source + '/{}.csv'
    for ticker in tickers:
        # just in case your connection breaks, we'd like to save our progress!        
       if (redownload | (not os.path.exists(filepath.format(ticker)))):
           try:
#            df = web.DataReader(ticker, source, start, end)
                
                if (source == 'yahoo'):                    
                    df = pdr.get_data_yahoo(ticker, start=start, end=end,  as_panel = False)                   
                    df.to_csv(filepath.format(ticker))
                if (source == 'alpha'):                    
                    ts = TimeSeries(key=apiKey, output_format='pandas')
                    df, _ = ts.get_daily(symbol=ticker, outputsize='full')                    
                    df.to_csv(filepath.format(ticker))
                    
           except Exception as e:
                print(str(e))
       else:
            print('Already have {}'.format(ticker))
Пример #21
0
def stockchart_3month(symbol1):

    title = '3 Months'
    ts = TimeSeries(key='QBGZM8IV1P2X2VJQ', output_format='pandas')
    data1, meta_data = ts.get_daily(symbol=symbol1, outputsize='compact')

    return graph(symbol1, data1, title)
Пример #22
0
    def initiate(self):
        """
        Produces a dataframe from the selected security's price history. No 
        parameteres are needed to initialize the dataframe. Necessary first 
        step for future data wrangling. 

        Parameters
        ----------
        None
        """
        # API Object 
        ts = TimeSeries(key=self.alpha_vantage_key, 
                        output_format='pandas')
        # API Call
        data, meta_data = ts.get_daily(symbol=self.symbol, 
                                       outputsize=self.outputsize)

        # Print Statement
        print('###################################################################','\n',
        'Ticker: ' , meta_data['2. Symbol'], '\n',
        'Last Refreshed: ', meta_data['3. Last Refreshed'], '\n',
        'Data Retrieved: ', meta_data['1. Information'],'\n',
        '###################################################################')

        # Produce better column names
        data = data.rename(columns={
                '1. open'  : self.symbol+' open', 
                '2. high'  : self.symbol+' high', 
                '3. low'   : self.symbol+' low', 
                '4. close' : self.symbol+' close', 
                '5. volume': self.symbol+' volume'
        }
    )
        return data
Пример #23
0
def get_data_from_api(stock_list):
    """
    Sources stock market data from the AlphaVantage API for a given list of stocks.

    Parameters: 
        stock_list (list): List of stock symbols specifying desired stocks

    Returns:
        stock_dict (dict): Dictionary containing daily stock prices indexed by stock symbol

    """

    # Get time series data, returns a tuple (data, meta_data)
    # First entry is a pandas dataframe containing data, second entry is a dict containing meta_data
    print("Sourcing stock market data from AlphaVantage API...")
    key = 'RY4QOCLLB7ZIVZ8M'  # your API key here
    ts = TimeSeries(key, output_format='pandas'
                    )  # choose output format, defaults to JSON (python dict)
    ti = TechIndicators(key)

    # Create dictionary of form stock_symbol: (data, meta_data)
    stock_dict = {}
    for stock in stock_list:
        print(stock)
        stock_dict[stock] = ts.get_daily(symbol=stock)
    return stock_dict
Пример #24
0
def get_data(time, tick):
    ts = TimeSeries(key='4H9RHI4W5JZIHA3Z', output_format='pandas')
    if time == constants.time['1d']:
        data, meta_data = ts.get_intraday(symbol=tick,
                                          interval='5min',
                                          outputsize='compact')
    elif time == constants.time['5d']:
        data, meta_data = ts.get_intraday(symbol=tick,
                                          interval='30min',
                                          outputsize='compact')
    elif time == constants.time['1m']:
        data, meta_data = ts.get_daily(symbol=tick, outputsize='compact')
    else:
        data, meta_data = ts.get_daily(symbol=tick, outputsize='full')
    data = data[::-1]
    return data, meta_data
Пример #25
0
def alpha_vantage_api():
	API_Key='KY74URGMWMKH6FJ8'
	ts = TimeSeries (key=API_Key, output_format = "pandas")
	data_daily, meta_data = ts.get_daily(symbol=stock_ticker, outputsize ='compact')
	        # data_daily['column name'][row number]
	daterow=meta_data['3. Last Refreshed'][i]
	data_daily_lastClosingPrice = data_daily['4. close'][i]
Пример #26
0
def get_company_status(company):
    try:
        ts = TimeSeries(key=os.environ['ALPHA_KEY'])
        data, meta_data = ts.get_daily(company + '.SA')
        today = datetime.strftime(datetime.now(tz=pytz.timezone("America/Sao_Paulo")), '%Y-%m-%d')

        if date.today().weekday() == 0:
            last_day = datetime.strftime(datetime.now(tz=pytz.timezone("America/Sao_Paulo")) - timedelta(3), '%Y-%m-%d')
        else:
            last_day = datetime.strftime(datetime.now(tz=pytz.timezone("America/Sao_Paulo")) - timedelta(1), '%Y-%m-%d')
        
        response = {
            'valid': 0,
            'cp': float("{0:.2f}".format(((float(data[today]['4. close']) * 100 / float(data[last_day]['4. close'])) - 100.0))),
            'op': float(data[today]['1. open']),
            'hi': float(data[today]['2. high']),
            'lo': float(data[today]['3. low']),
            'l': float(data[today]['4. close'])
        }

    except:
        response = {
            'valid': 1
        }

    return response
Пример #27
0
def visualization(key, s):
    """
        This function is used to create the stock chart visualization. It receives the API key and the ticker
        as arguments and then produces the plot as a result.

        @param: this function has two parameters: the first is the API key that is a string. The second is the stock ticker
                which is a string and has already been validated. 

    """
    #this was adopted from the alpha vantage customer service website/ github
    #https://medium.com/alpha-vantage/get-started-with-alpha-vantage-data-619a70c7f33a
    key = ALPHA_VANTAGE_API_KEY
    ts = TimeSeries(key, output_format='pandas')
    ti = TechIndicators(key)

    # Get the data, returns a tuple
    # stock_data is a pandas dataframe
    # note that the API is requested one more time
    stock_data, stock_meta_data = ts.get_daily(symbol=s)

    # Visualization
    figure(num=None, figsize=(15, 6), dpi=80, facecolor='w', edgecolor='k')
    stock_data['4. close'].plot()
    plt.tight_layout()
    plt.grid()
    plt.show()
Пример #28
0
    def collect_data(self, asset='GOOGL', interval='1min', output='compact'):
        ts = TimeSeries(key=self.key, output_format='pandas')
        if interval in ['1min', '1min', '5min', '15min', '30min', '60min']:
            data, meta_data = ts.get_intraday(
                asset,
                interval=output,
                outputsize=output
            )
        elif interval in ['daily']:
            data, meta_data = ts.get_daily(
                asset,
                outputsize=output
            )
        else:
            raise ValueError("Please use an appropriate interval in '1min', \
                              '1min', '5min', '15min', '30min', '60min' or \
                              'daily' ")

        series = (
            data
                .reset_index()[['date', '2. high']]
                .rename({"2. high": "t_0"}, axis=1)
                .drop(['date'], axis=1)
        )
        return series, meta_data
Пример #29
0
    def add_securities(self, symbols, primary_df):
        # TODO ASSERT symbols is a list:

        ts = TimeSeries(key=self.alpha_vantage_key, output_format='pandas')

        i_count = 0

        for symbol in symbols:

            data, meta_data = ts.get_daily(symbol=symbol,
                                           outputsize=self.outputsize)

            print(meta_data)

            data = data.rename(
                columns={
                    '1. open': symbol + ' open',
                    '2. high': symbol + ' high',
                    '3. low': symbol + ' low',
                    '4. close': symbol + ' close',
                    '5. volume': symbol + ' volume'
                })
            if i_count == 0:
                final_df = primary_df.merge(data, how='inner', on='date')
            else:
                final_df = final_df.merge(data, how='inner', on='date')

            i_count += 1

        return final_df
Пример #30
0
def get_close_price(symbol, startDate='', endDate=''):
    '''
    # alpha vantage每分钟只能提取五只股票数据,国内股票用tushare替代
    if symbol.split('.')[1].strip().upper() in ['SS','SZ']:
        start_date = '2019-12-31' if startDate == '' else startDate
        end_date = time.strftime("%Y-%m-%d") if endDate == '' else endDate
        start_date = start_date.replace('-', '')
        end_date = end_date.replace('-', '')
        symbolCode = symbol.replace(".SS", ".SH")
        #local variable 'ts' referenced before assignment
        tushare.set_token(TUSHARE_KEY)
        data = tushare.pro_bar(ts_code=symbolCode, start_date=start_date, end_date=end_date)
        close = data.loc[:, ('trade_date','ts_code','close')]
        close.rename(columns={'trade_date':'Date','ts_code':'SymbolCode','close':'Close'},inplace=True)
        close['Date'] = close.apply(lambda x: x['Date'][0:4]+'-'+x['Date'][4:6]+'-'+x['Date'][6:], axis=1)
        close['SymbolCode'] = symbol
    else:
    '''
    ts = TimeSeries(key=ALPHA_VANTAGE_KEY, output_format='pandas', indexing_type='date')
    data, meta_data = ts.get_daily(symbol)
    data.reset_index(inplace=True)
    close = data.loc[:, ('date', '4. close')]
    close.rename(columns={'date': 'Date', '4. close': 'Close'}, inplace=True)
    close.insert(1, 'SymbolCode', symbol)
    close['Date'] = close.apply(lambda x: x['Date'].strftime('%Y-%m-%d'), axis=1)

    return close