Beispiel #1
0
 def test_chartDF(self):
     from pyEX import chartDF
     with patch('requests.get') as mock:
         mock.return_value = MagicMock()
         mock.return_value.status_code = 200
         mock.return_value.json = MagicMock(return_value=[])
         chartDF('test')
Beispiel #2
0
def result():
    if request.method == 'POST':
        user = {'name': '','email': '','start_date': '','ticker1': '','amount1': '','ticker2': '','amount2': '','ticker3': '','amount3': '',}
        result1 = 0
        result2 = 0
        result3 = 0
        share1 = 0
        share2 = 0
        share3 = 0
        try:
            user['name'] = request.form['name']
            user['email'] = request.form['email']
            user['start_date'] = request.form['start_date']
            user['ticker1'] = request.form['ticker1']
            user['amount1'] = request.form['amount1']
            user['ticker2'] = request.form['ticker2']
            user['amount2'] = request.form['amount2']
            user['ticker3'] = request.form['ticker3']
            user['amount3'] = request.form['amount3']
        except:
            print('user input fetch error')

        try:
            df1 = p.chartDF(request.form['ticker1'], '5y').reset_index()
            start_price1 = df1.loc[df1['date'] ==
                                  request.form['start_date']]['close'].item()
            end_price1 = df1.iloc[-1:, 4].item()
            share1 = float(request.form['amount1']) / start_price1
            result1 = (end_price1 - start_price1) * share1
        except:
            print("tikcer1 search fail")

        try:
            df2 = p.chartDF(request.form['ticker2'], '5y').reset_index()
            start_price2 = df2.loc[df2['date'] ==
                                   request.form['start_date']]['close'].item()
            end_price2 = df2.iloc[-1:, 4].item()
            share2 = float(request.form['amount2']) / start_price2
            result2 = (end_price2 - start_price2) * share2
        except:
            print("tikcer2 search fail")

        try:
            df3 = p.chartDF(request.form['ticker3'], '5y').reset_index()
            start_price3 = df3.loc[df3['date'] ==
                                   request.form['start_date']]['close'].item()
            end_price3 = df3.iloc[-1:, 4].item()
            share3 = float(request.form['amount3']) / start_price3
            result3 = (end_price3 - start_price3) * share3
        except:
            print("tikcer3 search fail")

        result = result1 + result2 + result3
        result = round(result, 2)
        user['share'] = [share1, share2, share3]
        print(result)
        print(user)
    return render_template("result.html", result = result, user = user)
Beispiel #3
0
    def test_chartDF(self):
        from pyEX import chartDF
        with patch('requests.get') as mock, \
             patch('pickle.dump'):
            mock.return_value = MagicMock()
            mock.return_value.status_code = 200
            mock.return_value.json = MagicMock(return_value=[])

            chartDF(SYMBOL)
Beispiel #4
0
def _get_data(symbol, start, end):
    df = chartDF(symbol, '5y')
    if start:
        df = df[df.index > start]
    if end:
        df = df[df.index < end]

    return df
Beispiel #5
0
def _get_data(symbol, start, end):
    df = chartDF('aapl', '5y')
    df = df[['open', 'close', 'high', 'low', 'volume']].set_index(df['date'])
    df.index = pd.to_datetime(df.index)
    if start:
        df = df[df.index > start]
    if end:
        df = df[df.index < end]

    return df
Beispiel #6
0
def refetch(field, symbol):
    if field == 'TICK':
        return p.chartDF(symbol, '1d')
    if field == 'FINANCIALS':
        return p.financialsDF(symbol)
    elif field == 'DAILY':
        return p.chartDF(symbol, '5y')
    elif field == 'COMPANY':
        return p.companyDF(symbol)
    elif field == 'EARNINGS':
        return p.earningsDF(symbol)
    elif field == 'DIVIDENDS':
        return p.dividendsDF(symbol)
    elif field == 'NEWS':
        return p.newsDF(symbol)
    elif field == 'STATS':
        return p.stockStatsDF(symbol)
    elif field == 'COMPOSITION':
        return _fetchComposition(symbol)
    elif field == 'PEERS':
        return p.peersDF(symbol)
    raise NotImplementedError('%s - %s' % (field, symbol))
Beispiel #7
0
def Predict(ticker, timeframe, N):
    ticker = str(ticker)
    timeframe = str(timeframe)
    #N=int(N)
    df = p.chartDF(ticker, timeframe)
    df = df[['close']]
    df.reset_index(level=0, inplace=True)
    df.columns = ['ds', 'y']
    m = Prophet()
    m.fit(df)
    future = m.make_future_dataframe(periods=N)
    forecast = m.predict(future)
    forecast['day_week'] = forecast.ds.dt.weekday_name
    forecast = forecast[forecast.day_week != 'Sunday']
    forecast = forecast[forecast.day_week != 'Saturday']
    trend = forecast.to_json()
    #print(forecast)
    #print(trend)
    #print(forecast)
    #m.plot(forecast,xlabel='Date', ylabel='Price')
    #m.plot_components(forecast)
    #plt.show()
    return trend
Beispiel #8
0
 def test_chartDF(self):
     from pyEX import chartDF
     chartDF(SYMBOL)
Beispiel #9
0
#url=https://towardsdatascience.com/implementing-moving-averages-in-python-1ad28e636f9d

import pandas as pd
import numpy as np
from datetime import datetime

import matplotlib.pyplot as plt
import pyEX as p

ticker='AMD'
timeframe='1y'

df=p.chartDF(ticker,timeframe)
df=df[['close']]
df.reset_index(level=0, inplace=True)
df.columns=['ds','y']

plt.plot(df.ds,df.y)
plt.show()

rolling_mean=df.y.rolling(window=20).mean()
rolling_mean2=df.y.rolling(window=50).mean()

plt.plot(df.ds, df.y,label='AMD')
plt.plot(df.ds,rolling_mean,label='AMD 20 day SMA',color='orange')
plt.plot(df.ds,rolling_mean2,label='AMD 50 day SMA',color='magenta')
plt.legend(loc='upper_left')
plt.show()

exp1=df.y.ewm(span=20,adjust=False).mean()
exp2=df.y.ewm(span=50,adjust=False).mean()
companies = []
for company in topCompanies:
    companies.append(company['name'])

companies = {company: {} for company in companies}

for company in topCompanies:
    companies[company['name']]['symbol'] = company['symbol']
    companies[company['name']]['industry_id'] = company['industry_id']

arbSymbol = 'AAPL'

# arbitrarily create df object
# get stock history for last month
arbChart = p.chartDF(arbSymbol, timeframe='1m')
# add stock symbol to df to act as a foreign key for company table
arbChart['symbol'] = "Arbitrary"
arbChart['industry_id'] = 0
# get company info
arbCompany = p.companyDF(arbSymbol)
# join the 2 tables and add to rest of stocks df
stocks_df = pd.merge(arbChart, arbCompany, how='left', on=['symbol'])

for company in companies.values():
    symbol = company['symbol']
    industry_id = company['industry_id']
    # get stock history for last 1 month
    chart_df = p.chartDF(symbol, timeframe='1y')
    # add stock symbol to df to act as a foreign key for company table
    chart_df['symbol'] = symbol
Beispiel #11
0
def update_graph(tickers):
    graphs = []
    for i, ticker in enumerate(tickers):
        try:
            df = pyEX.chartDF(str(ticker), '6m').reset_index()
        except:
            graphs.append(
                html.H3(
                    'Data is not available for {}, please retry later.'.format(
                        ticker),
                    style={
                        'marginTop': 20,
                        'marginBottom': 20
                    }))
            continue

        candlestick = {
            'x': df['date'],
            'open': df['open'],
            'high': df['high'],
            'low': df['low'],
            'close': df['close'],
            'type': 'candlestick',
            'name': ticker,
            'legendgroup': ticker,
            'increasing': {
                'line': {
                    'color': colorscale[0]
                }
            },
            'decreasing': {
                'line': {
                    'color': colorscale[1]
                }
            }
        }
        bb_bands = bbands(df.close)
        bollinger_traces = [{
            'x': df['date'],
            'y': y,
            'type': 'scatter',
            'mode': 'lines',
            'line': {
                'width': 1,
                'color': colorscale[(i * 2) % len(colorscale)]
            },
            'hoverinfo': 'none',
            'legendgroup': ticker,
            'showlegend': True if i == 0 else False,
            'name': '{} - bollinger bands'.format(ticker)
        } for i, y in enumerate(bb_bands)]
        graphs.append(
            dcc.Graph(id=ticker,
                      figure={
                          'data': [candlestick] + bollinger_traces,
                          'layout': {
                              'margin': {
                                  'b': 0,
                                  'r': 10,
                                  'l': 60,
                                  't': 0
                              },
                              'legend': {
                                  'x': 0
                              }
                          }
                      }))

    return graphs
Beispiel #12
0
    def _minute_dataframe_for_date(
            self, ticker: str, start_timestamp: pd.Timestamp) -> pd.DataFrame:
        ret_df = pd.DataFrame()

        df = pyEX.chartDF(ticker, timeframe='1d', date=start_timestamp)

        if df.empty:
            return ret_df

        df = df.reset_index()
        df['volume'] = df['volume'].astype('int')
        df['date'] = df['date'].astype('str')
        df['minute'] = df['minute'].astype('str')
        df['datet'] = df['date'] + ' ' + df['minute']
        df['dividend'] = 0.0
        df['split'] = 1.0
        df.drop([
            'date', 'minute', 'average', 'changeOverTime', 'close', 'high',
            'label', 'low', 'marketAverage', 'marketChangeOverTime',
            'marketNotional', 'marketNumberOfTrades', 'notional',
            'numberOfTrades', 'open', 'volume'
        ],
                axis=1,
                level=None,
                inplace=True,
                errors='ignore')
        df.rename(columns={
            'datet': 'date',
            'marketClose': 'close',
            'marketHigh': 'high',
            'marketLow': 'low',
            'marketOpen': 'open',
            'marketVolume': 'volume'
        },
                  inplace=True)
        df.date = pd.to_datetime(df.date,
                                 errors='coerce',
                                 utc=False,
                                 infer_datetime_format=True)
        df = df[~df.date.isnull()]
        df.set_index('date',
                     drop=True,
                     append=False,
                     inplace=True,
                     verify_integrity=True)

        utc = pytz.utc
        nytz = pytz.timezone('US/Eastern')
        df = df.tz_localize(nytz,
                            axis=0,
                            level=None,
                            copy=False,
                            ambiguous='raise')
        df.index = df.index.tz_convert(utc)
        if not (pd.Series(['close', 'high', 'low', 'open']).isin(
                df.columns).all()):
            log.info(
                "Skipping {0} for {1}, not all columns ({2}) received".format(
                    ticker, start_timestamp.date(), str(df.columns)))
            return ret_df

        df = self._fixna(df, ticker)
        df.index = df.index.tz_convert(None)

        # Re-arrange them
        ret_df = df[self._cols]
        return ret_df
Beispiel #13
0
    def fetchDF(self, key, field, _ret=True):
        # tickers always caps
        key = key.upper()

        # fields always lower
        field = field.lower()

        if not (self._tickers['symbol'] == key).any():
            # FIXME
            return pd.DataFrame()

        if key not in self._cache:
            # initialize cache
            self._cache[key] = {}
            self._cache[key]['timestamp'] = {}

        if field in ('financials', 'all'):
            if 'financials' not in self._cache[key] or self._check_timestamp(
                    key, 'financials'):
                try:
                    self._cache[key]['financials'] = p.financialsDF(key)
                except KeyError:
                    self._cache[key]['financials'] = pd.DataFrame()
                self._cache[key]['timestamp']['financials'] = datetime.now()

        if field in ('chart', 'all'):
            if 'chart' not in self._cache[key] or self._check_timestamp(
                    key, 'chart'):
                try:
                    self._cache[key]['chart'] = p.chartDF(key, '1y')
                except KeyError:
                    self._cache[key]['chart'] = pd.DataFrame()

                self._cache[key]['timestamp']['chart'] = datetime.now()

        if field in ('company', 'all'):
            if 'company' not in self._cache[key] or self._check_timestamp(
                    key, 'company'):
                self._cache[key]['company'] = p.companyDF(key)
                self._cache[key]['timestamp']['company'] = datetime.now()

        if field in ('quote', 'all'):
            # always update
            self._cache[key]['quote'] = p.quoteDF(key)

        if field in ('dividends', 'all'):
            if 'dividends' not in self._cache[key] or self._check_timestamp(
                    key, 'dividends'):
                try:
                    self._cache[key]['dividends'] = p.dividendsDF(key)
                except KeyError:
                    self._cache[key]['dividends'] = pd.DataFrame()
                self._cache[key]['timestamp']['dividends'] = datetime.now()

        if field in ('earnings', 'all'):
            if 'earnings' not in self._cache[key] or self._check_timestamp(
                    key, 'earnings'):
                try:
                    self._cache[key]['earnings'] = p.earningsDF(key)
                except KeyError:
                    self._cache[key]['earnings'] = pd.DataFrame()
                self._cache[key]['timestamp']['earnings'] = datetime.now()

        if field in ('news', 'all'):
            if 'news' not in self._cache[key] or self._check_timestamp(
                    key, 'news'):
                try:
                    self._cache[key]['news'] = p.newsDF(key)
                except KeyError:
                    self._cache[key]['news'] = pd.DataFrame()
                self._cache[key]['timestamp']['news'] = datetime.now()

        if field in ('peers', 'all'):
            if 'peers' not in self._cache[key] or self._check_timestamp(
                    key, 'peers'):
                try:
                    peers = p.peersDF(key)
                except KeyError:
                    peers = pd.DataFrame()

                if peers is not None and not peers.empty:
                    peers = peers.replace({np.nan: None})
                    infos = pd.concat(
                        [p.companyDF(item) for item in peers['symbol'].values])
                    self._cache[key]['peers'] = infos
                else:
                    self._cache[key]['peers'] = pd.DataFrame()
                self._cache[key]['timestamp']['peers'] = datetime.now()

        if field in ('stats', 'all'):
            if 'stats' not in self._cache[key] or self._check_timestamp(
                    key, 'stats'):
                try:
                    self._cache[key]['stats'] = p.stockStatsDF(key)
                except KeyError:
                    self._cache[key]['stats'] = pd.DataFrame()
                self._cache[key]['timestamp']['stats'] = datetime.now()

        if field in ('composition', 'all'):
            if 'company' not in self._cache[key]:
                self.fetchDF(key, 'company', _ret=False)

            try:
                self._cache[key]['composition'] = pd.read_html(
                    ETF_URL % key, attrs={'id': 'etfs-that-own'})[0]
                self._cache[key]['composition']['% of Total'] = self._cache[
                    key]['composition']['% of Total'].str.rstrip('%').astype(
                        float) / 100.0
                self._cache[key]['composition'].columns = [
                    'Symbol', 'Name', 'Percent'
                ]
                self._cache[key]['composition'] = self._cache[key][
                    'composition'][['Symbol', 'Percent', 'Name']]

            except (IndexError, requests.HTTPError, ValueError, HTTPError):
                self._cache[key]['composition'] = pd.DataFrame()

            self._cache[key]['timestamp']['composition'] = datetime.now()

        if _ret:
            # pull data
            if field == 'all':
                ret = copy.deepcopy(self._cache[key])
                del ret['timestamp']
                ret = pd.concat(ret)

            elif field in self._cache[key]:
                # or i have that field
                ret = pd.concat({field: self._cache[key][field]})
            else:
                raise Exception('No ticker provided!')

            return ret