Esempio n. 1
0
def run():
    key = '1TKWNTNJE9BNAP7K'
    ts = TimeSeries(key)
    daily_peloton, daily_meta = ts.get_daily(symbol='PTON')
    monthly_peloton, monthly_meta = ts.get_monthly(symbol='PTON')

    create_file()

    today = datetime.today().strftime('%Y-%m-%d')
    daily_stock_data = daily_peloton.get(today)
    highest_price = 0
    for month in monthly_peloton:
        month_stock_data = monthly_peloton.get(month)
        high = month_stock_data.get('2. high')
        if highest_price < float(high):
            highest_price = float(high)
    if daily_stock_data:
        close = daily_stock_data.get('4. close')[:-2]
        high = daily_stock_data.get('2. high')[:-2]
        open_amt = daily_stock_data.get('1. open')[:-2]
        low = daily_stock_data.get('3. low')[:-2]
        content = "Peloton stock for %s:" % today + "\n"
        content += "\tOpened at: $" + open_amt + "\n"
        content += "\tClosed at: $" + close + "\n"
        content += "\tLow: $" + low + "\n"
        content += "\tHigh: $" + high + "\n"
        content += "Historical High: $" + str(highest_price) + "\n"

        content += "\n\n"
        if float(close) > 50.0:
            content += "SO RICH"
        else:
            content += "Not rich yet =("

        write_to_file(content)
Esempio n. 2
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
Esempio n. 3
0
def Time_series(name, time, output, type):
    #ts = TimeSeries(key=API_key, output_format='pandas')
    ts = TimeSeries(key=API_key)
    if (type == 'Intraday'):
        data, meta_data = ts.get_intraday(symbol=name,
                                          interval=time,
                                          outputsize=output)
        #print_time_series(data,name,time,type)
        return data
    elif (type == 'Day Adjusted'):
        data, meta_data = ts.get_daily_adjusted(symbol=name, outputsize=output)
        print_time_series(data, name, time, type)
    elif (type == 'Weekly'):
        data, meta_data = ts.get_weekly(symbol=name)
        print_time_series(data, name, time, type)
    elif (type == 'Weekly Adjusted'):
        data, meta_data = ts.get_weekly_adjusted(symbol=name)
        print_time_series(data, name, time, type)
    elif (type == 'Monthly'):
        data, meta_data = ts.get_monthly(symbol=name)
        #print_time_series(data,name,time,type)
        description(data, name, time, type)
    elif (type == 'Monthly Adjusted'):
        data, meta_data = ts.get_monthly_adjusted(symbol=name)
        print_time_series(data, name, time, type)
Esempio n. 4
0
def getAVdata(stock, interval, akey):
    while True:
        try:
            ts = TimeSeries(key=alphakeys[akey], output_format='pandas')
            if interval == 'daily':
                tdata, meta_data = ts.get_daily(symbol=stock,
                                                outputsize='full')
            elif interval == 'weekly':
                tdata, meta_data = ts.get_weekly(symbol=stock,
                                                 outputsize='full')
            elif interval == 'monthly':
                tdata, meta_data = ts.get_monthly(symbol=stock,
                                                  outputsize='full')
            else:
                tdata, meta_data = ts.get_intraday(symbol=stock,
                                                   interval=interval,
                                                   outputsize='full')
            break
        except Exception as e:
            print('Exception!!!: Stock %s   Alphakey: %s  Interval: %s' %
                  (stock, alphakeys[akey], interval))
            akey = (akey + 1) % len(alphakeys)
            print(e, '\n')

            continue
    print(stock, alphakeys[akey], interval)
    tdata = tdata.rename(columns={'1. open': 'Open', '2. high': 'High', '3. low': 'Low', \
                                  '4. close': 'Close', '5. volume': 'Volume'})
    tdata = tdata.dropna()
    return tdata, akey
Esempio n. 5
0
def monthlyPivotInfo(symbol):
    ts = TimeSeries(key=key, output_format='pandas')
    data, meta_data = ts.get_monthly(symbol=symbol)
    high = data.iloc[
        1, 1]  # ['1. open', '2. high', '3. low', '4. close', '5. volume']
    low = data.iloc[1, 2]
    close = data.iloc[1, 3]
    pivotPointCalculation = (high + low + close) / 3
    pivotPoint = round(pivotPointCalculation, 2)
    print(pivotPoint)
    return pivotPoint
Esempio n. 6
0
 def pull_tick_monthly(self, tick, adjusted=True):
     self.tracker.wait()
     ts = TimeSeries(key=self.key, output_format='pandas')
     if adjusted:
         df, meta_data = ts.get_monthly_adjusted(tick)
     else:
         df, meta_data = ts.get_monthly(tick)
     df = df.reset_index()
     df['ticker'] = tick
     self.tracker.update(1)
     return df
Esempio n. 7
0
def Data(Ticker):
    API_key = os.environ['key']
    allData = TimeSeries(API_key, output_format='pandas')
    data, meta_data= allData.get_monthly(Ticker)
    data.drop(['1. open', '2. high','3. low'], axis=1, inplace=True)
    data.rename(columns={'4. close' : 'price', '5. volume': 'volume'}, inplace=True)
    data.reset_index(level=data.index.names, inplace=True)
    data = data.sort_index(ascending=False)
    data['year'] = data['date'].dt.year
    data['date'] = data['date'].dt.strftime('%b-%Y')
    return data
Esempio n. 8
0
    def stockData(self):
        ts = TimeSeries(key=self.apiKey, output_format='pandas')
        if (self.timePeriod == "interday"):
            data, meta_data = ts.get_intraday(symbol=self.stockName)
        elif (self.timePeriod == "daily"):
            data, meta_data = ts.get_daily(symbol=self.stockName)
        elif (self.timePeriod == "weekly"):
            data, meta_data = ts.get_weekly(symbol=self.stockName)
        elif (self.timePeriod == "monthly"):
            data, meta_data = ts.get_monthly(symbol=self.stockName)

        return data
Esempio n. 9
0
def get_data_monthly(symbol, savingtoCsv=True):
    # gets data over of a week
    # loading necessary modules
    from alpha_vantage.timeseries import TimeSeries
    # getting api key
    API_KEY, waiting_times = api_key_finder()
    # creating object
    ts = TimeSeries(key=API_KEY, output_format='pandas')
    # reading data into pandas
    data, meta_data = ts.get_monthly(symbol=symbol)
    # writing data to database and csv
    write_to_database(data, 'Monthly', symbol, 'monthly', savingtoCsv)
    return data, meta_data
Esempio n. 10
0
 def Feed_Monthly(self):
     collectionname = 'Monthly'
     for com in self.Company:
         try:
             ts = TimeSeries(key=self.APIKEYS[3], output_format='pandas')
             data, meta_data = ts.get_monthly(com)
             data = pd.DataFrame(data)
             data.reset_index(inplace=True)
             mongodb.UpdateValue(collectionname, com, data.to_dict(orient='list'))
             # mongodb.WriteValue(collectionname, com, data.to_dict(orient='list'))
             # print(data)
         except Exception as e:
             print('Company Ignore due to high service call' + '\nError : ' + str(e))
Esempio n. 11
0
def stockchart_5year(symbol1, symbol2):
    title = '5 Years'
    ts = TimeSeries(key='QBGZM8IV1P2X2VJQ', output_format='pandas')
    data1, meta_data = ts.get_monthly(symbol=symbol1)
    data2, meta_data = ts.get_monthly(symbol=symbol2)

    newdata1 = data1.drop(data1.index[0:len(data1.index) - 62])
    newdata2 = data2.drop(data2.index[0:len(data2.index) - 62])

    newdata1 = modify_data(newdata1)
    newdata2 = modify_data(newdata2)

    return graph(symbol1, symbol2, newdata1, newdata2, meta_data, ts, title)
Esempio n. 12
0
def ogmonthly(name, k):
    key = k
    ts = TimeSeries(key, output_format='pandas')
    #ti = TechIndicators(key)

    #sym = input('Enter stock symbol: ')
    global datam
    sym = name
    datam, meta_data = ts.get_monthly(symbol=sym)
    print("model for month of data")
    #print(data)
    fn = name + ".month.csv"
    with open(fn, 'w') as ff:
        datam.to_csv(ff)
Esempio n. 13
0
def TimeSeriesMonthly(request, pk, format=None):
    try:
        symbol = Stock.objects.get(pk=pk).symbol
    except symbol.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        from alpha_vantage.timeseries import TimeSeries
        ts = TimeSeries(key=key)
        try:
            data, meta_data = ts.get_monthly(symbol=symbol)
        except Exception:
            return Response(status=status.HTTP_404_NOT_FOUND)
        return Response(data)
Esempio n. 14
0
    def output(self):
        """
        Retrieve stock data
        
        @return TableWrapper of stock data
        """

        stock_symbols = self.ap_paramList[0]()

        timeseries_retriever = TimeSeries(key=DataFetcher.getConfigItem(
            'stocks', 'api_key'),
                                          output_format='pandas',
                                          indexing_type='date')

        data_dict = OrderedDict()
        metadata_dict = OrderedDict()

        for symbol in stock_symbols:

            # Extract data
            if self.data_type == 'daily':
                data, metadata = timeseries_retriever.get_daily(
                    symbol, outputsize='full')
            elif self.data_type == 'daily_adjusted':
                data, metadata = timeseries_retriever.get_daily_adjusted(
                    symbol, outputsize='full')
            elif self.data_type == 'monthly':
                data, metadata = timeseries_retriever.get_monthly(symbol)
            elif self.data_type == 'monthly_adjusted':
                data, metadata = timeseries_retriever.get_monthly_adjusted(
                    symbol)
            elif self.data_type == 'weekly':
                data, metadata = timeseries_retriever.get_weekly(symbol)
            elif self.data_type == 'weekly_adjusted':
                data, metadata = timeseries_retriever.get_weekly_adjusted(
                    symbol)
            elif self.data_type == 'intraday':
                data, metadata = timeseries_retriever.get_weekly_adjusted(
                    symbol, self.interval, outputsize='full')
            # Convert index to pandas datetime
            if self.data_type == 'intraday':
                data.index = pd.to_datetime(data.index).tz_localize(
                    metadata['6. Time Zone'])
            else:
                data.index = pd.to_datetime(data.index)

            data_dict[symbol] = data[self.start_date:self.end_date]
            metadata_dict[symbol] = metadata

        return TableWrapper(data_dict, meta_data=metadata_dict)
Esempio n. 15
0
def home():
    form = Submissionform()
    if form.validate_on_submit():
        flash('Ticker Submited :  {}'.format(form.text.data))
        try:
            if form.submit.data == True:
                ts = TimeSeries(key='FSFW64CYZLUB5O4C', output_format='pandas')
                data, meta_data = ts.get_intraday(symbol=form.text.data,
                                                  interval='1min',
                                                  outputsize='full')
                data = data.reindex(index=data.index[::-1])
                values = data['4. close']
                labels = list(data.index)
                legend = form.text.data
                return render_template('chart.html',
                                       values=values,
                                       labels=labels,
                                       legend=legend)
            if form.monthly.data == True:
                ts = TimeSeries(key='FSFW64CYZLUB5O4C', output_format='pandas')
                data, meta_data = ts.get_monthly(symbol=form.text.data)
                print(data)
                data = data.reindex(index=data.index[::-1])
                values = data['4. close']
                labels = list(data.index)
                legend = form.text.data
                return render_template('chart.html',
                                       values=values,
                                       labels=labels,
                                       legend=legend)
            if form.download.data == True:
                ts = TimeSeries(key='FSFW64CYZLUB5O4C', output_format='pandas')
                data, meta_data = ts.get_intraday(symbol=form.text.data,
                                                  interval='1min',
                                                  outputsize='full')

                csv = data.to_csv()
                #print(csv)
                return Response(csv,
                                mimetype="text/csv",
                                headers={
                                    "Content-disposition":
                                    "attachment; filename=data.csv"
                                })
        except:
            flash('Enter Valid Ticker!')
    else:
        flash_errors(form)
    return render_template('home.html', form=form)
Esempio n. 16
0
    def getTimeSeries(self,
                      function,
                      symbols,
                      interval='1min',
                      outputsize="compact",
                      datatype="pandas"):
        #check if datatype is valid and create instance of time series
        if datatype != 'pandas' and datatype != 'json' and datatype != 'csv':
            print(
                "Invalid Datatype: Vaible options are 'pandas', 'json', 'csv'")
            return -1
        else:
            ts = TimeSeries(key=self.key, output_format=datatype)

        #check if outputsize is a valid input
        if outputsize != 'compact' and outputsize != 'full':
            print(
                "Invalide Output Size: Viable options are 'compact' and 'full'"
            )
            return -1

        #determine what time series the user wants and build request
        if function == 'intraday':
            valid_intervals = ['1min', '5min', '15min', '30min', '60min']
            if interval not in valid_intervals:
                print(
                    "Invalid Interval: Viable options are '1min', '5min', '15min', '30min', '60min'"
                )
                return -1
            else:
                data, meta_data = ts.get_intraday(symbol=symbols,
                                                  interval=interval,
                                                  outputsize=outputsize)
        elif function == 'daily':
            data, meta_data = ts.get_daily(symbol=symbols,
                                           outputsize=outputsize)
        elif function == 'weekly':
            data, meta_data = ts.get_weekly(symbol=symbols)
        elif function == 'monthly':
            data, meta_data = ts.get_monthly(symbol=symbols)
        else:
            print(
                "Invalid Function: Viable options are 'intraday', 'daily', 'weekly', and 'monthly'"
            )
            return -1

        return data
Esempio n. 17
0
    def get_monthly_price(self):
        '''
        object -> None
        This method gets a json file with prices
        '''
        ts = TimeSeries(key='WYXA08Z6LYUO5HL1', retries=2)
        # Get json object with the intraday data and another with  the call's metadata
        price = ts.get_monthly(self.name)[0]

        self.history = {}
        for i in price:

            if len(self.history) < 25:
                self.history[i] = price[i]

            else:
                break
Esempio n. 18
0
def getData(symbol, timeSeries, chartType, startDate, endDate):

    ts = TimeSeries(key=API_KEY, output_format='pandas')
    if timeSeries == '1':
        data, meta_data = ts.get_intraday(symbol=symbol,
                                          interval='60min',
                                          outputsize='full')
        f = 'H'
    if timeSeries == '2':
        data, meta_data = ts.get_daily(symbol=symbol, outputsize='compact')
        f = 'D'
    if timeSeries == '3':
        data, meta_data = ts.get_weekly(symbol=symbol)
        f = 'W'
    if timeSeries == '4':
        data, meta_data = ts.get_monthly(symbol=symbol)
        f = 'M'

    data_date_changed = data[endDate:startDate]

    if chartType == "1":
        line_chart = pygal.Bar(x_label_rotation=20, width=1000, height=400)
        line_chart.title = 'Stock Data for {}:  {} to {}'.format(
            symbol, startDate, endDate)
        labels = data_date_changed.index.to_list()
        line_chart.x_labels = reversed(labels)
        line_chart.add("Open", data_date_changed['1. open'])
        line_chart.add("High", data_date_changed['2. high'])
        line_chart.add("Low", data_date_changed['3. low'])
        line_chart.add("Close", data_date_changed['4. close'])
        line_chart.render_in_browser()

    if chartType == "2":
        line_chart = pygal.Line(x_label_rotation=20, spacing=80)
        line_chart.title = 'Stock Data for {}: {} to {}'.format(
            symbol, startDate, endDate)
        labels = data_date_changed.index.to_list()
        line_chart.x_labels = reversed(labels)
        line_chart.add("Open", data_date_changed['1. open'])
        line_chart.add("High", data_date_changed['2. high'])
        line_chart.add("Low", data_date_changed['3. low'])
        line_chart.add("Close", data_date_changed['4. close'])
        line_chart.render_in_browser()
Esempio n. 19
0
def load_data_history(ticker='SPY', freq='15min', start='2014', end='2016'):
    """ Loads data from Yahoo. After loading it renames columns to shorter
    format, which is what Backtest expects.

    Set `adjust close` to True to correct all fields with with divident info
    provided by Yahoo via Adj Close field.

    Defaults are in place for convenience. """

    if isinstance(ticker, list):
        return pd.Panel({
            t: load_data_history(ticker=t,
                                 start=start,
                                 adjust_close=adjust_close)
            for t in ticker
        })

    ts = TimeSeries(key='8YLDYU6Z9IAZNIS4')
    if freq == 'daily':
        data, meta_data = ts.get_daily(ticker, outputsize='full')
    elif freq == 'weekly':
        data, meta_data = ts.get_weekly(ticker, outputsize='full')
    elif freq == 'monthly':
        data, meta_data = ts.get_monthly(ticker, outputsize='full')
    else:
        data, meta_data = ts.get_intraday(
            ticker, interval=freq,
            outputsize='full')  #supported 1min, 15min, 30min, 60min

    #r = data['Close']
    ohlc_cols = ['Open', 'High', 'Low', 'Close']
    #data[ohlc_cols] = data[ohlc_cols].mul(r, axis=0)
    data = data.rename(
        columns={
            'Open': 'O',
            'High': 'H',
            'Low': 'L',
            'Close': 'C',
            'Adj Close': 'AC',
            'Volume': 'V'
        })
    return data
Esempio n. 20
0
def get_historical_data(key, time_slice, symbol):
    """Wrapper function to source historical EOD stock data

    Args:
        key (str): alphavantage api key
        time_slice (str): Aggregate level to fetch. Options are:
                - daily
                - weekly
                - monthly
        symbol (str): Symbol used, including the exchange

    Returns:
        DataFrame: EOD dataframe
    """

    # Instantiate Session
    ts = TimeSeries(key=key, output_format="pandas", indexing_type="integer")

    # Retrieve Data
    if time_slice == "daily":
        df, metadata = ts.get_daily(symbol, outputsize="full")
    elif time_slice == "weekly":
        df, metadata = ts.get_weekly(symbol)
    elif time_slice == "monthly":
        df, metadata = ts.get_monthly(symbol)

    # Replace 0's with NA's because they're almost certainly false
    df.replace(0, np.nan, inplace=True)

    # Fix crappy column header that contain numbers & periods
    df.columns = [
        remove_numbers(x).replace(". ", "") for x in df.columns.tolist()
    ]

    # Fix Date type
    df["date"] = pd.to_datetime(df["date"])

    return df
Esempio n. 21
0
class AlphaVantage:

    def __init__(self, last_date = None):
        self.key = config.get_alphavantage_key()
        self.last_date = last_date
        self.ts = TimeSeries(key=self.key, retries=5, output_format='pandas', indexing_type='date')

    def compact_quotes(self, sym):
        try: 
            df, m = self.ts.get_daily(sym, outputsize='compact')   
        except:
            print 'Compact quote get caused exception'
            return None

        if df is not None:
            df = df.rename(columns = {'1. open': 'open', '2. high': 'high', '3. low': 'low', '4. close': 'close', '5. volume': 'volume'})
            df = df[['open', 'high', 'low', 'close', 'volume']] 
        return df

    def full_quotes(self, sym):
        try: 
            df, m = self.ts.get_daily(sym, outputsize='full')   
        except:
            print 'Full quote get caused exception'
            return None

        if df is not None:
            df = df.rename(columns = {'1. open': 'open', '2. high': 'high', '3. low': 'low', '4. close': 'close', '5. volume': 'volume'})
            df = df[['open', 'high', 'low', 'close', 'volume']] 
        return df

    def compact_quotes_intraday(self, sym):
        try: 
            df, m = self.ts.get_intraday(sym, interval='30min', outputsize='compact')
        except:
            print 'Compact quote intraday get caused exception'
            return None

        if df is not None:
            df = df.rename(columns = {'1. open': 'open', '2. high': 'high', '3. low': 'low', '4. close': 'close', '5. volume': 'volume'})
            df = df[['open', 'high', 'low', 'close', 'volume']]
        return df

    def full_quotes_intraday(self, sym):
        try: 
            df, m = self.ts.get_intraday(sym, interval='30min', outputsize='full')
        except:
            print 'Full quote intraday get caused exception'
            return None

        if df is not None:
            df = df.rename(columns = {'1. open': 'open', '2. high': 'high', '3. low': 'low', '4. close': 'close', '5. volume': 'volume'})
            df = df[['open', 'high', 'low', 'close', 'volume']]
        return df

    def quotes_weekly(self, sym):
        try: 
            df, m = self.ts.get_weekly(sym)
        except:
            print 'Weekly quote get caused exception'
            return None

        if df is not None:
            df = df.rename(columns = {'1. open': 'open', '2. high': 'high', '3. low': 'low', '4. close': 'close', '5. volume': 'volume'})
            df = df[['open', 'high', 'low', 'close', 'volume']]
        return df

    def quotes_monthly(self, sym):
        try: 
            df, m = self.ts.get_monthly(sym)
        except:
            print 'Weekly quote get caused exception'
            return None

        if df is not None:
            df = df.rename(columns = {'1. open': 'open', '2. high': 'high', '3. low': 'low', '4. close': 'close', '5. volume': 'volume'})
            df = df[['open', 'high', 'low', 'close', 'volume']]
        return df
Esempio n. 22
0
    def stockIndicators(self):
        ti = TechIndicators(key=self.apiKey, output_format='pandas')

        if (self.stockIndi == "sma"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_sma(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "ema"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_ema(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "vwap"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_vwap(symbol=self.stockName,
                                                  time_period=30)

        elif (self.stockIndi == "macd"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_macd(symbol=self.stockName,
                                                  time_period=30)

        elif (self.stockIndi == "obv"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_obv(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "ad"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_ad(symbol=self.stockName,
                                                time_period=30)

        elif (self.stockIndi == "bbands"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_bbands(symbol=self.stockName,
                                                    time_period=30)

        elif (self.stockIndi == "aroon"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_aroon(symbol=self.stockName,
                                                   time_period=30)

        elif (self.stockIndi == "cci"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_cci(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "adx"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_adx(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "rsi"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_rsi(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "stoch"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_stoch(symbol=self.stockName,
                                                   time_period=30)

        return data, dataIndi
Esempio n. 23
0
# default is localhost:27017
connection = MongoClient('localhost:27017')

# Switching to a specific Database within MongoDB
db = connection.StockMarketDB

# Switching to a specific Collection(table) within the DB
col = db.monthlyStatistics

####################################################################

# Personal issued key from alpha_vantage
ts = TimeSeries(key='II0VU3FTX7AAEU99')

# Calling an individual company's monthly stock data
data, meta_data = ts.get_monthly(symbol='MSFT')

scope = monthly

# Will display that data
# pprint(meta_data)

parsed_data = {}

# formatting nested dictionary keys for mongoDB
for date, stock in data.items():
    parsed_data[date] = {}
    for price in stock.keys():
        parsed_data[date][price[3:]] = data[date][price]

#adding 'date' dictionary key as a value to
Esempio n. 24
0
import pandas as pd
from pandas import ExcelWriter
from alpha_vantage.timeseries import TimeSeries
import time
from credentials import *
import matplotlib.pyplot as plt

ts = TimeSeries(key=api_key, output_format='pandas')

a = 0
call_limit = [4, 8, 12]

writer = ExcelWriter('output.xlsx')

for i in stock_list:
    stonk_data, meta_data = ts.get_monthly(symbol=i)
    index=stonk_data.index
    index.name= "Stock: " + i
    close_data = stonk_data['4. close']
    percentage_change = close_data.pct_change() * 100
    stonks = "STOCK:", i, close_data, percentage_change
    print(stonk_data['4. close'])
    a += 1
    print("a =", a)
    file_name = i + " - Sheet - " + str(a)
    print(file_name)
    #Matplotlib will print a plot of each stock, how do i print them all in one view?
    #df = pd.DataFrame(stonk_data, columns=['4. close'])
    #df.plot(kind = 'line')
    #plt.show()
    stonk_data['4. close'].to_excel(writer, sheet_name=file_name)
Esempio n. 25
0
def plot(symbol):
    data = TimeSeries(key=key, output_format='pandas')
    data, meta_data = data.get_monthly(symbol)
    data['close'].plot()
    pyplot.title(symbol)
    pyplot.show()
Esempio n. 26
0
def get_monthly(symbol: str):
    ts = TimeSeries(key=config.AV_KEY, output_format="pandas")
    data, _ = ts.get_monthly(symbol)
    return data
Esempio n. 27
0
File: test.py Progetto: jklen/fin
    'SXR8'
]

#%%

from alpha_vantage.timeseries import TimeSeries

ts = TimeSeries(key='F5DIRSGL3KXINNCM', output_format='pandas')
# Get json object with the intraday data and another with  the call's metadata
#data, meta_data = ts.get_intraday('SPY')

dfs = []
metas = []
for ticker in finax_tickers:
    try:
        df, meta = ts.get_monthly(ticker)
        dfs.append(df)
        metas.append(meta)
    except Exception as e:
        print(f'ticker {ticker} data retreive error...')
        print(e)
    else:
        print(f'ticker {ticker} SUCCESS.....')
    time.sleep(13)

#%%

import investpy
# https://investpy.readthedocs.io/_info/introduction.html

# Retrieve all the available stocks as a Python list
Esempio n. 28
0
from alpha_vantage.timeseries import TimeSeries
import matplotlib.pyplot as plt

ts = TimeSeries(key='GSD3E3P11LSBZG5O', output_format='pandas')
data, meta_data = ts.get_monthly(symbol='FB')
data['close'].plot()
plt.title('Intraday Time Series for the FB4 stock (monthly)')
plt.show()
Esempio n. 29
0
 def collectData(self, outputsize='compact') -> pd.DataFrame:
     ts = TimeSeries(key=key, output_format='pandas')
     data, metadata = ts.get_monthly(self.symbol)
     return pd.DataFrame(data)
Esempio n. 30
0
def stockchart_5year(symbol1):
    title = '4 Years'
    ts = TimeSeries(key='QBGZM8IV1P2X2VJQ', output_format='pandas')
    data1, meta_data = ts.get_monthly(symbol=symbol1)

    return graph(symbol1, data1, title)