Get historical prices for the given ticker symbol.
        Date format is 'YYYY-MM-DD'

        Returns a nested list.
10124
def getQuotes(self, symbol, start, end):
        
        try:
            start = str(start).replace('-', '')
            end = str(end).replace('-', '')

            url = 'http://ichart.yahoo.com/table.csv?s=%s&' % symbol + \
                'd=%s&' % str(int(end[4:6]) - 1) + \
                'e=%s&' % str(int(end[6:8])) + \
                'f=%s&' % str(int(end[0:4])) + \
                'g=d&' + \
                'a=%s&' % str(int(start[4:6]) - 1) + \
                'b=%s&' % str(int(start[6:8])) + \
                'c=%s&' % str(int(start[0:4])) + \
                'ignore=.csv'
            days = urllib.urlopen(url).readlines()
            values = [day[:-2].split(',') for day in days]
            # sample values:[['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Clos'], \
            #              ['2009-12-31', '112.77', '112.80', '111.39', '111.44', '90637900', '109.7']...]
            data = []
            for value in values[1:]:
                data.append(Quote(value[0], value[1], value[2], value[3], value[4], value[5], value[6]))

            dateValues = sorted(data, key = lambda q: q.time)
            return dateValues

        except IOError:
            raise UfException(Errors.NETWORK_ERROR, "Can't connect to Yahoo server")
        except BaseException:
            raise UfException(Errors.UNKNOWN_ERROR, "Unknown Error in YahooFinance.getHistoricalPrices %s" % traceback.format_exc())
372097
def QA_util_get_real_datelist(start, end):
    
    real_start = QA_util_get_real_date(start, trade_date_sse, 1)
    real_end = QA_util_get_real_date(end, trade_date_sse, -1)
    if trade_date_sse.index(real_start) > trade_date_sse.index(real_end):
        return None, None
    else:
        return (real_start, real_end)
982227
def get_last_ticker(self, symbol, _async=False):
        
        params = {'symbol': symbol}

        url = u.MARKET_URL + '/market/trade'
        return http_get_request(url, params, _async=_async)
1236290
def getAll(self, symbol):
        
        values = self.__request(symbol, 'l1c1va2xj1b4j4dyekjm3m4rr5p5p6s7').split(',')
        data = {}
        data['price'] = values[0]
        data['change'] = values[1]
        data['volume'] = values[2]
        data['avg_daily_volume'] = values[3]
        data['stock_exchange'] = values[4]
        data['market_cap'] = values[5]
        data['book_value'] = values[6]
        data['ebitda'] = values[7]
        data['dividend_per_share'] = values[8]
        data['dividend_yield'] = values[9]
        data['earnings_per_share'] = values[10]
        data['52_week_high'] = values[11]
        data['52_week_low'] = values[12]
        data['50day_moving_avg'] = values[13]
        data['200day_moving_avg'] = values[14]
        data['price_earnings_ratio'] = values[15]
        data['price_earnings_growth_ratio'] = values[16]
        data['price_sales_ratio'] = values[17]
        data['price_book_ratio'] = values[18]
        data['short_ratio'] = values[19]
        return data
1147718
def get_historical_price(self, crypto, fiat, at_time):
        
        # represents the 'width' of the quandl data returned (one day)
        # if quandl ever supports data hourly or something, this can be changed
        interval = datetime.timedelta(hours=48)
        crypto = crypto.lower()
        fiat = fiat.lower()

        at_time = arrow.get(at_time).datetime

        data = crypto_data[crypto]
        name, date_created = data['name'], data['genesis_date']

        if date_created.replace(tzinfo=pytz.utc) > at_time:
            raise Exception("%s (%s) did not exist on %s" % (name, crypto, at_time))

        if crypto == 'btc':
            # Bitcoin to fiat
            if fiat == 'usd':
                if at_time < datetime.datetime(2013, 2, 1, tzinfo=pytz.utc):
                    exchange = 'MtGox'
                else:
                    exchange = "Bitstamp"
            else:
                exchange = quandl_exchange_btc_to_fiat[fiat.upper()]

            source = "BITCOIN/%s%s" % (exchange.upper(), fiat.upper())
            price_index = 1
        else:
            # some altcoin to bitcoin
            if fiat != 'btc':
                raise Exception("Altcoins are only available via BTC base fiat")
            if crypto == 'ltc':
                source, price_index = ['BTCE/BTCLTC', 4]
            else:
                source, price_index = ['CRYPTOCHART/' + crypto.upper(), 1]

        url = "https://www.quandl.com/api/v1/datasets/%s.json" % source
        trim = "?trim_start={0:%Y-%m-%d}&trim_end={1:%Y-%m-%d}".format(
            at_time - interval, at_time + interval
        )

        response = self.get_url(url + trim).json()
        closest_distance = interval

        best_price = None
        for line in response['data']:
            date = line[0]
            price = line[price_index]
            tick_date = arrow.get(date).datetime
            distance = at_time - tick_date

            if distance.total_seconds() == 0:
                return price, source, tick_date

            if distance < closest_distance:
                closest_distance = distance
                best_price = price
                best_date = tick_date

        if not best_price:
            msg = "Quandl's data source is incomplete. Could not get best price for %s/%s on %s." % (
                crypto, fiat, at_time
            )
            raise NoData(msg)

        return best_price, source, best_date
123260
def handle_data(self):
        
        # 读取历史数据，使用sma方式计算均线准确度和数据长度无关，但是在使用ema方式计算均线时建议将历史数据窗口适当放大，结果会更加准确
        today = datetime.datetime.today()
        pre_day = (today - datetime.timedelta(days=self.observation)
                   ).strftime('%Y-%m-%d')
        end_dt = today.strftime('%Y-%m-%d')
        ret_code, prices = self.quote_ctx.get_history_kline(self.stock, start=pre_day, end=end_dt, ktype=ft.KLType.K_DAY)
        if ret_code != ft.RET_OK:
            print("get_history_kline fail: {}".format(prices))
            return

        # 用talib计算MACD取值，得到三个时间序列数组，分别为 macd, signal 和 hist
        # macd 是长短均线的差值，signal 是 macd 的均线
        # 使用 macd 策略有几种不同的方法，我们这里采用 macd 线突破 signal 线的判断方法
        macd, signal, hist = talib.MACD(prices['close'].values,
                                        self.short_period, self.long_period,
                                        self.smooth_period)

        # 如果macd从上往下跌破macd_signal
        if macd[-1] < signal[-1] and macd[-2] > signal[-2]:
            # 计算现在portfolio中股票的仓位
            ret_code, data = self.trade_ctx.position_list_query(
                trd_env=self.trade_env)

            if ret_code != ft.RET_OK:
                raise Exception('账户信息获取失败: {}'.format(data))
            pos_info = data.set_index('code')

            cur_pos = int(pos_info['qty'][self.stock])
            # 进行清仓
            if cur_pos > 0:
                ret_code, data = self.quote_ctx.get_market_snapshot(
                    [self.stock])
                if ret_code != 0:
                    raise Exception('市场快照数据获取异常 {}'.format(data))
                cur_price = data['last_price'][0]
                ret_code, ret_data = self.trade_ctx.place_order(
                    price=cur_price,
                    qty=cur_pos,
                    code=self.stock,
                    trd_side=ft.TrdSide.SELL,
                    order_type=ft.OrderType.NORMAL,
                    trd_env=self.trade_env)
                if ret_code == ft.RET_OK:
                    print('stop_loss MAKE SELL ORDER\n\tcode = {} price = {} quantity = {}'
                          .format(self.stock, cur_price, cur_pos))
                else:
                    print('stop_loss: MAKE SELL ORDER FAILURE: {}'.format(ret_data))

        # 如果短均线从下往上突破长均线，为入场信号
        if macd[-1] > signal[-1] and macd[-2] < signal[-2]:
            # 满仓入股
            ret_code, acc_info = self.trade_ctx.accinfo_query(
                trd_env=self.trade_env)
            if ret_code != 0:
                raise Exception('账户信息获取失败! 请重试: {}'.format(acc_info))

            ret_code, snapshot = self.quote_ctx.get_market_snapshot(
                [self.stock])
            if ret_code != 0:
                raise Exception('市场快照数据获取异常 {}'.format(snapshot))
            lot_size = snapshot['lot_size'][0]
            cur_price = snapshot['last_price'][0]
            cash = acc_info['Power'][0]  # 购买力
            qty = int(math.floor(cash / cur_price))
            qty = qty // lot_size * lot_size

            ret_code, ret_data = self.trade_ctx.place_order(
                price=cur_price,
                qty=qty,
                code=self.stock,
                trd_side=ft.TrdSide.BUY,
                order_type=ft.OrderType.NORMAL,
                trd_env=self.trade_env)
            if not ret_code:
                print(
                    'stop_loss MAKE BUY ORDER\n\tcode = {} price = {} quantity = {}'
                    .format(self.stock, cur_price, qty))
            else:
                print('stop_loss: MAKE BUY ORDER FAILURE: {}'.format(ret_data))
244517
def prepare_query(self, symbol,  start_date, end_date):
        """"""
        query = \
            'select * from yahoo.finance.historicaldata where symbol = "%s" and startDate = "%s" and endDate = "%s"' \
            % (symbol, start_date, end_date)

        return query
257400
def get_last_ticker(self, symbol):
        
        params = {'symbol': symbol}

        url = u.MARKET_URL + '/market/trade'

        def _wrapper(_func):
            @wraps(_func)
            def handle():
                _func(http_get_request(url, params))

            return handle

        return _wrapper
501553
def get_card_prices(ctx, currency):
    
    appid = ctx.obj['appid']

    detailed = True

    appids = [appid]
    if ',' in appid:
        appids = [appid.strip() for appid in appid.split(',')]
        detailed = False

    for appid in appids:
        print_card_prices(appid, currency, detailed=detailed)
        click.echo('')
915873
def ticker(rest):
	""
	ticker = rest.upper()
	# let's use Yahoo's nifty csv facility, and pull last time/price both
	symbol = 's'
	last_trade_price = 'l1'
	last_trade_time = 't1'
	change_percent = 'p2'
	format = ''.join((symbol, last_trade_time, last_trade_price, change_percent))
	url = (
		'http://finance.yahoo.com/d/quotes.csv?s=%(ticker)s&f=%(format)s'
		% locals())
	stock_info = csv.reader(util.open_url(url).text.splitlines())
	last_trade, = stock_info
	ticker_given, time, price, diff = last_trade
	if ticker_given != ticker:
		return "d'oh... could not find information for symbol %s" % ticker
	return '%(ticker)s at %(time)s (ET): %(price)s (%(diff)s)' % locals()
4127
def prices(self):
        
        # if accessing and stale - update first
        if self._needupdate or self.now != self.parent.now:
            self.update(self.root.now)
        return self._prices.loc[:self.now]
1179946
def market_snapshot(self, prefix=False):
        
        return self.get_stock_data(self.stock_list, prefix=prefix)
1245
def get_today_all(output='pd'):
    

    data = []
    today = str(datetime.date.today())
    codes = QA_fetch_get_stock_list('stock').code.tolist()
    bestip = select_best_ip()['stock']
    for code in codes:
        try:
            l = QA_fetch_get_stock_day(
                code, today, today, '00', ip=bestip)
        except:
            bestip = select_best_ip()['stock']
            l = QA_fetch_get_stock_day(
                code, today, today, '00', ip=bestip)
        if l is not None:
            data.append(l)

    res = pd.concat(data)
    if output in ['pd']:
        return res
    elif output in ['QAD']:
        return QA_DataStruct_Stock_day(res.set_index(['date', 'code'], drop=False))
95478
def get_previous_price(self, currency, date_obj):
        
        start = date_obj.strftime('%Y-%m-%d')
        end = date_obj.strftime('%Y-%m-%d')
        url = (
            'https://api.coindesk.com/v1/bpi/historical/close.json'
            '?start={}&end={}&currency={}'.format(
                   start, end, currency
               )
        )
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()
            price = data.get('bpi', {}).get(start, None)
            if self._force_decimal:
                return Decimal(price)
            return price
        raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date")
261756
def QA_fetch_get_sh_margin(date):
    
    if date in trade_date_sse:
        data= pd.read_excel(_sh_url.format(QA_util_date_str2int
                                            (date)), 1).assign(date=date).assign(sse='sh')             
        data.columns=['code','name','leveraged_balance','leveraged_buyout','leveraged_payoff','margin_left','margin_sell','margin_repay','date','sse']
        return data
    else:
        pass
627098
def hold_price(self, datetime=None):
        

        def weights(x):
            if sum(x['amount']) != 0:
                return np.average(
                    x['price'],
                    weights=x['amount'],
                    returned=True
                )
            else:
                return np.nan

        if datetime is None:
            return self.history_table.set_index(
                'datetime',
                drop=False
            ).sort_index().groupby('code').apply(weights).dropna()
        else:
            return self.history_table.set_index(
                'datetime',
                drop=False
            ).sort_index().loc[:datetime].groupby('code').apply(weights
                                                               ).dropna()
747003
def values(self, dtype, dates, sids):
        
        shape = (len(dates), len(sids))
        return {
            datetime64ns_dtype: self._datetime_values,
            float64_dtype: self._float_values,
            int64_dtype: self._int_values,
            bool_dtype: self._bool_values,
            object_dtype: self._object_values,
        }[dtype](shape)