本文整理汇总了Python中quandl.get方法的典型用法代码示例。如果您正苦于以下问题:Python quandl.get方法的具体用法?Python quandl.get怎么用?Python quandl.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类quandl
的用法示例。
在下文中一共展示了quandl.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_price_quandl
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def get_price_quandl(self,ticker ):
try:
if Cache.data_request_delay != None:
time.sleep(Cache.data_request_delay)
if Cache.quandl_key != None:
df = quandl.get("WIKI/"+ticker, authtoken=Cache.quandl_key)
else:
df = quandl.get("WIKI/"+ticker)
except quandl.errors.quandl_error.NotFoundError as e:
print("WIKI/"+ticker)
raise e
df = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']]
df.rename(columns={'Adj. Open':'Open','Adj. High':'High', 'Adj. Low':'Low', 'Adj. Close':'Close', 'Adj. Volume':'Volume'},inplace = True)
df.dropna(inplace=True)
return df
示例2: getStocksList
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def getStocksList():
# https://www.quandl.com/api/v3/databases/HKEX/codes?api_key=X1xf_1YJLkT9mdxDj13v
# down the zip file above and unzip to the _share folder
# rename the stock code name from "HKEX/XXXX" to "XXXX"
Config = configparser.ConfigParser()
Config.read("../../config.ini")
dir = Config.get('Paths', 'STOCK_HK')
if os.path.exists(dir) == False:
os.makedirs(dir)
share_dir = dir + Config.get('Paths', 'CSV_SHARE')
if os.path.exists(share_dir) == False:
os.makedirs(share_dir)
filename = share_dir + 'HKEX-datasets-codes.csv'
if os.path.exists(filename):
listData = pd.read_csv(filename)
listData = listData[listData['Code'].astype(str).str.isdigit()]
return listData['Code'].values.tolist()
return []
示例3: ef_minimum_volatility
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def ef_minimum_volatility(self, verbose=False):
"""Interface to
``finquant.efficient_frontier.EfficientFrontier.minimum_volatility``.
Finds the portfolio with the minimum Volatility.
:Input:
:verbose: ``boolean`` (default= ``False``), whether to print out properties
or not.
:Output:
:df_weights: a ``pandas.DataFrame`` of weights/allocation of stocks within
the optimised portfolio.
"""
# let EfficientFrontier.efficient_frontier handle input arguments
# get/create instance of EfficientFrontier
ef = self._get_ef()
# perform optimisation
opt_weights = ef.minimum_volatility()
# if verbose==True, print out results
ef.properties(verbose=verbose)
return opt_weights
示例4: ef_maximum_sharpe_ratio
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def ef_maximum_sharpe_ratio(self, verbose=False):
"""Interface to
``finquant.efficient_frontier.EfficientFrontier.maximum_sharpe_ratio``.
Finds the portfolio with the maximum Sharpe Ratio, also called the
tangency portfolio.
:Input:
:verbose: ``boolean`` (default= ``False``), whether to print out properties
or not.
:Output:
:df_weights: a ``pandas.DataFrame`` of weights/allocation of stocks within
the optimised portfolio.
"""
# let EfficientFrontier.efficient_frontier handle input arguments
# get/create instance of EfficientFrontier
ef = self._get_ef()
# perform optimisation
opt_weights = ef.maximum_sharpe_ratio()
# if verbose==True, print out results
ef.properties(verbose=verbose)
return opt_weights
示例5: ef_efficient_return
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def ef_efficient_return(self, target, verbose=False):
"""Interface to
``finquant.efficient_frontier.EfficientFrontier.efficient_return``.
Finds the portfolio with the minimum Volatility for a given target return.
:Input:
:target: ``float``, the target return of the optimised portfolio.
:verbose: ``boolean`` (default= ``False``), whether to print out properties
or not.
:Output:
:df_weights: a ``pandas.DataFrame`` of weights/allocation of stocks within
the optimised portfolio.
"""
# let EfficientFrontier.efficient_frontier handle input arguments
# get/create instance of EfficientFrontier
ef = self._get_ef()
# perform optimisation
opt_weights = ef.efficient_return(target)
# if verbose==True, print out results
ef.properties(verbose=verbose)
return opt_weights
示例6: ef_efficient_volatility
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def ef_efficient_volatility(self, target, verbose=False):
"""Interface to
``finquant.efficient_frontier.EfficientFrontier.efficient_volatility``.
Finds the portfolio with the maximum Sharpe Ratio for a given
target Volatility.
:Input:
:target: ``float``, the target Volatility of the optimised portfolio.
:verbose: ``boolean`` (default= ``False``), whether to print out properties
or not.
:Output:
:df_weights: a ``pandas.DataFrame`` of weights/allocation of stocks within
the optimised portfolio.
"""
# let EfficientFrontier.efficient_frontier handle input arguments
# get/create instance of EfficientFrontier
ef = self._get_ef()
# perform optimisation
opt_weights = ef.efficient_volatility(target)
# if verbose==True, print out results
ef.properties(verbose=verbose)
return opt_weights
示例7: ef_plot_optimal_portfolios
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def ef_plot_optimal_portfolios(self):
"""Interface to
``finquant.efficient_frontier.EfficientFrontier.plot_optimal_portfolios``.
Plots markers of the optimised portfolios for
- minimum Volatility, and
- maximum Sharpe Ratio.
"""
# let EfficientFrontier.efficient_frontier handle input arguments
# get/create instance of EfficientFrontier
ef = self._get_ef()
# plot efficient frontier
ef.plot_optimal_portfolios()
# optimising the investments with the efficient frontier class
示例8: mc_optimisation
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def mc_optimisation(self, num_trials=1000):
"""Interface to
``finquant.monte_carlo.MonteCarloOpt.optimisation``.
Optimisation of the portfolio by performing a Monte Carlo
simulation.
:Input:
:num_trials: ``int`` (default: ``1000``), number of portfolios to be
computed, each with a random distribution of weights/allocation
in each stock.
:Output:
:opt_w: ``pandas.DataFrame`` with optimised investment strategies for maximum
Sharpe Ratio and minimum Volatility.
:opt_res: ``pandas.DataFrame`` with Expected Return, Volatility and Sharpe Ratio
for portfolios with minimum Volatility and maximum Sharpe Ratio.
"""
# dismiss previous instance of mc, as we are performing a new MC optimisation:
self.mc = None
# get instance of MonteCarloOpt
mc = self._get_mc(num_trials)
opt_weights, opt_results = mc.optimisation()
return opt_weights, opt_results
示例9: download_instrument
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def download_instrument(self, instrument, **kwagrs):
recent = kwagrs.get('recent', False)
if recent:
c = instrument.roll_progression().tail(1).iloc[0] - 100 #-100 here rolls it back one year
else:
c = str(instrument.first_contract) # Download all contracts
fail_count = 0
# Since quandl doesn't seem to have an API function to list all available contracts,
# we just loop and download them one by one until no data can be found for the next
logger.info('Downloading contracts for instrument: %s' % instrument.name)
while fail_count <= 12:
# print(c)
if self.download_contract(instrument, c):
fail_count = 0
else:
fail_count += 1
# Just try one more time in case of a network error
self.download_contract(instrument, c)
c = instrument.next_contract(c)
logger.debug('More than 12 missing contracts in a row - ending the downloading'
' for the instrument %s' % instrument.name)
return True
示例10: test
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def test(year, stock, window=10, up=0.05, down=0.05, get_plots=True, verbose=True):
quandl.ApiConfig.api_key = "FDEDsMbK1E2t_PMf7X3M"
df = quandl.get('NSE/ZEEL', start_date='2017-01-01', end_date='2017-12-31')
prices = df["Close"]
dates = df["Date"]
agent = EMA_Agent(window, up, down)
test = Backtest(agent, 10000)
output = test.run(prices)
# class Evaluation takes for initialization - prices, output, name of algorithm, name of security
evaluator = Evaluation(prices, dates, output, "EMA", stock)
return evaluator.complete_evaluation(get_plots, verbose)
示例11: _open_ticker_price_online
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def _open_ticker_price_online(self, ticker):
"""
Opens the CSV online from yahoo finance, then store in a dictionary.
"""
if self.end_date is not None:
ed = self.end_date
else:
ed = datetime.today()
if self.start_date is not None:
sd = self.start_date
else:
sd = ed- timedelta(days = 365)
data = quandl.get('wiki/'+ticker, start_date=sd, end_date=ed, authtoken='ay68s2CUzKbVuy8GAqxj')
self.tickers_data[ticker] = data
self.tickers_data[ticker]["Ticker"] = ticker
示例12: _fetch
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def _fetch(self):
feed = {}
try:
for market in self.datasets:
quote, base = market.split(":")
if base not in feed:
feed[base] = {}
prices = []
for dataset in self.datasets[market]:
data = quandl.get(dataset, rows=1, returns='numpy')
feed[base][quote] = {"price": data[0][1],
"volume": 1.0}
except Exception as e:
raise Exception("\nError fetching results from {1}! ({0})".format(str(e), type(self).__name__))
return feed
示例13: get_data_from_quandl
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def get_data_from_quandl(stocks, save=True):
"""
Returned dataframe is indexed by Date. So, no need to externally parse dates and change index column.
:param stocks: Stocks to be downloaded
:param save: If True, then save the downloaded stock.
:return: A list of pandas dataframe containing the details of requested stocks.
"""
quandl.ApiConfig.api_key = QUANDL_KEY
df_list = []
for stock in stocks:
print("DOWNLOADING {0} DATA".format(stock))
df = quandl.get(stock, start_date=RETRIEVAL_START_DATE, end_date=RETRIEVAL_END_DATE)
df = df[REL_DATA_COLUMNS]
df_list.append(df)
if save:
df.to_csv('{0}/{1}.csv'.format(DATA_DIR, stock.split('/')[-1]))
return df_list
示例14: is_trading_day
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def is_trading_day(day: datetime.datetime):
s = redis.StrictRedis(
host=config.get('REDIS', 'host', fallback='localhost'),
db=config.getint('REDIS', 'db', fallback=1), decode_responses=True)
return day, day.strftime('%Y%m%d') in (s.get('TradingDay'), s.get('LastTradingDay'))
# async with aiohttp.ClientSession() as session:
# await max_conn_cffex.acquire()
# async with session.get(
# 'http://{}/fzjy/mrhq/{}/index.xml'.format(cffex_ip, day.strftime('%Y%m/%d')),
# allow_redirects=False) as response:
# max_conn_cffex.release()
# return day, response.status != 302
示例15: update_from_shfe
# 需要导入模块: import quandl [as 别名]
# 或者: from quandl import get [as 别名]
def update_from_shfe(day: datetime.datetime):
try:
async with aiohttp.ClientSession() as session:
day_str = day.strftime('%Y%m%d')
await max_conn_shfe.acquire()
async with session.get('http://{}/data/dailydata/kx/kx{}.dat'.format(shfe_ip, day_str)) as response:
rst_json = await response.json()
max_conn_shfe.release()
for inst_data in rst_json['o_curinstrument']:
"""
{'OPENINTERESTCHG': -11154, 'CLOSEPRICE': 36640, 'SETTLEMENTPRICE': 36770, 'OPENPRICE': 36990,
'PRESETTLEMENTPRICE': 37080, 'ZD2_CHG': -310, 'DELIVERYMONTH': '1609', 'VOLUME': 51102,
'PRODUCTSORTNO': 10, 'ZD1_CHG': -440, 'OPENINTEREST': 86824, 'ORDERNO': 0, 'PRODUCTNAME': '铜 ',
'LOWESTPRICE': 36630, 'PRODUCTID': 'cu_f ', 'HIGHESTPRICE': 37000}
"""
# error_data = inst_data
if inst_data['DELIVERYMONTH'] == '小计' or inst_data['PRODUCTID'] == '总计':
continue
if '_' not in inst_data['PRODUCTID']:
continue
DailyBar.objects.update_or_create(
code=inst_data['PRODUCTID'].split('_')[0] + inst_data['DELIVERYMONTH'],
exchange=ExchangeType.SHFE, time=day, defaults={
'expire_date': inst_data['DELIVERYMONTH'],
'open': inst_data['OPENPRICE'] if inst_data['OPENPRICE'] else inst_data['CLOSEPRICE'],
'high': inst_data['HIGHESTPRICE'] if inst_data['HIGHESTPRICE'] else
inst_data['CLOSEPRICE'],
'low': inst_data['LOWESTPRICE'] if inst_data['LOWESTPRICE']
else inst_data['CLOSEPRICE'],
'close': inst_data['CLOSEPRICE'],
'settlement': inst_data['SETTLEMENTPRICE'] if inst_data['SETTLEMENTPRICE'] else
inst_data['PRESETTLEMENTPRICE'],
'volume': inst_data['VOLUME'] if inst_data['VOLUME'] else 0,
'open_interest': inst_data['OPENINTEREST'] if inst_data['OPENINTEREST'] else 0})
except Exception as e:
print('update_from_shfe failed: %s' % e)