Exemplo n.º 1
0
def _iex_aggregator(fn_name: str, **kwargs: object) -> dict:
    agg = dict()

    for chunk in util.chunk(symbols(remove='expired'), 100):
        tickers = list(chunk)
        fn = getattr(iex.Stock(tickers), fn_name)

        retrieved = fn(**kwargs)
        if type(retrieved) is list:
            data = defaultdict(list)
            for datum in retrieved:
                data[datum['symbol']].append(datum)
        elif type(retrieved) is dict:
            data = {ticker: datum for ticker, datum in retrieved.items()}
        else:
            raise RuntimeError(
                "Error: `%s' (retrieved) is neither dict nor list" % retrieved)

        agg.update(data)

    if fn_name == 'get_financials':
        # Yes, iexfinance is returning this mess for financials, which we need to correct
        return {
            ticker: datum.get('financials', [None])[0]
            for ticker, datum in agg.items()
        }
    else:
        return {ticker: datum for ticker, datum in agg.items()}
Exemplo n.º 2
0
def Evaluate(Name, **kwargs):
    OverrideGrowthRate = kwargs.get('G', None)

    #Get Stock from ticker Name
    Company = Stock.Stock(Name)
    eps = Company.get_earnings(last=1)

    if (OverrideGrowthRate != None):
        Results = (eps[0]['actualEPS'] *
                   (8.5 + 2.0 + 100.0 * OverrideGrowthRate) *
                   4.4) / USAAA20yrCorporateBondYield
        return Results
    else:
        #inform on graham growth rate correction factors
        #YoYGrowth = eps[0]['actualEPS']/eps[0]['yearAgo']
        SurprisePercent = eps[0]['EPSSurpriseDollar'] / eps[0]['consensusEPS']

        flow = Company.get_income_statement(period='annual', last=4)
        RevGrowth = AvgRevenueGrowth(flow)
        IncGrowth = AvgNetIncomeGrowth(flow)

        GrowthRate = min(RevGrowth, IncGrowth)

        #Corrections based on EPS GrowthYoY
        #This is a judgement call and likely will need adjustment
        #Will only bring Growth Rate down, never up to keep a reasonable margin of safety
        if (SurprisePercent > 0):
            GrowthRate = GrowthRate + SurprisePercent * 0.5

        Result = (eps[0]['actualEPS'] *
                  (8.5 + 2.0 * GrowthRate) * 4.4) / USAAA20yrCorporateBondYield
        return Result
Exemplo n.º 3
0
def iex_stock(ticker):
    global IEX_STOCKS
    if ticker in IEX_STOCKS:
        stock = IEX_STOCKS[ticker]
    else:
        stock = iex.Stock(ticker)
        IEX_STOCKS[ticker] = stock
    return stock
Exemplo n.º 4
0
 def get_chart(self, start=date(2019, 3, 1), end=datetime.now().date()):
     quote = stocks.Stock(self.symbol).get_quote()
     return stocks.get_historical_data(
         self.symbol,
         start=start,
         end=end,
         close_only=True,
         output_format="pandas",
     ).close.append(
         pd.Series(data=quote.get("latestPrice"),
                   index=[datetime.now().date()]))
Exemplo n.º 5
0
def resolve_sectors(obj: Portfolio, info: GraphQLResolveInfo):
    positions = obj.position_set.all()
    sectors = []
    for position in positions:
        sectors.append({
            "name": stocks.Stock(position.stock.symbol).get_sector(),
            "share": position.quantity * position.price,
        })
    total = sum([sector.get("share") for sector in sectors])
    sectors = [{
        **sector, "share": sector.get("share") / total
    } for sector in sectors]
    return sectors
Exemplo n.º 6
0
def buy_order(clean_input):
    symbol = clean_input.get("symbol")
    quote = stocks.Stock(symbol).get_quote()
    portfolio = Portfolio.objects.first()
    stock, created = Stock.objects.get_or_create(symbol=symbol,
                                                 name=quote.get("companyName"))
    return Position.objects.create(
        portfolio=portfolio,
        stock=stock,
        quantity=clean_input.get("quantity"),
        opened=timezone.now(),
        price=quote.get("latestPrice"),
        long=True,
    )
Exemplo n.º 7
0
def makeLinearModel(ticker, start, end):
    '''
    Given a start, and ending date, we can calculate a linear regressionself.
    '''
    historicalData = iex.get_historical_data(ticker,
                                             start,
                                             end,
                                             output_format='pandas')
    historicalData = historicalData.values
    Data_X = []
    Data_Y = []
    for i in range(len(historicalData) - 1):
        Data_X.append([historicalData[i][0], historicalData[i][4]])
        Data_Y.append([historicalData[i + 1][0]])
    linear = LinearRegression()
    imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
    Data_X = imputer.fit_transform(Data_X)
    Data_Y = imputer.fit_transform(Data_Y)
    linear.fit(Data_X, Data_Y)
    stock = iex.Stock(ticker)
    currentDay = [[stock.get_price(), stock.get_volume()]]
    return (linear.predict(Data_X), linear.predict(currentDay))
Exemplo n.º 8
0
 def get_history(self):
     history = self.get_balance()
     for position in self.position_set.all():
         prices = stocks.get_historical_data(
             position.stock.symbol,
             start=position.opened,
             end=position.closed or timezone.now(),
             close_only=True,
             output_format="pandas",
         )
         quote = stocks.Stock(position.stock.symbol).get_quote()
         values = prices.close
         if not position.closed:
             values = values.append(
                 pd.Series(data=quote.get("latestPrice"),
                           index=[datetime.now().date()]))
         q = 1 if position.long else -1
         history["close"] = history["close"].add(
             position.quantity * values.diff().cumsum() * q,
             fill_value=0,
         )
     return history
Exemplo n.º 9
0
def informationMap(ticker):
    '''
    Input: Ticker (ie TSLA)
    Output: A list of tuples, that contain all the basic informaiton of the stock.
    '''
    stock = iex.Stock(ticker)
    financials = ['reportDate', 'totalRevenue', 'grossProfit', 'currentAssets']
    infoMap = []
    infoMap.append(('Company Name', stock.get_company_name()))
    infoMap.append(('Sector', stock.get_sector()))
    infoMap.append(('Market Cap', '$' + str(stock.get_market_cap())))
    infoMap.append(('Volume', (stock.get_market_cap())))
    infoMap.append(('Most Recent EPS', stock.get_latest_eps()))
    for metric in financials:
        if (metric == 'reportDate'):
            infoMap.append((convert(metric),
                            ' ' + str(stock.get_financials()[0][metric])))
        else:
            infoMap.append((convert(metric),
                            ' $' + str(stock.get_financials()[0][metric])))

    infoMap.append(('Beta', stock.get_beta()))
    return infoMap
Exemplo n.º 10
0
def randomForestModel(ticker, start, end):
    '''
    Given a start, and ending date, we can calculate a linear regressionself.
    '''
    historicalData = iex.get_historical_data(ticker,
                                             start,
                                             end,
                                             output_format='pandas')
    historicalData = historicalData.values
    Data_X = []
    Data_Y = []
    for i in range(len(historicalData) - 1):
        Data_X.append([historicalData[i][0], historicalData[i][4]])
        Data_Y.append([historicalData[i + 1][0]])
    Data_X = np.array(Data_X)
    Data_Y = np.array(Data_Y)
    imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
    Data_X = imputer.fit_transform(Data_X)
    Data_Y = imputer.fit_transform(Data_Y)
    forest = RandomForestRegressor(max_depth=10, n_estimators=100)
    forest.fit(Data_X, Data_Y.ravel())
    stock = iex.Stock(ticker)
    currentDay = [[stock.get_price(), stock.get_volume()]]
    return (forest.predict(Data_X), forest.predict(currentDay))
Exemplo n.º 11
0
def GetData(name):
        stock=Stock.Stock(str(name))
        return stock.get_financials()
Exemplo n.º 12
0
def get_iex_stock(ticker):
    """get_iex_stock(ticker) -> iexstocks.Stock

Gets a stock with the given ticker.
"""
    return iexstocks.Stock(ticker, output_format='json', token=IEX_TOKEN)
Exemplo n.º 13
0

#calculate Net Income growth last 3y
def AvgNetIncomeGrowth(Data):
    FirstYear = Data[3]['netIncome']
    LastYear = Data[0]['netIncome']
    if (FirstYear != None and LastYear != None and FirstYear != 0):
        rate = (LastYear / FirstYear) / 3
        if (FirstYear > LastYear):
            return rate * -1
        else:
            return rate


#Get latest earnings value
Company = Stock.Stock("MCD")
eps = Company.get_earnings(last=1)

#inform on graham growth rate correction factors
YoYGrowth = eps[0]['actualEPS'] / eps[0]['yearAgo']
SurprisePercent = eps[0]['EPSSurpriseDollar'] / eps[0]['consensusEPS']

flow = Company.get_income_statement(period='annual', last=4)
RevGrowth = AvgRevenueGrowth(flow)
IncGrowth = AvgNetIncomeGrowth(flow)

#To account for companies that are becoming
#more efficient while not increasing Revenue
GrowthRate = min(RevGrowth, IncGrowth)

#Corrections based on EPS GrowthYoY
Exemplo n.º 14
0
def resolve_latest_price(obj: Stock, info: GraphQLResolveInfo):
    quote = stocks.Stock(obj.symbol).get_quote()
    return quote.get("latestPrice")
Exemplo n.º 15
0
def CalcReturnOnTotalAssets(data):
    EBIT = float(data[0]['grossProfit']) - float(data[0]['operatingExpense'])
    ROTA = EBIT / float(data[0]['totalAssets'])
    return round(ROTA * 100, 2)


#this is for long term ability to pay debts
def CalcDebtToEquityRatio(data):
    output = float(data[0]['totalLiabilities']) / float(
        data[0]['shareholderEquity'])
    return round(output * 100, 2)


def CalcCurrentRatio(data):
    output = float(data[0]['currentDebt']) / float(data[0]['currentAssets'])
    return round(output * 100, 2)


stock = Stock.Stock("MCD")

d = stock.get_financials()

a = CalcReturnOnEquity(d)

b = CalcReturnOnTotalAssets(d)

c = CalcDebtToEquityRatio(d)

aa = CalcCurrentRatio(d)
Exemplo n.º 16
0
def GetPrice(name):
    if type(name) is str:
        stock = Stock.Stock(name)
        return stock.get_price()