Esempio n. 1
0
    def load_tickers(self, cur, conn):

        self.df_ticker = pd.DataFrame()
        self.nasdaq = si.tickers_nasdaq()
        self.sp500 = si.tickers_sp500()
        self.dow = si.tickers_dow()
        self.other = si.tickers_other()

        self.tickers = list(set([*nasdaq, *sp500, *dow, *other]))

        self.df_ticker['ticker'] = self.tickers
        self.df_ticker.replace("", float("NaN"), inplace=True)
        self.df_ticker.dropna(subset=["ticker"], inplace=True)

        self.df_ticker['isdow'] = self.df_ticker['ticker'].isin(self.dow)
        self.df_ticker['issp500'] = self.df_ticker['ticker'].isin(self.sp500)
        self.df_ticker['isnasdaq'] = self.df_ticker['ticker'].isin(self.nasdaq)

        self.insert = [
            list(row) for row in self.df_ticker.itertuples(index=False)
        ]

        self.SQL_Ticker_insert = """ INSERT INTO public.tickers(ticker,isdow, isnasdaq, issp500) VALUES (%s,%s,%s,%s) ON CONFLICT DO NOTHING"""
        self.cur.executemany(self.SQL_Ticker_insert, self.insert)
        self.conn.commit()
        self.rowcount = self.cur.rowcount

        return None
Esempio n. 2
0
    def listStock_gen(self, combobox):
        # gather stock symbols from major US exchanges
        df1 = pd.DataFrame( si.tickers_sp500() )
        df2 = pd.DataFrame( si.tickers_nasdaq() )
        df3 = pd.DataFrame( si.tickers_dow() )
        df4 = pd.DataFrame( si.tickers_other() )

        # convert DataFrame to list, then to sets
        sym1 = set( symbol for symbol in df1[0].values.tolist() )
        sym2 = set( symbol for symbol in df2[0].values.tolist() )
        sym3 = set( symbol for symbol in df3[0].values.tolist() )
        sym4 = set( symbol for symbol in df4[0].values.tolist() )

        # join the 4 sets into one. Because it's a set, there will be no duplicate symbols
        symbols = set.union( sym1, sym2, sym3, sym4 )

        # Some stocks are 5 characters. Those stocks with the suffixes listed below are not of interest.
        my_list = ['W', 'R', 'P', 'Q']
        del_set = set()
        sav_set = set()

        for symbol in symbols:
            if len( symbol ) > 4 and symbol[-1] in my_list:
                del_set.add( symbol )
            else:
                sav_set.add( symbol )
        for ticker in sav_set:
            combobox.addItem(str(ticker))
def get_tickers():
    '''
    Get ticker symbols for stocks listed on major stock exchanges. 
    At time of writing, this function retrieves 9899 stock symbols
    '''

    print("Retrieving Stock Symbols...")

    dow_tickers = stock_info.tickers_dow()
    nasdaq_ticker = stock_info.tickers_nasdaq()
    sp500_ticker = stock_info.tickers_sp500()
    other_tickers = stock_info.tickers_other()

    all_tickers = list(
        set(dow_tickers + nasdaq_ticker + sp500_ticker + other_tickers))
    print(f"\nTotal number of stock symbols retrieved: {len(all_tickers)}")

    tickers_dict = {
        'DOW': dow_tickers,
        'NASDAQ': nasdaq_ticker,
        'SP500': sp500_ticker,
        'others': other_tickers
    }
    for exchange_name, ticker_list in tickers_dict.items():
        print(f"\t{exchange_name}: {len(ticker_list)}")

    return all_tickers
Esempio n. 4
0
def yahoo_finance():

    #dict_info = si.get_analysts_info('nflx')

    #df_info = pd.DataFrame.from_dict(dict_info, orient='index')

    #pprint.pprint(dict_info)

    symbols = si.tickers_dow()

    return str(symbols)
Esempio n. 5
0
    def get_dow_tickers(self):
        """
        Get the Dow stocks tickers.

        Returns
        -------
        tickers_dow : list of str
            Dow tickers

        """
        tickers_dow = ys.tickers_dow()

        return tickers_dow
Esempio n. 6
0
def tickers(request):
    dow = si.tickers_dow()
    nasdaq = si.tickers_nasdaq()
    sp500 = si.tickers_sp500()
    other = si.tickers_other()

    all = json.dumps({
        'dow': dow,
        'nasdaq': nasdaq,
        'sp500': sp500,
        'other': other
    })

    return HttpResponse(all)
Esempio n. 7
0
def get_US_price(start_date, end_date):
    """
    Download US stocks prices.

    Parameters
    ----------
    start_date : string
        example : '2000-01-01'.
    end_date : string
        example : '2019-12-31'.

    Returns
    -------
    total_df : pd.DataFrame
        Stocks prices from start_date to end_date.

    """
    dow_list = si.tickers_dow()
    sp500_list = si.tickers_sp500()
    nasdaq_list = si.tickers_nasdaq()
    other_list = si.tickers_other()

    ticker = dow_list + sp500_list + nasdaq_list + other_list
    ticker = [ticker[i] for i in range(len(ticker)) if not ticker[i] in ticker[:i]]

    ticker = pd.DataFrame(ticker, columns=['Ticker'])
    
    for num, code in enumerate(ticker['Ticker']):
        try:
            print(num, code)
            time.sleep(1)
            try:
                df = fdr.DataReader(code, start_date, end_date)
                df = df['Close']
                df = pd.DataFrame(df)
                df.columns = [code]
            except Exception as e:
                print(e, 'Error in Ticker', code)
                continue
            if num == 0:
                total_df = df
            else:
                total_df = pd.merge(total_df, df, how='outer', right_index=True, left_index=True)
        except ValueError:
            continue
        except KeyError:
            continue
    total_df.to_csv(r'C:\Users\Samsung\Downloads\quant\Python\data\US_price.csv')
    return total_df
Esempio n. 8
0
def get_symbols(index):

    symbols = []

    if index == CFG.INDEX_DOW:
        symbols = si.tickers_dow()
    elif index == CFG.INDEX_NASDAQ:
        symbols = si.tickers_nasdaq()
    elif index == CFG.INDEX_SP500:
        symbols = si.tickers_sp500()

    return {
        'fulfillmentText': str(symbols),
        'displayText': '25',
        'source': 'webhookdata',
        'platform': 'FACEBOOK',
    }
Esempio n. 9
0
def update_tickers(path, name):
    '''
    Gets a list of tickers from the yahoo finance database and saves the list to a .csv file under a given directory and name
    :param path: string, must  be denoted as path\\to\\main\\folder\\
    :param name: string, will be the name of the .csv  file saved, must not have any file denotion in it
    :return: saves a list of tickers to path\\name.csv
    '''
    sources, tickers = [
        stock_info.tickers_dow(),
        stock_info.tickers_nasdaq(),
        stock_info.tickers_other(),
        stock_info.tickers_sp500()
    ], []
    for source in sources:
        for ticker in source:
            if ticker not in tickers:
                tickers.append(ticker)
    pd.DataFrame(tickers).to_csv(path + name + '.csv')
Esempio n. 10
0
    def __init__(self, date=None):

        self.ticker = "AAPL"
        self.date = date
        self.expiry_date = None
        self.underlying = self.get_underlying_price()
        self.tickers_select = [{
            "label": i,
            "value": i
        } for i in stock_info.tickers_dow()] + [{
            "label": "SPY",
            "value": "SPY"
        }]
        self.calls_formatted = None
        self.puts_formatted = None
        self.live_price = self.live_prices_released()

        if self.live_price:
            self.live_price_comment = ''
            self.current_date = datetime.datetime.now()
        else:
            self.live_price_comment = "* Prices displayed are not current. Live prices released around 3pm GMT"
            self.current_date = datetime.datetime(2021, 1, 7)
Esempio n. 11
0
def main():
    initialize()
    parser = build_parser()
    options = parser.parse_args()

    if options.mode == "train":
        import finrl.autotrain.training

        finrl.autotrain.training.train_one()
    elif options.mode == "download_data":
        print('Download Data Begin')

        dow_30 = si.tickers_dow()
        # ETF
        #dftmp = pd.read_csv('data/etf_tom.csv',index_col=0)
        #dow_30 = dftmp.tic.unique()

        # DOW30

        dftmp = pd.read_csv('data/tom_dow_done_data.csv', index_col=0)
        dow_30 = dftmp.tic.unique()
        #dow_30 = ['DSS','AAPL','INFY']
        #dow_30 = ['^DJI']
        price_data = {ticker: si.get_data(ticker) for ticker in dow_30}
        df = reduce(lambda x, y: x.append(y), price_data.values())
        df.reset_index(inplace=True)
        df = df.rename(columns={'index': 'date', 'ticker': 'tic'})

        fe = FeatureEngineer(use_technical_indicator=True,
                             use_turbulence=False,
                             user_defined_feature=False)

        df = fe.preprocess_data(df)
        now = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
        df.to_csv(config.DATA_SAVE_DIR + "/" + "dow30_" + now + ".csv",
                  index=False)
        print('Download Complete')
Esempio n. 12
0
def format_ticker():
    # this function allows a user to pick a stock or get a random stock

    # These the sets are formed by importing the tickers from Yahoo API
    dow_set = set(yf.tickers_dow())
    snp_set = set(yf.tickers_sp500())

    # Combine both sets to create a random set of all companies in the S&P 500 and the dow jones
    sp_dow = dow_set.union(snp_set)

    test = True
    print("Please type 'quit' to exit the program at any time")
    print("Please type 'random' to get a random stock to analyze")
    while test:
        input_1 = str(
            input(
                "Please enter a ticker of your choosing, with no quotation marks:"
            ))
        # allows the user to quit
        if input_1.upper().strip() == "QUIT":
            print("you have opted to quit the program, goodbye!")
            test = False
        # this allows the user get a random stock from the dop and SP set
        elif input_1.upper().strip() == "RANDOM":
            # pops a string from the set
            a = sp_dow.pop()
            print(a)
            # this ticker calls the format object function which is the main function
            format_object(a)
            test = False
        # will allow the function to run again if the user enters a string longer than 8 elements
        # no stock will no 8 strings long
        elif len(input_1) < 8:
            print(input_1)
            # this ticker calls the format object function which is the main function
            format_object(input_1)
            test = False
Esempio n. 13
0
def getOptionsData(personalRiskTolerance, budget, printOutput = 'True'):
    '''
    get the up to date stock options pareto.
    Currently hardcoded for the DOW stocks
    inputs: 
        personalRiskTolerance - risk level - number between 0 and 0.9
        budget - Number - larger than 2000
        printOutput - bool to determine whether print statements show
    outputs:
       stockPareto DataFrame (all options within the budget)
       bestPick DataFrame (highest value return within risk tolerance)
    hardcoded:
       options date - 5/15/2020
       stocks to pick from: All DOW stocks
    '''
    
    # date selection
    today = datetime.today()
    optionsDate = datetime(2020,5,15)
    t = ((optionsDate - today).days + ((optionsDate - today).seconds/86400))/365
    daysLeft = (optionsDate - today).days
    hoursLeft = int((optionsDate - today).seconds/3600)
    if printOutput:
        print('\nOptions will expire in approximately {} days and {} hours'.format(daysLeft,hoursLeft))
    stockPareto = pd.DataFrame()

    if printOutput:
        print('Pulling stock data...\n')

    # initial data capture and processing
    for stock in stock_info.tickers_dow():

        # checks if there is an option during the particular week.
        try:
            individualOptionsData = options.get_puts(stock,date=optionsDate)
            # capture stock, current price for each stock
            individualOptionsData['Stock Name'] = stock
            individualOptionsData['Current Price'] = stock_info.get_live_price(stock)
            # IV formatting to a number
            individualOptionsData['IV']= individualOptionsData['Implied Volatility'].str.slice_replace(-1,repl='').astype(float)/100

        # if not, skip the ticker
        except:
            if printOutput:
                print('No data from {}'.format(stock))
            continue

        # if successful at obtaining options data, fill DataFrame stockPareto with the values
        stockPareto = stockPareto.append(individualOptionsData)
        if printOutput:
            print('Data from {} collected'.format(stock))

    if printOutput:
        print('Data Capture Complete!')

    # bool logic to make sure options are worth investing in
    beingTraded = stockPareto['Volume'] != '-'
    asksExist = stockPareto['Ask'] != '-'
    bidsExist = stockPareto['Bid'] != '-'

    # filtering by bool logic
    stockPareto = stockPareto[beingTraded & asksExist & bidsExist]

    ####################################################
    ### formatting of key variables in the DataFrame ###
    ####################################################

    # POP derived from Black-Scholes model
    stockPareto['POP'] = 100*stats.norm.cdf((np.log(stockPareto['Current Price'] / stockPareto['Strike'] ) +
                                         ( (stockPareto['IV']**2) /2)*t) / (stockPareto['IV']*np.sqrt(t)))
    stockPareto['Strike'] = stockPareto['Strike'].astype(float)
    stockPareto['Bid'] = stockPareto['Bid'].astype(float)
    stockPareto['Ask'] = stockPareto['Ask'].astype(float)

    # determine number of each contract that is in budget
    # potential gain is the average contract selling price ~ (bid / ask) * 100
    # potential gain multiple contracts - potential gain * number of contracts that can be sold within budget
    stockPareto['contractsInBudget'] = np.floor(budget/(stockPareto['Strike']*100))
    stockPareto['Potential Gain'] = ((stockPareto['Ask'] + stockPareto['Bid'])/2) * 100
    stockPareto['Potential Gain Multiple Contracts'] = stockPareto['Potential Gain'] * stockPareto['contractsInBudget']
    ###########################
    ### plotting the pareto ###
    ###########################

    inBudget = stockPareto['contractsInBudget'] > 0
    isInteresting = stockPareto['Bid'] != 0
    stockPareto = stockPareto[inBudget & isInteresting]
    stockPareto = stockPareto.set_index('Contract Name')

    # this is the field which will show in the interactive plot
    stockPareto['printString'] = ('Stock: ' + stockPareto['Stock Name']+'\n'
                                  'Strike Price = $'+ round(stockPareto['Strike'],2).astype(str)+'\n'+
                                  'Current Price = $' + round(stockPareto['Current Price'],2).astype(str) + '\n' +
                                  'Potential Gain = $'+ round(stockPareto['Potential Gain Multiple Contracts'],2).astype(str)+'\n' + 
                                  'ROI = ' + round(((stockPareto['Potential Gain Multiple Contracts']/budget) * 100),2).astype(str) + '%\n' +
                                  'Probability of Profit = ' + round(stockPareto['POP'],2).astype(str))
    
    ####################
    ## Best Fit Logic ##
    ####################

    notBelowRisk = stockPareto['POP'] > (personalRiskTolerance*100)
    bestPick = stockPareto[notBelowRisk].sort_values(by='Potential Gain Multiple Contracts',ascending = False)
    bestPick = bestPick.loc[bestPick['Potential Gain Multiple Contracts'].idxmax()]

    if printOutput:
        print('The best OPTION is:')
        print(bestPick)
        
    return stockPareto, bestPick
Esempio n. 14
0
import numpy as np
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
import datetime
from yahoo_fin import stock_info as si

plt.rcParams['figure.figsize'] = (15, 10)

tickers = si.tickers_dow()
individual_stock = input(
    f"Which of the following stocks would you like to backtest \n{tickers}\n:")

num_of_years = 1
start = datetime.date.today() - datetime.timedelta(days=int(365.25 *
                                                            num_of_years))
yf_prices = yf.download(tickers, start=start)

# Individual Stock Strategy
prices = yf_prices['Adj Close'][individual_stock]
rs = prices.apply(np.log).diff(1).fillna(0)

w1 = 5
w2 = 22
ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean()
pos = ma_x.apply(np.sign)

fig, ax = plt.subplots(2, 1)
ma_x.plot(ax=ax[0],
          title=f'{individual_stock} Moving Average Crossovers and Positions')
pos.plot(ax=ax[1])
Esempio n. 15
0
from typing import Optional

import yahoo_fin.stock_info as si

from great_expectations.core.expectation_configuration import ExpectationConfiguration
from great_expectations.execution_engine import PandasExecutionEngine
from great_expectations.expectations.expectation import ColumnMapExpectation
from great_expectations.expectations.metrics import (
    ColumnMapMetricProvider,
    column_condition_partial,
)

DOW_TICKERS_LIST = [t.lower() for t in si.tickers_dow()]


# This method compares a string to the valid Dow Jones ticker
def is_valid_dow_ticker(ticker: str) -> bool:
    return ticker.lower() in DOW_TICKERS_LIST


# This class defines a Metric to support your Expectation.
# For most ColumnMapExpectations, the main business logic for calculation will live in this class.
class ColumnValuesToBeValidDowTicker(ColumnMapMetricProvider):

    # This is the id string that will be used to reference your metric.
    condition_metric_name = "column_values.valid_dow_ticker"

    # This method implements the core logic for the PandasExecutionEngine
    @column_condition_partial(engine=PandasExecutionEngine)
    def _pandas(cls, column, **kwargs):
        return column.apply(lambda x: is_valid_dow_ticker(x))
Esempio n. 16
0
#!/usr/bin/env python3
from yahoo_fin import options, stock_info as si
import random
# commented out bc takes a while to scrape all this data

# get S&P stock tickers
sp500 = si.tickers_sp500()
# get NASDAQ stock tickers
nasdaq = si.tickers_nasdaq()
# get Dow Jones stock tickers
dow = si.tickers_dow()
# get Other stock tickers
others = si.tickers_other()

# Combine all elements into one list
all = sp500 + nasdaq + dow + others
# select random ticker from list
random_ticker = random.choice(all)
# random_ticker = "T"
print(random.choice(["calls","puts"])
Esempio n. 17
0
File: SymbObj.py Progetto: hukf/test
 def dow(self):
     self.symb = si.tickers_dow()
Esempio n. 18
0
def getDowJonesList():
    return si.tickers_dow()
def get_symbols_down_jones():
    """Retrieves Dow Jones Symbols"""
    return tickers_dow()
Esempio n. 20
0
import pandas as pd
import plotly.offline as py
import datetime as dt
import yahoo_fin.stock_info as yf
import plotly.graph_objs as go

Markets = ("NASDAQ", "DOW", "SP500")

Market = input("Select Market Index: ")

while Market not in Markets:
    print("Please Select between DOW, NASDAQ or SP500")
    Market = input("Select Market Index: ")

if Market == "DOW":
    Market = yf.tickers_dow()
    print("Fetching DOW JONES tickers")
elif Market == "SP500":
    Market = yf.tickers_sp500()
    print("Fetching S&P500 tickers")
elif Market == "NASDAQ":
    Market = yf.tickers_nasdaq()
    print("Fetching NASDAQ tickers")
else:
    print("Market Data currently unavailabe")
    Market = input("Select Market Index: ")

Ticker = input("Select Stock: ")

if Ticker in Market:
    print("Fetching Required Data for " + str(Ticker) +
Esempio n. 21
0
import statsmodels.api as sm

key = "PKDMJ3EFG7K6RBAQNPT3"
sec = "gogIZwlzCnbkBbxcdBWPdiUxrrRJDyoPNR88GO4K"

#API endpoint URL
url = "https://paper-api.alpaca.markets"

#api_version v2 refers to the version that we'll use
#very important for the documentation
api = tradeapi.REST(key, sec, url, api_version='v2')

#Init our account var
account = api.get_account()

dow_list = si.tickers_dow()
sp500_list = si.tickers_sp500()
nasdaq_list = si.tickers_nasdaq()
all_tickers = sorted(list(filter(None, set(dow_list + sp500_list + nasdaq_list))))

"""
all_historical = {}
for ticker in all_tickers:
    all_historical[ticker] = si.get_data(ticker)
    print(ticker)

dow_historical = {}
for ticker in dow_list:
    dow_historical = si.get_data(ticker, start_date='1990-01-01', end_date='2020-01-01', interval='1d')
    print(ticker)
Esempio n. 22
0
import urllib.request, urllib.error, urllib.parse
import time
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib
import pylab
import requests
from yahoo_fin import stock_info as si
matplotlib.rcParams.update({'font.size': 9})

evenBetter = si.tickers_dow()


def rsiFunc(prices, n=14):
    deltas = np.diff(prices)
    seed = deltas[:n + 1]
    up = seed[seed >= 0].sum() / n
    down = -seed[seed < 0].sum() / n
    rs = up / down
    rsi = np.zeros_like(prices)
    rsi[:n] = 100. - 100. / (1. + rs)

    for i in range(n, len(prices)):
        delta = deltas[i - 1]  # the diff is 1 shorter

        if delta > 0:
            upval = delta
from pandas_datareader import data as pdr
import yfinance as yf
yf.pdr_override()  # Override yfinance API in order to use Pandas DataReader
import numpy as np
import os

end = datetime.date.today()
end = datetime.datetime(end.year, end.month,
                        end.day)  # to midnight of that day

#Going back 3 years ensures that we can accumulate a 200 day MA for the most recent 100 days
#These are isolated after attaching the 200 day MA
start = (end - relativedelta(years=3))

# return list of Dow tickers
dow_tickers = pd.Series(stock_info.tickers_dow()).unique()
sp_tickers = pd.Series(stock_info.tickers_sp500()).unique()
nasdaq_tickers = pd.Series(stock_info.tickers_nasdaq()).unique()
all_tickers = np.unique(np.hstack((nasdaq_tickers, dow_tickers, sp_tickers)))

indicators = [
    'dma', 'volume_delta', 'close_12_ema', 'close_26_ema', 'macd',
    'macd_9_ema', 'macds', 'macdh'
]


# Functions
# Returns the OCHLV for a stock over a 10 year period
def get_ticker_data(ticker):
    '''Takes a list of stock symbols and appends the open, close,
    high, low and trading day data from Yahoo Finance for that
Esempio n. 24
0
import matplotlib.pyplot as plt
from datetime import date
import yfinance as yf
import pandas as pd
from yahoo_fin import stock_info as si
import mplcursors

symbol1 = "AAPL"
stockOne = yf.Ticker(symbol1)

dailyData = pd.DataFrame(stockOne.history(period="1d", interval="1m"))['Open']
dailyData.index = dailyData.index.strftime("%H:%M:%S")

gainers = pd.DataFrame(si.get_day_gainers())[['Price (Intraday)', '% Change']]
gainers.index = pd.DataFrame(si.get_day_gainers())['Symbol']

losers = pd.DataFrame(si.get_day_losers())[['Price (Intraday)', '% Change']]
losers.index = pd.DataFrame(si.get_day_losers())['Symbol']

active = pd.DataFrame(
    si.get_day_most_active())[['Price (Intraday)', '% Change']]
active.index = pd.DataFrame(si.get_day_most_active())['Symbol']

print(pd.DataFrame(si.tickers_dow()))
Esempio n. 25
0
 days = 0
 constDate = str("0001") + "-" + str("01") + "-" + str("01")
 if args.days:
     days = int(args.days)
 if args.processes:
     noOfProcesses = int(args.processes)
 else:
     noOfProcesses = 10
 if args.filename:
     fileName = args.filename + ".xlsx"
 else:
     fileName = "insider_trading.xlsx"
 if args.stocklist:
     l1 = args.stocklist.split(',')
 else:
     l1 = si.tickers_sp500() + si.tickers_nasdaq() + si.tickers_other() + si.tickers_dow() 
     l1 = list(set(l1))
     l1.sort()
     l1.pop(0)
     tickerList = []
     for i,ticker in enumerate(l1):
         if not re.search(r"\$", ticker):
             tickerList.append(ticker)
     l1 = tickerList
 if args.insidersales:
     value = int(args.insidersales)
     if value > 1:
         print("ERROR insider sales value can only be 0 or 1 and you have passed %d" %(value))
         sys.exit(1)
     else:
         insiderSales = value
Esempio n. 26
0
def get_dow_tickers():
    return si.tickers_dow()
Esempio n. 27
0
def query_tickers(industry):
    # load tickers
    dow = si.tickers_dow()
    dow_set = set(dow)
    if industry == "Business & Commerce":
        companies = [
            "AMZN", "TSLA", "HD", "LOW", "MCD", "SBUX", "NKE", "WMT", "COST",
            "PG", "PEP", "KO"
        ]
        companies_set = set(companies)
        non_dupes = list(companies_set - dow_set)
        tickers = dow + non_dupes
    elif industry == "Healthcare Professions & Pharmacology Programs":
        companies = [
            "JNJ", "MRK", "ABBV", "PFE", "LLY", "AMGN", "GILD", "ABT", "TMO",
            "DHR", "REGN", "UNH"
        ]
        companies_set = set(companies)
        non_dupes = list(companies_set - dow_set)
        tickers = dow + non_dupes
    elif industry == "Biological & Biomedical Sciences":
        companies = [
            "AMZN", "TSLA", "HD", "LOW", "MCD", "SBUX", "NKE", "WMT", "COST",
            "PG", "PEP", "KO"
        ]
        companies_set = set(companies)
        non_dupes = list(companies_set - dow_set)
        tickers = dow + non_dupes
    elif industry == "Engineering & Technology":
        companies = [
            "AMAT", "TSLA", "ADBE", "CSCO", "NVDA", "AVGO", "IBM", "AMD",
            "TXN", "QCOM", "INTC", "CRM"
        ]
        companies_set = set(companies)
        non_dupes = list(companies_set - dow_set)
        tickers = dow + non_dupes
    elif industry == "Energy & Infrastructure":
        companies = [
            "XOM", "CVX", "COP", "EOG", "PSX", "MPC", "SPG", "NEE", "DUK",
            "LIN", "APD", "SRE"
        ]
        companies_set = set(companies)
        non_dupes = list(companies_set - dow_set)
        tickers = dow + non_dupes
    elif industry == "Communication, Journalism & Related Programs":
        companies = [
            "GOOGL", "FB", "T", "VZ", "TMUS", "ATVI", "NFLX", "DIS", "CMCSA",
            "CHTR", "EA", "LYV"
        ]
        companies_set = set(companies)
        non_dupes = list(companies_set - dow_set)
        tickers = dow + non_dupes
    else:
        tickers = dow

    yahoo_recommendations = []

    # call request from yahoo
    for each_ticker in tickers:
        print("Now Querying Recommendation for: " + each_ticker)
        query_a = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/'
        query_b = '?formatted=true&crumb=swg7qs5y9UP&lang=en-US&region=US&' \
                  'modules=upgradeDowngradeHistory,recommendationTrend,' \
                  'financialData,earningsHistory,earningsTrend,industryTrend&' \
                  'corsDomain=finance.yahoo.com'

        request_url = query_a + each_ticker + query_b
        response = requests.get(request_url)

        # if response failed
        if not response.ok:
            recommendation = 0

        # response success
        try:
            result = response.json()['quoteSummary']['result'][0]
            recommendation = result['financialData']['recommendationMean'][
                'fmt']
        except:
            recommendation = 0

        yahoo_recommendations.append(recommendation)

    # converting to a pandas dataframe
    data = {'Ticker': tickers, 'Recommendations': yahoo_recommendations}
    df = pd.DataFrame(data)
    df['Recommendations'] = pd.to_numeric(df['Recommendations'])

    # sort and filter dataframe
    df = df[df.Recommendations != 0]
    df.sort_values(by=['Recommendations'], ascending=True)

    # filter based on recommendation value
    df_buy = df[df.Recommendations <= 1.5]
    df_sell = df[df.Recommendations >= 4.5]
    df_hold = df[df.Recommendations == 3]

    # combine dataframes (for experienced investor who understands buys/sells/holds)
    df_final = pd.concat([df_hold, df_buy, df_sell])
    df_final.reset_index(level=0, inplace=True)

    if df_final.empty:
        df_buy = df[df.Recommendations <= 2]
        df_sell = df[df.Recommendations >= 4]
        df_hold = df[df.Recommendations == 3]

        df_final = pd.concat([df_hold, df_buy, df_sell])
        df_final.reset_index(level=0, inplace=True)

    return df_final
Esempio n. 28
0
 print(80*'=')
 print('Choose the index analysis:Our analysis will be made on stocks composites of index you want,type:(DOW has the smallest index with 30 components)') 
 print('SP500  : for S&P 500 composites')
 print('DOW    : for DOW JONES composites')
 print('NASDAQ : for NASDAQ composites')
 print(80*'=')
 print('What is your choice?')
 stocklist=input('NASDAQ/DOW/SP500 : ')
 while stocklist!='NASDAQ' and stocklist!='DOW' and stocklist!='SP500' :
     print('Please choose the right option')
     stocklist=input()
     
 if stocklist=='NASDAQ':
     stocklist=si.tickers_nasdaq()
 elif stocklist=='DOW':
     stocklist=si.tickers_dow()
 else:
     stocklist=si.tickers_sp500()
     
 start_date=date.today()-timedelta(days=360)
 end_date=date.today()
 
 print('Do you want to use the dividend yields or not(Y/N)?')
 yn=input()
 while yn!='Y' and yn!='N':
     print('You can type Y or N')
     yn=input()
 
 print('Do you want to use the pricing for American Options or European ones?(type A or E)')
 opt=input('You can type A or E : ')
 while opt!='A' and opt!='E':
Esempio n. 29
0
import pandas as pd
from sklearn.cluster import KMeans
from math import sqrt
import pylab as pl
import numpy as np
import yfinance as yf
import datetime as dt
import requests
from pandas_datareader import data as pdr
from yahoo_fin import stock_info as si

#Loading the data
yf.pdr_override()
stocks = si.tickers_dow()
stocks = stocks[10:30]
start = dt.datetime(2010, 1, 1)
now = dt.datetime.now()

data = pdr.get_data_yahoo(stocks, start, now)['Close']

#Calculating annual mean returns and variances
returns = data.pct_change().mean() * 252
variance = data.pct_change().std() * sqrt(252)
returns.columns = ["Returns"]
variance.columns = ["Variance"]

#Concatenating the returns and variances into a single data-frame
ret_var = pd.concat([returns, variance], axis=1).dropna()
ret_var.columns = ["Returns", "Variance"]

X = ret_var.values  #Converting ret_var into nummpy array