Exemplo n.º 1
0
    def fetch_data(self):
        print("fetching")
        stock = self.stock
        start_date = datetime.strftime(self.date - timedelta(days=500), '%Y-%m-%d')
        end_date = datetime.strftime(self.date, '%Y-%m-%d')
        print("downloading stock data...")
        try:
            share_getter = Share(stock)
            if stock[-1] == 'L': comparitor = Share('^FTSE')
            else: comparitor = Share(share_getter.get_stock_exchange())
        except:
            print("network not available")
            comparitor = None

        df, dfb = pd.DataFrame(), pd.DataFrame()
        try:
            df = df.from_dict(share_getter.get_historical(start_date, end_date))
            dfb = dfb.from_dict(comparitor.get_historical(start_date, end_date))
            print("download complete: fetched", len(df.index) +
                len(dfb.index), "records")
            df = df.drop(['Symbol'], axis=1)
            df['comparitor'] = dfb['Adj_Close']
            df['Adj_Close'] = pd.to_numeric(df['Adj_Close'], errors='ignore')
            df['Volume'] = pd.to_numeric(df['Volume'], errors='ignore')
            df['comparitor'] = pd.to_numeric(df['comparitor'], errors='ignore')
            return df
        except Exception as e:
            print("error in fetch_data", e)
            return df
Exemplo n.º 2
0
 def _fetch_data(self, base_date, end_date):
     """
     helper function which retrieves data from the yahoo finance api
     """
     print("downloading stock data...")
     try:
         share_getter = Share(self.stock)
         if self.stock[-1] == 'L': comparitor = Share('^FTSE')
         else: comparitor = Share(share_getter.get_stock_exchange())
     except:
         print("network not available")
         comparitor = None
     df, dfb = pd.DataFrame(), pd.DataFrame()
     try:
         df = df.from_dict(share_getter.get_historical(base_date, end_date))
         dfb = dfb.from_dict(comparitor.get_historical(base_date, end_date))
         print("download complete: fetched",
               len(df.index) + len(dfb.index), "records")
         df = df.drop(['Symbol'], axis=1)
         df['comparitor'] = dfb['Adj_Close']
         df['Adj_Close'] = pd.to_numeric(df['Adj_Close'], errors='ignore')
         df['comparitor'] = pd.to_numeric(df['comparitor'], errors='ignore')
         df['comparitor'] = df['Adj_Close'] / df['comparitor']
         df['roll_av'] = df['Adj_Close'].rolling(center=False,
                                                 window=7).mean()
         return df
     except Exception as e:
         print("error in fetch_data", e)
         return df
Exemplo n.º 3
0
def get_symbol_exchange(sym):
    """
    Download the stock exchange sym from Yahoo Finance.
    YQL is required.
    """
    stock = Share(sym)
    return stock.get_stock_exchange()
def stock_summary(request, symbol=None):
    if symbol == None:
        symbol = request.POST['symbol']

    current_stock = Stock()
    stock = Share(symbol)
    current_stock.symbol = symbol.upper()
    current_stock.price = stock.get_price()
    current_stock.change = stock.get_change()
    current_stock.volume = stock.get_volume()
    current_stock.prev_close = stock.get_prev_close()
    current_stock.stock_open = stock.get_open()
    current_stock.avg_daily_volume = stock.get_avg_daily_volume()
    current_stock.stock_exchange = stock.get_stock_exchange()
    current_stock.market_cap = stock.get_market_cap()
    current_stock.book_value = stock.get_book_value()
    current_stock.ebitda = stock.get_ebitda()
    current_stock.dividend_share = stock.get_dividend_share()
    current_stock.dividend_yield = stock.get_dividend_yield()
    current_stock.earnings_share = stock.get_earnings_share()
    current_stock.days_high = stock.get_days_high()
    current_stock.days_low = stock.get_days_low()
    current_stock.year_high = stock.get_year_high()
    current_stock.year_low = stock.get_year_low()
    current_stock.fifty_day_moving_avg = stock.get_50day_moving_avg()
    current_stock.two_hundred_day_moving_avg = stock.get_200day_moving_avg()
    current_stock.price_earnings_ratio = stock.get_price_earnings_ratio()
    current_stock.price_earnings_growth_ratio = stock.get_price_earnings_growth_ratio()
    current_stock.price_sales = stock.get_price_sales()
    current_stock.price_book = stock.get_price_book()
    current_stock.short_ratio = stock.get_short_ratio()

    date_metrics = []
    url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+symbol+'/chartdata;type=quote;range=1y/csv'
    page = urllib2.urlopen(url).read()
    pagebreaks = page.split('\n')
    for line in pagebreaks:
        items = line.split(',')
        if 'Company-Name:' in line:
            current_stock.company_name = line[13:len(line)]
            current_stock.save()
        if 'values' not in items:
            if len(items)==6:
                hd = HistoricalData(
                    stock_id = Stock.objects.get(id=int(current_stock.id)).id,
                    date = items[0][4:6]+'/'+items[0][6:9]+'/'+items[0][0:4],
                    close = items[1][0:(len(items[1])-2)],
                    high = items[2][0:(len(items[2])-2)],
                    price_open = items[3][0:(len(items[3])-2)],
                    low = items[4][0:(len(items[4])-2)],
                    volume = items[5][0:-6]+","+items[5][-6:-3]+","+items[5][-3:len(items[5])])
                hd.save()
                date_metrics.append(hd)
    del date_metrics[0]
    return render(request, "stock_summary.html", {'current_stock': current_stock, 'date_metrics': date_metrics})
Exemplo n.º 5
0
def get_current_stock_info(stock_short):
    stock_share = Share(stock_short)
    stock_current_info = {}
    stock_current_info['stock_short'] = stock_short
    stock_latest_price = stock_share.get_price()
    stock_current_info['stock_latest_price'] = stock_latest_price
    stock_trade_datetime = stock_share.get_trade_datetime()
    stock_current_info['stock_trade_datetime'] = stock_trade_datetime
    stock_exchange = stock_share.get_stock_exchange()
    stock_current_info['stock_exchange'] = stock_exchange
    stock_company_name = stock_share.get_name()
    stock_current_info['stock_company_name'] = stock_company_name
    return stock_current_info
Exemplo n.º 6
0
    def fetch_stock_price(self, stock_unit_key):
        # Step 1: Make HTTP Call to fetch the Stock Details
        # Step 2: Once received, create it into its corresponding model
        # Step 2.1 : Between the models, exchange packet as a native dictionary, rather as a JSON object

        # Get the share price
        share_item = Share(stock_unit_key)

        if share_item.get_open() is None:
            return

        share_item_dict = share_item.data_set

        st_model = StockModel()
        st_model.stock_unit = stock_unit_key
        st_model.stock_title = share_item_dict['Name']

        # Share Price + Unit of Currency
        st_model.stock_price = share_item.get_price(
        ) + " " + share_item_dict['Currency']

        deviation_price = share_item.get_change()
        st_model.stock_deviation = deviation_price + " (" + share_item_dict[
            'ChangeinPercent'] + ") "  # Ex: '-1.83 (-1.59%)'
        if deviation_price[0] == '-':
            st_model.stock_deviation_status = 'Decline'
        else:
            st_model.stock_deviation_status = 'Incline'

        st_model.stock_equity = share_item.get_stock_exchange()
        st_model.stock_last_update_time = 'At close: ' + share_item_dict[
            'LastTradeDateTimeUTC']

        st_model.stock_52wkrange = share_item.get_year_low(
        ) + " - " + share_item.get_year_high()
        st_model.stock_open = share_item.get_open()
        st_model.stock_market_cap = share_item.get_market_cap()
        st_model.stock_prev_close = share_item.get_prev_close()
        st_model.stock_peratio_tte = share_item.get_price_earnings_ratio()

        st_model_to_publish = self.payload_to_publish_dict.get_stock_payload_to_publish(
            st_model)
        self.push_stock_to_delivery_queue(st_model_to_publish, stock_unit_key)
Exemplo n.º 7
0
def bot_action(c, symbol):
    stock = Share(symbol)                # Link stock with yahoo_finance module
    print(stock)
    if stock.get_price() == None:
        main()
    #print(stock.get_price())
    head = 'Up to date stock info for **${0}** ({1}):\n\n'.format(symbol.upper(), stock.get_name())
    price = '**Price:** ${0:.2f}\n\n'.format(float(stock.get_price()))
    price_open = '**Open:** ${0:.2f}\n\n'.format(float(stock.get_open()))
    change = '**Change:** {0:.2f} ({1})\n\n'.format(float(stock.get_change()), stock.get_percent_change())
    vol = '**Volume:** {0:,.2f}\n\n'.format(float(stock.get_volume()))
    market_cap = '**Mkt Cap:** {0}\n\n'.format(stock.get_market_cap())
    average = '**Average (50 day):** {0:.2f}\n\n'.format(float(stock.get_50day_moving_avg()))
    exchange = '**Exchange:** {0}\n\n'.format(stock.get_stock_exchange())
    divider = '-----------------------------------------------------------------------------------------\n\n'
    tail = "Don't abuse me, robots have feelings too! | [Source Code](https://github.com/Logicmn/Reddit-Stock-Bot) " \
           "| [Report Bug](https://www.reddit.com/message/compose/?to=Pick-a-Stock) " \
           "| [Suggest Feature](https://www.reddit.com/message/compose/?to=Pick-a-Stock)"
    c.reply(head + divider + price + price_open + change + vol + market_cap + average + exchange+ divider + tail)
Exemplo n.º 8
0
def get_symbol_yahoo_stats_yql(symbols, exclude_name=False):
    """
    Get the symbols' basic statistics from Yahoo Finance.
    Input:
       symbols - a list of symbol strings, e.g. ['AAPL']
    Output: stats in Pandas DataFrame.
    This function is ported from pandas_datareader/yahoo/components.py
    """
    sym_list = str2list(symbols)
    if sym_list == None:
        return DataFrame()

    # Yahoo Finance tags, refer to http://www.financialwisdomforum.org/gummy-stuff/Yahoo-data.htm
    tags = ['Symbol']
    if not exclude_name:
        tags += ['Name']
    tags += ['Exchange', 'MarketCap', 'Volume', 'AverageDailyVolume', 'BookValue', 'P/E', 'PEG', 'Price/Sales',
            'Price/Book', 'EBITDA', 'EPS', 'EPSEstimateNextQuarter', 'EPSEstimateCurrentYear', 'EPSEstimateNextYear',
            'OneyrTargetPrice', 'PriceEPSEstimateCurrentYear', 'PriceEPSEstimateNextYear', 'ShortRatio',
            'Dividend/Share', 'DividendYield', 'DividendPayDate', 'ExDividendDate']
    lines = []
    for sym in sym_list:
        stock = Share(sym)
        line = [sym]
        if not exclude_name:
            line += [stock.get_name()]
        line += [stock.get_stock_exchange(), str2num(stock.get_market_cap(), m2b=True),
                str2num(stock.get_volume()), str2num(stock.get_avg_daily_volume()), str2num(stock.get_book_value()),
                str2num(stock.get_price_earnings_ratio()), str2num(stock.get_price_earnings_growth_ratio()),
                str2num(stock.get_price_sales()), str2num(stock.get_price_book()), str2num(stock.get_ebitda()),
                str2num(stock.get_earnings_share()), str2num(stock.get_EPS_estimate_next_quarter()),
                str2num(stock.get_EPS_estimate_current_year()), str2num(stock.get_EPS_estimate_next_year()),
                str2num(stock.get_one_yr_target_price()), str2num(stock.get_price_EPS_estimate_current_year()),
                str2num(stock.get_price_EPS_estimate_next_year()), str2num(stock.get_short_ratio()),
                str2num(stock.get_dividend_share()), str2num(stock.get_dividend_yield()), stock.get_dividend_pay_date(),
                stock.get_ex_dividend_date()]
        lines.append(line)

    stats = DataFrame(lines, columns=tags)
    stats = stats.drop_duplicates()
    stats = stats.set_index('Symbol')
    return stats
Exemplo n.º 9
0
def write_technical_files(stock_code, start_time, end_time):
  # """ Experiment on quandl """
  # print('quandl data')
  # mydata = quandl.get("FRED/GDP")
  # print(mydata)
  # print('hello')

  # data = quandl.get("WIKI/FB.11", start_date="2014-01-01", end_date="2014-12-31", collapse="monthly", transform="diff")
  # print(data)

  stock = Share(stock_code)

  print('stock.get_info()')
  print(stock.get_info())

  print('get_price()')
  print(stock.get_price())

  print('get_change()')
  print(stock.get_change())

  print('get_stock_exchange()')
  print(stock.get_stock_exchange())

  print('get_market_cap()')
  print(stock.get_market_cap())

  print('get_book_value()')
  print(stock.get_book_value())

  print('get_ebitda()')
  print(stock.get_ebitda())

  print('get_dividend_share()')  
  print(stock.get_dividend_share())

  print('get_dividend_yield()')
  print(stock.get_dividend_yield())

  print('get_earnings_share()')
  print(stock.get_earnings_share())

  print('get_50day_moving_avg()')
  print(stock.get_50day_moving_avg())

  print('get_200day_moving_avg()')
  print(stock.get_200day_moving_avg())

  print('get_price_earnings_ratio()')
  print(stock.get_price_earnings_ratio())

  print('get_price_earnings_growth_ratio()')
  print(stock.get_price_earnings_growth_ratio())

  print('get_price_sales()')
  print(stock.get_price_sales())

  print('get_price_book()')
  print(stock.get_price_book())

  print('get_short_ratio()')
  print(stock.get_short_ratio())

  print('historical_data')
  print(stock.get_historical(start_time, end_time))

  historical_data = stock.get_historical(start_time, end_time)

  info_text = "Symbol\t" + "Stock Exchange\t" + "Price\t" + "Market Cap\t" + "Book Value\t" + "EBITDA\t" + "50d Moving Avg\t" + "100d Moving Avg\n"
  info_text += str(stock.get_info()['symbol']) + "\t" + str(stock.get_stock_exchange()) + "\t" + str(stock.get_price()) + "\t" + str(stock.get_market_cap()) + "\t" + str(stock.get_book_value()) + "\t";
  info_text += str(stock.get_ebitda()) + "\t" + str(stock.get_50day_moving_avg()) + "\t" + str(stock.get_200day_moving_avg()) + "\n";

  info_directory = '/data/info.tsv'

  write_to_file(info_directory, info_text)

  high_low_text = "date\t" + "High\t" + "Low\n"
  open_close_text = "date\t" + "Open\t" + "Close\n"
  volume_text = "date\t" + "Volume\n"

  for index, value in enumerate(historical_data):
    date = str(historical_data[len(historical_data) - 1 - index]['Date'])
    date = date.replace('-','')

    stock_high = str(historical_data[len(historical_data) - 1 - index]['High'])
    stock_low = str(historical_data[len(historical_data) - 1 - index]['Low'])

    stock_open = str(historical_data[len(historical_data) - 1 - index]['Open'])
    stock_close = str(historical_data[len(historical_data) - 1 - index]['Close'])

    stock_volume = str(int(historical_data[len(historical_data) - 1 - index]['Volume']) / 1000)

    high_low_text += date + "\t" + stock_high + "\t" + stock_low + "\n"
    open_close_text += date + "\t" + stock_open + "\t" + stock_close + "\n"
    volume_text += date + "\t" + stock_volume + "\n"

  high_low_directory = '/data/highlow.tsv'
  open_close_directory = '/data/openclose.tsv'
  volume_directory = '/data/volume.tsv'

  write_to_file(high_low_directory, high_low_text)
  write_to_file(open_close_directory, open_close_text)
  write_to_file(volume_directory, volume_text)

  ratio_text = "name\t" + "value\n"

  if stock.get_change() != None:
    name = "Change"
    value = str(stock.get_change())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_dividend_share() != None:
    name = "Dividend Share"
    value = str(stock.get_dividend_share())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_dividend_yield() != None:
    name = "Divident Yield"
    value = str(stock.get_dividend_yield())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_earnings_share() != None:
    name = "Earning Share"
    value = str(stock.get_earnings_share())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_price_earnings_ratio() != None:
    name = "Price Earning"
    value = str(stock.get_price_earnings_ratio())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_price_earnings_growth_ratio() != None:
    name = "Price Earning Growth"
    value = str(stock.get_price_earnings_growth_ratio())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_price_sales() != None:
    name = "Price Sales"
    value = str(stock.get_price_sales())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_price_book() != None:
    name = "Price Book"
    value = str(stock.get_price_book())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_short_ratio() != None:
    name = "Short"
    value = str(stock.get_short_ratio())
    ratio_text += name + "\t" + value + "\n"

  ratio_directory = '/data/ratio.tsv'

  write_to_file(ratio_directory, ratio_text)
Exemplo n.º 10
0
		print change

	if myargs.avgvol is True:
		avgvolume = stock.get_avg_daily_volume()
		print avgvolume

	if myargs.short is True:
		short = stock.get_short_ratio()
		print short

	if myargs.peratio is True:
		pe = stock.get_price_earnings_ratio()
		print pe

	if myargs.exchange is True:
		exchange = stock.get_stock_exchange()

	if myargs.ma50 is True:
		ma50 = stock.get_50day_moving_avg()
		print ma50

	if myargs.ma200 is True:
		ma200 = stock.get_200day_moving_avg()
		print ma200

	if myargs.marketcap is True:
		marketcap = stock.get_market_cap()
		print marketcap

	if myargs.getopen is True:
		getopen = stock.get_open()
Exemplo n.º 11
0
from yahoo_finance import Share

inp = open('input.txt', 'r')
out = open('output.txt', 'w')
for line in inp:
	temp = Share(line)
	temp.refresh()
	out.write(line.rstrip("\n") + "," + temp.get_price() + "," + temp.get_change() + "\n")
	#FORMAT:  Symbol, last closing price, last change
temp = Share('FUSVX')
print(temp.get_stock_exchange())
Exemplo n.º 12
0
from yahoo_finance import Share, Currency



yahoo = Share('AAPL')

yahoo.refresh()

print yahoo.get_info()
print yahoo.get_avg_daily_volume()
print yahoo.get_stock_exchange()
print yahoo.get_book_value()
print yahoo.get_ebitda()
print yahoo.get_dividend_share()
print yahoo.get_price_earnings_ratio()
print yahoo.get_short_ratio()
print yahoo.get_price_book()

# f = open('nasdaqlisted.txt', 'r')

# print (f.readline())
# print (f.readline())
Exemplo n.º 13
0
    #make sure it really represents a stock

    try:
        yahooSymbol = Share(ticker)
    except:
        print('error in starting ticker- ' + ticker + " deleted")
        error = 1
    try:
        yahooIndustry = industry(ticker)
    except:
        print('error in getting industry- ' + ticker + " deleted")
        error = 1

    if error != 1:
        # If NYSE
        if str(yahooSymbol.get_stock_exchange()) == "NYQ":
            NYSEdict[ticker] = (yahooSymbol.get_name(), yahooIndustry)
            current = len(NYSEquotes)
            try:
                NYSEquotes.append(
                    quotes_historical_yahoo_ochl(ticker, d1, d2,
                                                 asobject=True))
            except:
                print('error - ' + ticker + " deleted")
                NYSEdict.pop(ticker)
                if current != len(NYSEquotes):
                    del NYSEquotes[len(NYSEquotes) - 1]
            else:
                if NYSEquotes[len(NYSEquotes) - 1] == None:
                    del NYSEquotes[len(NYSEquotes) - 1]
                    NYSEdict.pop(ticker)
Exemplo n.º 14
0
def result_page(request):
    rstlist = list()
    grow_sortlst = list()
    value_sortlst = list()
    quality_sortlst = list()

    grow_stcklist = [ 'PNW','RL','PPG','ACN', 'ATVI', 'AYI', 'AMD', 'LNT', 'ALXN', 'GOOGL']
    value_stcklist = ['AMG', 'AFL', 'APD', 'AKAM','PCG','PM','PSX', 'AAP', 'AES', 'AET']
    quality_stcklist = ['MMM', 'ABT', 'ABBV','PEP','PKI','PRGO','PFE', 'ALB', 'ECL', 'AGN']
    stckdict = dict()

    if request.method == 'POST':
        allotment = int(str(request.POST['allotment']))
        ori_allotment = allotment
        iv_type = 0
        for key in request.POST.keys():
            print "iv_type="+str(iv_type)
            print str(key)
            if key in ['ethical','growth','index','quality','value']:
                iv_type = iv_type + 1

        print("current selected types count = " + str(iv_type))
        if iv_type == 2:
            allotment = allotment/float(2)

        if 'ethical' in request.POST.keys():
            AAPL = Share('AAPL')
            aapl_f = float(str(AAPL.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(AAPL.get_percent_change_from_50_day_moving_average())[0:-1]) - \
                     float(str(AAPL.get_percent_change_from_year_high())[0:-1])

            ADBE = Share('ADBE')
            adbe_f = float(str(ADBE.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(ADBE.get_percent_change_from_50_day_moving_average())[0:-1]) - \
                     float(str(ADBE.get_percent_change_from_year_high())[0:-1])

            NSRGY = Share('NSRGY')
            nsrgy_f = float(str(NSRGY.get_percent_change_from_year_low())[0:-1]) + \
                      float(str(NSRGY.get_percent_change_from_50_day_moving_average())[0:-1]) - \
                      float(str(NSRGY.get_percent_change_from_year_high())[0:-1])
            stckdict['AAPL'] = AAPL
            stckdict['ADBE'] = ADBE
            stckdict['NSRGY'] = NSRGY
            total_f = (aapl_f + adbe_f + nsrgy_f)*iv_type
            aapl_pct = aapl_f/float(total_f)
            adbe_pct = adbe_f/float(total_f)
            nsrgy_pct = nsrgy_f/float(total_f)
            aaplD = {"sticker":"AAPL","name":AAPL.get_name(),"aloc_pct":str(aapl_pct),"aloc_amt":str(allotment*aapl_pct),"price":str(AAPL.get_price()),"exchange":str(AAPL.get_stock_exchange())}
            adbeD = {"sticker":"ADBE","name":ADBE.get_name(),"aloc_pct":str(adbe_pct),"aloc_amt":str(allotment*adbe_pct),"price":str(ADBE.get_price()),"exchange":str(ADBE.get_stock_exchange())}
            nsrgyD = {"sticker":"NSRGY","name":NSRGY.get_name(),"aloc_pct":str(nsrgy_pct),"aloc_amt":str(allotment*nsrgy_pct),"price":str(NSRGY.get_price()),"exchange":str(NSRGY.get_stock_exchange())}
            rstlist.append(aaplD)
            rstlist.append(adbeD)
            rstlist.append(nsrgyD)

        if 'growth' in request.POST.keys():
            for stock in grow_stcklist:
                while True:
                    try:
                        detail = Share(stock)
                    except:
                        time.sleep(0.1)
                        continue
                    break
                stckdict[stock]=detail
                heapq.heappush(grow_sortlst, (float(str(detail.get_percent_change_from_year_low())[0:-1]) +
                                              float(
                                                  str(detail.get_percent_change_from_200_day_moving_average())[0:-1]) +
                                              float(str(detail.get_percent_change_from_50_day_moving_average())[0:-1]) +
                                              float(str(detail.get_percent_change_from_year_high())[0:-1]), stock,
                                              detail))
                if len(grow_sortlst) > 3:
                    heapq.heappop(grow_sortlst)
            total_f = 0
            for item in grow_sortlst:
                total_f = total_f + item[0]
            for item in grow_sortlst:
                item_pct = item[0]/float(total_f*iv_type)
                item_amt = allotment*item_pct
                rstlist.append({"sticker":item[1],"name":item[2].get_name(),"aloc_pct":str(item_pct),"aloc_amt":str(item_amt),"price":str(item[2].get_price()),"exchange":str(item[2].get_stock_exchange())})

        if 'index' in request.POST.keys():

            VTI = Share('VTI')
            vti_f = float(str(VTI.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(VTI.get_percent_change_from_200_day_moving_average())[0:-1]) - \
                     float(str(VTI.get_percent_change_from_year_high())[0:-1])

            IXUS = Share('IXUS')
            ixus_f = float(str(IXUS.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(IXUS.get_percent_change_from_200_day_moving_average())[0:-1]) - \
                     float(str(IXUS.get_percent_change_from_year_high())[0:-1])

            ILTB = Share('ILTB')
            iltb_f = float(str(ILTB.get_percent_change_from_year_low())[0:-1]) + \
                      float(str(ILTB.get_percent_change_from_200_day_moving_average())[0:-1]) - \
                      float(str(ILTB.get_percent_change_from_year_high())[0:-1])
            stckdict['VTI'] = VTI
            stckdict['IXUS'] = IXUS
            stckdict['ILTB'] = ILTB
            total_f = (vti_f + ixus_f + iltb_f)*iv_type
            vti_pct = vti_f / float(total_f)
            ixus_pct = ixus_f / float(total_f)
            iltb_pct = iltb_f / float(total_f)
            vtiD = {"sticker": "VTI", "name": VTI.get_name(), "aloc_pct": str(vti_pct),
                     "aloc_amt": str(allotment * vti_pct), "price": str(VTI.get_price()),
                     "exchange": str(VTI.get_stock_exchange())}
            ixusD = {"sticker": "IXUS", "name": IXUS.get_name(), "aloc_pct": str(ixus_pct),
                     "aloc_amt": str(allotment * ixus_pct), "price": str(IXUS.get_price()),
                     "exchange": str(IXUS.get_stock_exchange())}
            iltbD = {"sticker": "ILTB", "name": ILTB.get_name(), "aloc_pct": str(iltb_pct),
                      "aloc_amt": str(allotment * iltb_pct), "price": str(ILTB.get_price()),
                      "exchange": str(ILTB.get_stock_exchange())}
            rstlist.append(vtiD)
            rstlist.append(ixusD)
            rstlist.append(iltbD)

        if 'quality' in request.POST.keys():
            for stock in quality_stcklist:
                while True:
                    try:
                        detail = Share(stock)
                    except:
                        time.sleep(0.1)
                        continue
                    break
                stckdict[stock] = detail
                heapq.heappush(quality_sortlst, (
                    float(detail.get_price_earnings_ratio() if detail.get_price_earnings_ratio() != None else 0) +
                    float(
                        detail.get_price_earnings_growth_ratio() if detail.get_price_earnings_growth_ratio() != None else 0) +
                    float(
                        detail.get_change_from_200_day_moving_average() if detail.get_change_from_200_day_moving_average() != None else 0) +
                    float(
                        detail.get_price_earnings_growth_ratio() if detail.get_price_earnings_growth_ratio() != None else 0),
                    stock, detail))
                if len(quality_sortlst) > 3:
                    heapq.heappop(quality_sortlst)
            total_f = 0
            for item in quality_sortlst:
                total_f = total_f + item[0]
            for item in quality_sortlst:
                item_pct = item[0] / float(total_f*iv_type)
                item_amt = allotment * item_pct
                rstlist.append({"sticker": item[1], "name": item[2].get_name(), "aloc_pct": str(item_pct),
                                "aloc_amt": str(item_amt), "price": str(item[2].get_price()),
                                "exchange": str(item[2].get_stock_exchange())})

        if 'value' in request.POST.keys():
            for stock in value_stcklist:
                while True:
                    try:
                        detail = Share(stock)
                    except:
                        time.sleep(0.1)
                        continue
                    break
                stckdict[stock] = detail
                heapq.heappush(value_sortlst,
                               (float(detail.get_dividend_yield() if detail.get_dividend_yield() != None else 0) +
                                float(
                                    detail.get_price_earnings_growth_ratio() if detail.get_price_earnings_growth_ratio() != None else 0) -
                                float(detail.get_price_book() if detail.get_price_book() != None else 0), stock,
                                detail))
                if len(value_sortlst) > 3:
                    heapq.heappop(value_sortlst)
            total_f = 0
            for item in value_sortlst:
                total_f = total_f + item[0]
            print "total_f=" + str(total_f)
            for item in value_sortlst:
                item_pct = item[0] / float(total_f*iv_type)
                item_amt = allotment * item_pct
                rstlist.append({"sticker": item[1], "name": item[2].get_name(), "aloc_pct": str(item_pct),
                                "aloc_amt": str(item_amt), "price": str(item[2].get_price()),
                                "exchange": str(item[2].get_stock_exchange())})
        days_cnt = 15
        str_date =  str((datetime.now() - timedelta(days=days_cnt)).date().isoformat())
        end_date = str(datetime.today().date().isoformat())
        day_pro = list()
        remaining = 0
        for item in rstlist:
            while True:
                try:
                    hist_info = stckdict[item["sticker"]].get_historical(str_date,end_date)
                except:
                    continue
                break
            for i in range(0,6):
                if len(day_pro)<=i:
                    day_pro.append({hist_info[i]["Date"]:float(hist_info[i]["Close"])*int(float(item["aloc_amt"])/float(hist_info[i]["Open"]))+float(item["aloc_amt"])%float(hist_info[i]["Open"])})
                else:
                    day_pro[i][hist_info[i]["Date"]] = float(day_pro[i][hist_info[i]["Date"]]) + float(hist_info[i]["Close"])*int(float(item["aloc_amt"])/float(hist_info[i]["Open"])) + float(item["aloc_amt"])%float(hist_info[i]["Open"])
        rstlist.append({"sticker":"portfolio","history":day_pro})
        print(json.dumps(rstlist))
        return render(request, 'portfolio/result.html', {'result': json.dumps(rstlist)})
    return render(request, 'portfolio/home.html')
Exemplo n.º 15
0
from yahoo_finance import Share, Currency

yahoo = Share('AAPL')

yahoo.refresh()

print yahoo.get_info()
print yahoo.get_avg_daily_volume()
print yahoo.get_stock_exchange()
print yahoo.get_book_value()
print yahoo.get_ebitda()
print yahoo.get_dividend_share()
print yahoo.get_price_earnings_ratio()
print yahoo.get_short_ratio()
print yahoo.get_price_book()

# f = open('nasdaqlisted.txt', 'r')

# print (f.readline())
# print (f.readline())