MOVED to iexfinance.stocks.get_market_iex_percent
172154
def get_market_iex_percent(*args, **kwargs):
    
    import warnings
    warnings.warn(WNG_MSG, ("get_market_iex_percent",
                            "stocks.get_market_iex_percent"))
    return stocks.get_market_iex_percent(*args, **kwargs)
1231196
def QA_SU_save_stock_xdxr(client=DATABASE, ui_log=None, ui_progress=None):
    
    stock_list = QA_fetch_get_stock_list().code.unique().tolist()
    # client.drop_collection('stock_xdxr')
    try:

        coll = client.stock_xdxr
        coll.create_index(
            [('code',
              pymongo.ASCENDING),
             ('date',
              pymongo.ASCENDING)],
            unique=True
        )
    except:
        client.drop_collection('stock_xdxr')
        coll = client.stock_xdxr
        coll.create_index(
            [('code',
              pymongo.ASCENDING),
             ('date',
              pymongo.ASCENDING)],
            unique=True
        )
    err = []

    def __saving_work(code, coll):
        QA_util_log_info(
            '##JOB02 Now Saving XDXR INFO ==== {}'.format(str(code)),
            ui_log=ui_log
        )
        try:
            coll.insert_many(
                QA_util_to_json_from_pandas(QA_fetch_get_stock_xdxr(str(code))),
                ordered=False
            )

        except:

            err.append(str(code))

    for i_ in range(len(stock_list)):
        QA_util_log_info(
            'The {} of Total {}'.format(i_,
                                        len(stock_list)),
            ui_log=ui_log
        )
        strLogInfo = 'DOWNLOAD PROGRESS {} '.format(
            str(float(i_ / len(stock_list) * 100))[0:4] + '%'
        )
        intLogProgress = int(float(i_ / len(stock_list) * 100))
        QA_util_log_info(
            strLogInfo,
            ui_log=ui_log,
            ui_progress=ui_progress,
            ui_progress_int_value=intLogProgress
        )
        __saving_work(stock_list[i_], coll)
863042
def portfolio_value(portfolio, date, price='close'):
    
    value = 0.0
    for (sym, sym_shares) in portfolio.iteritems():
        sym_price = None
        if sym_shares:
            sym_price = get_price(symbol=sym, date=date, price=price)
        # print sym, sym_shares, sym_price
        # print last_date, k, price
        if sym_price != None:
            if np.isnan(sym_price):
                print 'Invalid price, shares, value, total: ', sym_price, sym_shares, (float(sym_shares) * float(sym_price)) if sym_shares and sym_price else 'Invalid', value
                if sym_shares:
                    return float('nan')
            else:
                # print ('{0} shares of {1} = {2} * {3} = {4}'.format(sym_shares, sym, sym_shares, sym_price, sym_shares * sym_price))
                value += sym_shares * sym_price
                # print 'new price, value = {0}, {1}'.format(sym_price, value)
    return value
626224
def fetch_trades_since(self, since: int) -> List[Trade]:
        """"""
        return self._fetch_since('trades', self.market.code)(self._trades_since)(since)
1157579
def from_dict(data, ctx):
        

        type = data.get("type")

        if type == "TAKE_PROFIT":
            return TakeProfitOrder.from_dict(data, ctx)
        if type == "STOP_LOSS":
            return StopLossOrder.from_dict(data, ctx)
        if type == "TRAILING_STOP_LOSS":
            return TrailingStopLossOrder.from_dict(data, ctx)
        if type == "MARKET":
            return MarketOrder.from_dict(data, ctx)
        if type == "FIXED_PRICE":
            return FixedPriceOrder.from_dict(data, ctx)
        if type == "LIMIT":
            return LimitOrder.from_dict(data, ctx)
        if type == "STOP":
            return StopOrder.from_dict(data, ctx)
        if type == "MARKET_IF_TOUCHED":
            return MarketIfTouchedOrder.from_dict(data, ctx)

        data = data.copy()

        if data.get('clientExtensions') is not None:
            data['clientExtensions'] = \
                ctx.transaction.ClientExtensions.from_dict(
                    data['clientExtensions'], ctx
                )

        return Order(**data)
1007630
def get_trend(timeseries):
    

    last = timeseries['value'][len(timeseries['value']) - 1]
    prev = timeseries['value'][len(timeseries['value']) - 2]
    trend = last - prev
    trend_percentage = None

    if last == 0:
        if prev > 0:
            trend_percentage = -100
        else:
            trend_percentage = 0
    else:
        trend_percentage = int((trend / last) * 100)
    return (last, trend_percentage)
242647
def clear(self, asset_manager_id):
        
        self.logger.info('Clear Market Data - Asset Manager: %s', asset_manager_id)
        url = '%s/clear/%s' % (self.endpoint, asset_manager_id)
        response = self.session.delete(url)
        if response.ok:
            eod_price_count = response.json().get('eod_price_count', 'Unknown')
            self.logger.info('Deleted %s EOD Prices.', eod_price_count)
            fx_rate_count = response.json().get('fx_rate_count', 'Unknown')
            self.logger.info('Deleted %s FX Rates.', fx_rate_count)
            return response.json()
        else:
            self.logger.error(response.text)
            response.raise_for_status()
1274859
function percent_px(el, prop, percent) {
          var parent_width = Embedo.utils.compute(el.parentNode, prop, true);
          percent = parseFloat(percent);
          return parent_width * (percent / 100);
        }
356750
def __getCashToBuyStock(self):
        '''  '''
        account=self.__strategy.getAccountCopy()
        if (account.getCash() >= account.getTotalValue() / self.buying_ratio):
            return account.getTotalValue() / self.buying_ratio
        else:
            return 0
1236908
def get_market_gainers(*args, **kwargs):
    
    import warnings
    warnings.warn(WNG_MSG, ("get_market_gainers", "stocks.get_market_gainers"))
    return stocks.get_market_gainers(*args, **kwargs)
1184721
def get_market_deep(symbols=None, **kwargs):
    
    import warnings
    warnings.warn(WNG_MSG % ("get_market_deep", "iexdata.get_deep"))
    return DEEP(symbols, **kwargs).fetch()
840220
def xdxr(self, symbol=''):
        '''
        
        '''
        market = get_stock_market(symbol)

        with self.client.connect(*self.bestip):
            data = self.client.get_xdxr_info(int(market), symbol)
            return self.client.to_df(data)
364951
def get_stockprices(chart_range='1y'):
    '''
    
    '''

    all_symbols = list_symbols()

    @daily_cache(filename='iex_chart_{}'.format(chart_range))
    def get_stockprices_cached(all_symbols):
        return _get_stockprices(all_symbols, chart_range)

    return get_stockprices_cached(all_symbols)
321633
def move_if_not_on_dow(original, replacement, dow_not_orig, dow_replacement):
    
    return lambda x: (
        (x.hdate.day == original and x.gdate.weekday() != dow_not_orig) or
        (x.hdate.day == replacement and x.gdate.weekday() == dow_replacement))
1348250
def _get_history_daily_window(self,
                                  assets,
                                  end_dt,
                                  bar_count,
                                  field_to_use,
                                  data_frequency):
        
        session = self.trading_calendar.minute_to_session_label(end_dt)
        days_for_window = self._get_days_for_window(session, bar_count)

        if len(assets) == 0:
            return pd.DataFrame(None,
                                index=days_for_window,
                                columns=None)

        data = self._get_history_daily_window_data(
            assets, days_for_window, end_dt, field_to_use, data_frequency
        )
        return pd.DataFrame(
            data,
            index=days_for_window,
            columns=assets
        )
809348
def Task_display(self):
    
    re = """%(stock_name)s %(stock_no)s %(stock_date)s
Today: %(stock_price)s %(stock_range)s
=-=-=-=""" % {
        'stock_name': unicode(self.stock_name),
        'stock_no': unicode(self.stock_no),
        'stock_date': unicode(self.data_date[-1]),
        'stock_price': unicode(self.raw_data[-1]),
        'stock_range': unicode(self.stock_range[-1]),
      }
    return re
1039430
def get_stock_market(symbol='', string=False):
    """'"""
    assert isinstance(symbol, str), 'stock code need str type'

    if symbol.startswith(('sh', 'sz')):
        market = symbol[:2]

    if symbol.startswith(('50', '51', '60', '90', '110', '113', '132', '204')):
        market = 'sh'

    if symbol.startswith(
        ('00',
         '13',
         '18',
         '15',
         '16',
         '18',
         '20',
         '30',
         '39',
         '115',
         '1318')):
        market = 'sz'

    if symbol.startswith(('5', '6', '9', '7')):
        market = 'sh'

    if string is False:
        return 0 if market == 'sz' else 1

    return market