Example #1
0
def get_div_yield(symbol):

    stock = YahooFinancials(symbol)
    if stock.get_dividend_yield() != None:
        y = stock.get_dividend_yield()
    elif stock.get_summary_data()[symbol] != None:
        y = stock.get_summary_data()[symbol]['yield']
    else:
        y = 0

    if y == None:
        return 0
    else:
        return y
 def calculate_dividend_yield(self):
     yahoo_financials = YahooFinancials(self.symbols)
     logging.debug(
         "[calculate_dividend_yield] YahooFinancials - Fetching get_dividend_yield"
     )
     divs = yahoo_financials.get_dividend_yield()
     logging.debug(
         "[calculate_dividend_yield] YahooFinancials - Finished fetching get_exdividend_date"
     )
     for symbol in self.symbols:
         self.fin_data[symbol]["dividend_yield"] = divs[symbol]
Example #3
0
def fundamentals(tickers, begin="2020-05-26", end="2020-06-26",):
    format_header = '{:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>10} {:>10}'
    format_numbers = '{:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6}  {:>6} {:>10.2e} {:>10.2E}'
    print(format_header.format('ticker', 'P/E', 'EARNSH', 'BK/PR', 'DY', 'DR', 'VAR', 'PEG', 'PS', 'PCI', 'VOLPR', 'CM',))

    for ticker in tickers:
        yf = YF(ticker)

        try:
            pe = get_number_for_None(get_number_for_None(yf.get_pe_ratio()))
            prices = yf.get_historical_price_data(begin, end, "daily")[ticker]['prices']
            stat_pr = calc_statistics(prices)
            var_pr = get_number_for_None(100 * stat_pr[1] / stat_pr[0])
            volume = get_number_for_None(stat_pr[4])
            es = get_number_for_None(yf.get_earnings_per_share())
            sh = get_number_for_None(yf.get_num_shares_outstanding(price_type='current'))
        
            ''' "pegRatio" "priceToBook" "heldPercentInstitutions" '''
            
            statistics = yf.get_key_statistics_data()[ticker]
            summary = yf.get_summary_data()[ticker]
            peg = get_number_for_None(statistics["pegRatio"])
            PCI = get_number_for_None(statistics["heldPercentInstitutions"])
            bv = yf.get_key_statistics_data()[ticker]['bookValue']
            pr = yf.get_current_price()

            if pr is not None and bv is not None:
                pr_bv = get_number_for_None(pr/bv)
            else:
                pr_bv = '-99.99'

            f_s = yf.get_financial_stmts('annual', 'income')['incomeStatementHistory'][ticker][0]
            f_s_key = list(f_s.keys())[0]
            totalRevenue = f_s[f_s_key]['totalRevenue']
            outstanding = statistics["sharesOutstanding"]
            rev_per_share = totalRevenue / outstanding
            
            if pr is not None and es is not None:
                p_s = get_number_for_None(rev_per_share/float(es))
            else:
                p_s = '99'

              
            dy = get_number_for_None(yf.get_dividend_yield())
            dr = get_number_for_None(yf.get_dividend_rate())
        
            volume10days = summary['averageVolume10days']
            marketCap = summary['marketCap']
        
            # float(volume)*pr
            # float(sh)*pr)
            print(format_numbers.format(ticker, pe, es, pr_bv, dy, dr, var_pr, peg, p_s, PCI, volume10days, marketCap))
        except Exception as e:
            print(ticker, e)
Example #4
0
def getMarketData():
    tickers = 'AAPL'
    financials = YahooFinancials(tickers)

    #	company_stock_price = financials.get_stock_price_data() #gets stock price information

    historical_stock_prices_data = financials.get_historical_price_data(
        '2015-11-21', '2020-11-21',
        'daily')  #gets historical daily stock price of company
    #	get_Div_data(historical_stock_prices_data[tickers])
    get_stock_price_data(historical_stock_prices_data[tickers])

    #	company_balance_sheet_data_qt = financials.get_financial_stmts('quarterly', 'balance') #get balance sheet
    #	company_income_statement_data_qt = financials.get_financial_stmts('quarterly', 'income') #get income statement

    company_key_statistics_data = financials.get_key_statistics_data(
    )  #includes profit margins, forward eps, yearly change etc.
    #	get_forward_pe(company_key_statistics_data[tickers])
    #	get_trailing_eps(company_key_statistics_data[tickers])
    #	get_foward_eps(company_key_statistics_data[tickers])
    #	get_ytdReturn(company_key_statistics_data[tickers])

    company_earnings_data = financials.get_stock_earnings_data(
    )  #historical eps only for 1 year span
    #	get_earnings_data(company_earnings_data[tickers])

    company_dividend_yield = financials.get_dividend_yield(
    )  #current dividends yield
    company_dividend = financials.get_dividend_rate()  #current dividends rate
    company_avg_div_yield_1year = financials.get_annual_avg_div_yield(
    )  #average 1 year div yield
    company_avg_div_yield_5year = financials.get_five_yr_avg_div_yield(
    )  #average 5 year div yield
    company_eps = financials.get_earnings_per_share()  #current eps
    company_pe = financials.get_pe_ratio()  #current pe ratio
    company_beta = financials.get_beta()  #current beta
    company_current_stock_price = financials.get_current_price(
    )  #current stock price

    company_revenue = financials.get_total_revenue()  #current company revenue
    company_operating_income = financials.get_operating_income(
    )  #current company operating income
    company_net_income = financials.get_net_income()  #current net income

    company_yearly_high = financials.get_yearly_high()  #get yearly high
    company_yearly_low = financials.get_yearly_low()  #get yearly low
    company_moving_50 = financials.get_50day_moving_avg(
    )  #50 day moving average of stock
    company_moving_200 = financials.get_200day_moving_avg(
    )  #200 day moving average of stock
Example #5
0
def update_shares(request, portfolio_pk):

    portfolio = Portfolio.objects.get(pk=portfolio_pk)
    check_ownership(request, portfolio)
    pstocks = PortfolioStock.objects.filter(portfolio=portfolio)
    for pstock in pstocks:
        stock = pstock.stock
        yf = YahooFinancials(quote_name)
        stock.last_price = convert_number(yf.get_current_price())
        stock.price_sales_ratio = convert_number(yf.get_price_to_sales())
        stock.dividend_yield = convert_number(yf.get_dividend_yield())

        stock.save()
    return http.HttpResponseRedirect('..')
Example #6
0
def index(response):
    form = EnterMarketCap
    form2 = EnterDividend
    form3 = EnterIndustry
    form4 = EnterPrice
    form5 = EnterPE

    form9 = ""
    form10 = ""
    form11 = ""
    bla = ""

    mk = 0
    div = 0
    ind = ""
    price = 0

    if response.method == "GET" and response.GET.get('apply') == 'apply':
        form = EnterMarketCap(response.GET)
        form2 = EnterDividend(response.GET)
        form3 = EnterIndustry(response.GET)
        form4 = EnterPrice(response.GET)
        form5 = EnterPE(response.GET)

        #payload = pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
        #first_table = payload[0]

        #df = first_table
        #df.head()

        #symbols = df['Symbol'].values.tolist()
        ticker_list = [
            'FB', 'AAPL', 'FRT', 'AMZN', 'FIS', 'FITB', 'FE', 'FRC', 'FISV',
            'FLT', 'FLIR', 'FLS', 'FMC', 'F', 'FTNT', 'FTV', 'FBHS', 'FOXA',
            'FOX', 'BEN', 'FCX', 'GPS', 'GRMN', 'IT', 'GD', 'GE', 'GIS', 'GM',
            'L', 'LOW', 'LUMN', 'LYB', 'MTB', 'MRO', 'MPC', 'MKTX', 'MAR',
            'MMC', 'MLM', 'MAS', 'MA', 'MKC', 'MXIM', 'MCD', 'MCK', 'MDT',
            'TSLA', 'MET', 'MTD', 'MGM', 'MCHP', 'MU', 'MSFT', 'MAA', 'MHK'
        ]

        if form.is_valid():
            mk = (form.cleaned_data["marketcap"])
            ck = form.cleaned_data["check"]
            sign = form.cleaned_data["sign"]
        else:
            mk = 0
            ck = False
            sign = ""

        if form2.is_valid():
            div = form2.cleaned_data["dividend"]
            ck2 = form2.cleaned_data["check2"]
            sign2 = form2.cleaned_data["sign2"]
        else:
            div = 0.0
            ck2 = False
            sign2 = ""

        if form3.is_valid():
            ind = form3.cleaned_data["industry"]
            ck3 = form3.cleaned_data["check3"]
        else:
            ind = ""
            ck3 = False

        if form4.is_valid():
            p = form4.cleaned_data["price"]
            ck4 = form4.cleaned_data["check4"]
            sign4 = form4.cleaned_data["sign4"]
        else:
            p = 0
            ck4 = False
            sign4 = ""

        if form5.is_valid():
            pe_ratio = form5.cleaned_data["pe_ratio"]
            ck5 = form5.cleaned_data["check5"]
            sign5 = form5.cleaned_data["sign5"]
        else:
            pe_ratio = 0
            ck5 = False
            sign5 = ""

        if ck is True:
            form10 = mk
        else:
            form10 = ""

        if ck4 is True:
            form9 = p
        else:
            form9 = ""

        resultMK = []
        form11 = ""

        if mk != 0 and ck is True and ck5 is False and ck4 is False and ck2 is False:
            for i in ticker_list:
                ticker = yf.Ticker(i)
                b = ticker.info["marketCap"]
                if sign == "Above":
                    if b > (mk * 1000000000):
                        resultMK.append(i)
                elif sign == "Below":
                    if b < (mk * 1000000000):
                        resultMK.append(i)

        resultDIV = []

        if div != 0 and ck is False and ck5 is False and ck4 is False and ck2 is True:
            for i in ticker_list:
                yahoo_financials = YahooFinancials(i)
                d = yahoo_financials.get_dividend_yield()
                if sign2 == "Above":
                    if d > (div / 100):
                        resultDIV.append(i)
                elif sign2 == "Below":
                    if d < (div / 100):
                        resultDIV.append(i)

        resultP = []

        if p != 0 and ck is False and ck5 is False and ck4 is True and ck2 is False:
            for i in ticker_list:
                price = si.get_live_price(i)
                if sign4 == "Above":
                    if price > p:
                        resultP.append(i)
                elif sign4 == "Below":
                    if price < p:
                        resultP.append(i)

        resultPE = []

        if div != 0 and ck is False and ck5 is True and ck4 is False and ck2 is False:
            for i in ticker_list:
                ticker = yf.Ticker(i)
                pe = ticker.info["forwardPE"]
                if sign5 == "Above":
                    if pe > pe_ratio:
                        resultPE.append(i)
                elif sign5 == "Below":
                    if pe < pe_ratio:
                        resultPE.append(i)

        intermediate = []
        resultP_MK = []

        if ck is True and ck5 is False and ck4 is True and ck2 is False:
            for i in ticker_list:
                price = si.get_live_price(i)
                if sign4 == "Above":
                    if price > p:
                        intermediate.append(i)
                elif sign4 == "Below":
                    if price < p:
                        intermediate.append(i)

            for i in intermediate:
                ticker = yf.Ticker(i)
                b = ticker.info["marketCap"]
                if sign == "Above":
                    if b > (mk * 1000000000):
                        resultP_MK.append(i)
                elif sign == "Below":
                    if b < (mk * 1000000000):
                        resultP_MK.append(i)

        if ck is True and ck5 is False and ck4 is False and ck2 is False:
            if not resultMK:
                form11 = "Your filters match no stock (From my list of 50 stocks :)"
            else:
                form11 = resultMK
        elif ck is False and ck4 is True and ck5 is False and ck2 is False:
            if not resultP:
                form11 = "Your filters match no stock (From my list of 50 stocks :)"
            else:
                form11 = resultP
        elif ck is True and ck5 is False and ck4 is True and ck2 is False:
            if not resultP_MK:
                form11 = "Your filters match no stock (From my list of 50 stocks :)"
            else:
                form11 = resultP_MK
        elif ck is False and ck5 is True and ck4 is False and ck2 is False:
            form11 = resultPE
            #if not resultDIV:
            #    form11 = "Your filters match no stock (From my list of 50 stocks :)"
            #else:
            #    form11 = resultDIV
        elif ck is False and ck5 is False and ck4 is False and ck2 is True:
            form11 = resultDIV
        elif ck is False and ck2 is False and ck4 is False and ck2 is False:
            form11 = "You didn't enter any filter, Click use to use a filter!"

    return render(
        response, "main/home.html", {
            "form": form,
            "form2": form2,
            "form3": form3,
            "form4": form4,
            "form5": form5,
            "form9": form9,
            "form10": form10,
            "form11": form11
        })
Example #7
0
def Statement():
    page_bg_img = '''
    <style>
    body {
    background-image: url("https://images.pexels.com/photos/2748757/pexels-photo-2748757.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=1000");
    background-size: cover;
    }
    </style>
    '''
    st.markdown(page_bg_img, unsafe_allow_html=True)
    symbols = 'https://raw.githubusercontent.com/Moly-malibu/Stocks/main/bxo_lmmS1.csv'
    df = pd.read_csv(symbols)
    ticker = st.sidebar.selectbox('Stocks by Company', (df['Symbol']))
    tickerData = YahooFinancials(ticker)

    def get_symbol(symbol):
        url = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query={}&region=1&lang=en".format(
            symbol)
        result = requests.get(url).json()
        for x in result['ResultSet']['Result']:
            if x['symbol'] == symbol:
                return x['name']

    company_name = get_symbol(ticker.upper())
    st.write("""# Analysis of """, company_name)
    company = yf.Ticker(ticker)
    # st.write(company.info)
    company_general = st.sidebar.checkbox("Financial Ratio")
    if company_general:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Financial Ratios</h1>",
            unsafe_allow_html=True)
        st.write('***Payout Ratio:*** ', company.info["payoutRatio"])
        st.write('***Trailing Annual Dividend Yield:*** ',
                 company.info["trailingAnnualDividendYield"])
        st.write('***Dividend Rate:*** ', company.info["dividendRate"])
        st.write('***Profit Margins: ***', company.info["profitMargins"])
        st.write('***Peg Ratio: ***', company.info["pegRatio"])
        yahoo_financials = YahooFinancials(ticker)
        marketcap = yahoo_financials.get_market_cap()
        price_to_sales = yahoo_financials.get_current_price()
        dividend_yield = yahoo_financials.get_dividend_yield()
        income_balance = si.get_income_statement(ticker)
        transpose_income = income_balance.transpose()
        balance_income = si.get_balance_sheet(ticker)
        transpose_balance = balance_income.transpose()
        st.write("""**Dividends**""", company.dividends)
        income = si.get_income_statement(ticker)
        transpose = income.transpose()
        interest_coverage1 = transpose['operatingIncome']
        interest_coverage2 = transpose['interestExpense']
        st.write(
            '***Interest Coverage:*** Operating Income / interest Expenses',
            interest_coverage1 / interest_coverage2)
        gross_profit_margin1 = transpose['totalRevenue']
        gross_profit_margin2 = transpose['costOfRevenue']
        st.write(
            '***Gross Profit Margin:*** Total Revenue / Gross Profit Margin',
            (gross_profit_margin1 - gross_profit_margin2) /
            gross_profit_margin1)
        balance = si.get_balance_sheet(ticker)
        transpose = balance.transpose()
        current_ratio1 = transpose['totalCurrentAssets']
        current_ratio2 = transpose['totalCurrentLiabilities']
        debt_to_assets1 = transpose['otherCurrentAssets']
        debt_to_assets2 = transpose['totalAssets']
        st.write('***Debit Assets:*** Total Debit / Total Assets',
                 (debt_to_assets1 / debt_to_assets2))
        debt_to_equity1 = transpose['otherCurrentAssets']
        debt_to_equity2 = transpose['totalStockholderEquity']
        st.write(
            '***Debit to Equity:*** Total Debit / Total Stock Holders Equity',
            (debt_to_equity1 / debt_to_equity2))
        ROE1 = transpose_income['netIncome']
        ROE2 = transpose_balance['totalStockholderEquity']
        st.write(
            '***Return On Equity ROE:*** Net Income / (Total Stock Holder Equity + Total Stock Holder Equity)/2',
            (ROE1 / ((ROE2 + ROE2) / 2)))
        ROA1 = transpose_income['netIncome']
        ROA2 = transpose_balance['totalAssets']
        st.write('***Return On Assets:*** Net Income / Total Assets',
                 (ROA1 / ROA2))

    company_simulation = st.sidebar.checkbox("Monte Carlo Simulation")
    if company_simulation:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Monte Carlo Simulation Price</h1>",
            unsafe_allow_html=True)
        st.write(
            """Monte Carlo Simulation project future price for the stocks. """)
        yahoo_financials = YahooFinancials(ticker)
        price = yahoo_financials.get_current_price()
        st.write('***Current Price:***', price)
        marketcap = yahoo_financials.get_market_cap()
        st.write('***Market Capital***', marketcap)
        income_balance = si.get_income_statement(ticker)
        transpose_income = income_balance.transpose()
        revenue = transpose_income['totalRevenue']
        st.write('***Price to sales:*** (Market Capital / Revenue',
                 marketcap / revenue)
        price_to_earnings = transpose_income['netIncome']
        st.write('***Price to Earnings:*** (Market Capital/ Net Income',
                 marketcap / price_to_earnings)
        balance_income = si.get_balance_sheet(ticker)
        transpose_balance = balance_income.transpose()
        price_to_book = transpose_balance['totalStockholderEquity']
        st.write('***Price to book:*** (marketcap/Total Stock Holders Equity',
                 marketcap / price_to_book)
        start = st.date_input("Please enter date begin Analysis: ")
        price = yf.download(ticker, start=start, end=None)['Close']
        returns = price.pct_change()
        last_price = price[-1]
        num_simulations = 1000
        num_days = 252
        num_simulations_df = pd.DataFrame()
        for x in range(num_simulations):
            count = 0
            daily_vol = returns.std()
            price_series = []
            price = last_price * (1 + np.random.normal(0, daily_vol))
            price_series.append(price)
            for y in range(num_days):
                if count == 251:
                    break
                price = price_series[count] * (1 +
                                               np.random.normal(0, daily_vol))
                price_series.append(price)
                count += 1
            num_simulations_df[x] = price_series
        fig = plt.figure()
        plt.title('Monte Carlo Simulation')
        plt.plot(num_simulations_df)
        plt.axhline(y=last_price, color='r', linestyle='-')
        plt.xlabel('Day')
        plt.ylabel('Price')
        st.set_option('deprecation.showPyplotGlobalUse', False)
        st.pyplot()
        st.write('Price Series Predict: ', num_simulations_df)
    # company_general = st.sidebar.checkbox("Quick_Ratio")
    # if company_general:
    #     st.subheader("""**Quick Ratio**""")
    #     balance=si.get_balance_sheet(ticker)
    #     transpose=balance.transpose()
    #     quick_ratio1 = transpose['otherCurrentAssets']
    #     quick_ratio2 = transpose['inventory']
    #     quick_ratio3 = transpose['otherCurrentLiab']
    #     quick_ratio = ((quick_ratio1-quick_ratio2)/quick_ratio3)
    #     if not quick_ratio2:
    #         st.write("No data available")
    #     else:
    #         st.write('(***Quick Ratio:*** CurrentAssets - Inventory)/Current Liabilities)', (quick_ratio1-quick_ratio2)/quick_ratio3)
    company_hist = st.sidebar.checkbox("Cash Flow")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Cash Flow</h1>",
            unsafe_allow_html=True)
        display_cash = si.get_cash_flow(ticker)
        if display_cash.empty == True:
            st.write("No data available")
        else:
            st.write(display_cash)
    company_hist = st.sidebar.checkbox("Income Statement")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Income Statement</h1>",
            unsafe_allow_html=True)
        display_income_stat = si.get_income_statement(ticker)
        if display_income_stat.empty == True:
            st.write("No data available")
        else:
            st.write(display_income_stat)
    company_hist = st.sidebar.checkbox("Balance Sheet")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Balance Sheet</h1>",
            unsafe_allow_html=True)
        display_balance = si.get_balance_sheet(ticker)
        if display_balance.empty == True:
            st.write("No data available")
        else:
            st.write(display_balance)
    company_hist = st.sidebar.checkbox("Quote Table")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Quote Table</h1>",
            unsafe_allow_html=True)
        display_table = si.get_quote_table(ticker, dict_result=False)
        if display_table.empty == True:
            st.write("No data available")
        else:
            st.write(display_table)
        quote_table = si.get_quote_table(ticker)
        t = quote_table["Forward Dividend & Yield"]
        st.write('Forward Dividend & Yield:', t)
        display_capital = si.get_quote_table(ticker)["Market Cap"]
        st.write('Market Capital', display_capital)
    company_hist = st.sidebar.checkbox("Call Option")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Call Option</h1>",
            unsafe_allow_html=True)
        c = ops.get_calls(ticker)
        transpose = c.transpose()
        st.write(transpose)
Example #8
0
    def run(self):
        tickers = ['ATVI', 'GOOGL', 'AMED', 'CHWY', 'C', 'CRWD', 'FB', 'FTHM', 'VEEV']
        today = date.today()
        writeToday = str(today)
        writeToday = writeToday + ".txt"
        outF = open(writeToday, "w")
        for i in tickers:
            ticker = "$" + i + ":"
            addedDate = getBuyDate(ticker)
            #get market cap + stock price
            yearold = today.year - 1
            yago = datetime.date(yearold, today.month, today.day)
            stock = web.DataReader(i, 'yahoo', yago, today)
            outF.write("\n\nDISPLAYING DATA FOR " + ticker)
            outF.write("\n\tAdded to the portfolio on: " + addedDate.strftime('%m/%d/%Y'))
            outF.write("\n\tShare price as of "+ today.strftime('%m/%d/%Y') + " for "+ ticker + " ${0:.2f}".format(stock['Close'][-1])+ " per share")
            market_cap = int(data.get_quote_yahoo(i)['marketCap'])
            outF.write("\n\tMarket cap is: ${:,}".format(market_cap))
            yahoo_financials = YahooFinancials([i])

            #get dividend yield
            dividend_yield = str(yahoo_financials.get_dividend_yield())
            dividend_yield = dividend_yield[(len(i) + 5):len(dividend_yield) - 1]
            if (dividend_yield == "None"):
                dividend_yield = 0.00
            dividend_yield = float(dividend_yield) * 100
            outF.write("\n\tDividend yield: "+"{0:.4g}".format(dividend_yield)+ "%")

            #Get daily return
            stock['Daily Return'] = stock['Close'].pct_change(1)
            daily_return = float(stock['Daily Return'][-1]) * 100
            outF.write("\n\tDaily return as of " + today.strftime('%m/%d/%Y') + "is: " + "{0:.3f}".format(daily_return) + "%")

            #Get week to date return
            lastMonday = today - datetime.timedelta(days=today.weekday())
            weekToDate = web.DataReader(i, 'yahoo', lastMonday, today)
            firstPrice = float(weekToDate['Open'][0])
            lastPrice = float(weekToDate['Close'][-1])
            weekToDateReturn = (lastPrice/firstPrice - 1) * 100
            #weekToDate['Daily Return'] = weekToDate['Close'].pct_change(1)
            #weekToDate['Cumulative Return'] = ((1 + weekToDate['Daily Return']).cumprod() - 1) * 100
            #returnWeekly =  float(weekToDate['Cumulative Return'][1])
            outF.write("\n\tWeek-to-date return: "+"{0:.4g}".format(weekToDateReturn)+ "%")

            #get month to date return
            first_day_of_month = today.replace(day=1)
            monthToDate = web.DataReader(i, 'yahoo', first_day_of_month, today)
            firstPrice = float(monthToDate['Open'][0])
            lastPrice = float(monthToDate['Close'][-1])
            monthToDateReturn = (lastPrice/firstPrice - 1) * 100
            outF.write("\n\tMonth-to-date return: " + "{0:.4g}".format(monthToDateReturn)+ "%")

            #get trailing month change
            if today.month == 3 and today.day > 28:
                day = 28
            else:
                day = today.day
            if today.month == 1:
                year = today.year - 1
                month = 12
            else:
                year = today.year
                month = today.month - 1
            lastMonth = datetime.date(year, month, day)
            trailingMonth = web.DataReader(i, 'yahoo', lastMonth, today)
            firstPrice = float(trailingMonth['Open'][0])
            lastPrice = float(monthToDate['Close'][-1])
            trailingMonthReturn = (lastPrice/firstPrice - 1) * 100
            outF.write("\n\tTrailing month return: "+"{0:.5g}".format(trailingMonthReturn)+ "%")

            #get YTD return
            firstDay = datetime.date(today.year, 1, 4)
            yearToDate = web.DataReader(i, 'yahoo', firstDay, today)
            firstPrice = float(yearToDate['Open'][0])
            lastPrice = float(yearToDate['Close'][-1])
            yearToDateReturn = (lastPrice/firstPrice - 1) * 100
            outF.write("\n\tYear-to-date return: {0:.3g}".format(yearToDateReturn)+ "%")

            #get percent down from 52 week high
            yearAgo = datetime.date(today.year - 1, 1, 1)
            oneYear = web.DataReader(i, 'yahoo', yearAgo, today)
            high = float(oneYear['High'][0])
            count = int(oneYear['High'].count())
            for j in range (1,count):
                if float(oneYear['High'][j]) > high:
                    high = float(oneYear['High'][j])
            priceToday = float(oneYear['Close'][-1])
            down52wk = (high/priceToday - 1) * 100
            outF.write("\n\tPercent down from 52-week-high is: {0:.5g}".format(down52wk) + "%")

            # get percent down from peak since buy
            buyDate = getBuyDate(ticker)
            holdingPeriod = web.DataReader(i, 'yahoo', buyDate, today)
            peakHigh = float(holdingPeriod['High'][0])
            count = int(holdingPeriod['High'].count())
            for j in range(1, count):
                 if float(holdingPeriod['High'][j]) > peakHigh:
                     peakHigh = float(holdingPeriod['High'][j])
            priceToday = float(holdingPeriod['Close'][-1])
            downPeak = (peakHigh / priceToday - 1) * 100
            outF.write("\n\tPercent down from peak since purchase is: {0:.5g}".format(downPeak) + "%")

            #get 50 day SMA
            stock['SMA10'] = talib.MA(stock['Close'].values, timeperiod=10, matype=0)
            SMA10 = float(stock['SMA10'][-1])
            stock['SMA50'] = talib.MA(stock['Close'].values, timeperiod=50, matype=0)
            SMA50 = float(stock['SMA50'][-1])
            if SMA10 > SMA50:
                outF.write("\n\tThe SMA10 is: " + "${0:.5g}, ".format(SMA10) + " which is above the SMA50 of: ${0:.5g}".format(SMA50))
            elif SMA10 == SMA50:
                outF.write("\n\tThe SMA10 is:" + "${0:.5g}".format(SMA10) + "which is equal the SMA50 of: ${0:.5g}".format(SMA50))
            else:
                outF.write("\n\tThe SMA10 is:"+ "${0:.5g}".format(SMA10)+ "which is below the SMA50 of: ${0:.5g}".format(SMA50))

            #get the RSI
            stock['RSI'] = talib.RSI(stock['Close'].values)
            rsiVal = float(stock['RSI'][-1])
            outF.write("\n\tThe RSI is "+ "{0:.5g}".format(rsiVal))

            #get the MACD
            stock['MACD'], stock['MACDsignal'], stock['MACDhist'] = talib.MACD(stock["Close"], fastperiod=12, slowperiod=26, signalperiod=9)
            fig, axes = plt.subplots(2, 1)
            stock[['MACD', 'MACDsignal', 'MACDhist']].plot(ax=axes[1], grid=True)
            plt.legend(loc='best', shadow=True)
            symbol = ticker + " MACD graph"
            plt.title(symbol)
            plt.show()
            print("\tDone with", i)
            time.sleep(8)
Example #9
0
pe_ratios = []
market_caps = []
dividend_yields = []
sectors = []
industries = []
names = []

# For each company in the S&P 500 list, extract its PE ratio and market cap and add each of them to its respective list
for ticker in companyTickers:
    yahoo_financials = YahooFinancials(ticker)
    print('Downloading data for ' + ticker + '...')
    pe_ratios.append(yahoo_financials.get_pe_ratio())
    market_caps.append(yahoo_financials.get_market_cap())
    try:
        dividend_yields.append(
            str(format(yahoo_financials.get_dividend_yield() * 100, ".2f")) +
            '%')
    except:
        dividend_yields.append(str(yahoo_financials.get_dividend_yield()))
    sectors.append(yahoo_data.getSector(ticker))
    industries.append(yahoo_data.getIndustry(ticker))
    names.append(yahoo_data.getName(ticker))

companiesData['Name'] = names
companiesData['Sector'] = sectors
companiesData['Industry'] = industries
companiesData['P/E'] = pe_ratios
companiesData['Market Cap'] = market_caps
companiesData['Dividend Yield'] = dividend_yields

#print(companiesData)