Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
新手在Python上卡住了Quandl ValueError_Python_Pandas_Numpy_Dataframe_Quandl - Fatal编程技术网

新手在Python上卡住了Quandl ValueError

新手在Python上卡住了Quandl ValueError,python,pandas,numpy,dataframe,quandl,Python,Pandas,Numpy,Dataframe,Quandl,我试图用一组股票符号来计算夏普比率。该代码适用于前5个库存符号,但在6个符号后停止工作 我在文档中搜索了可能是ValueError消息的维度错误,但没有发现任何可能性。我还搜索了Quandl和Google,查找我得到的错误,但没有找到具体的结果 如果有人能让我知道我做错了什么,那就太好了。我对编码很陌生 # import needed modules import quandl import pandas as pd import numpy as np i

我试图用一组股票符号来计算夏普比率。该代码适用于前5个库存符号,但在6个符号后停止工作

我在文档中搜索了可能是ValueError消息的维度错误,但没有发现任何可能性。我还搜索了Quandl和Google,查找我得到的错误,但没有找到具体的结果

如果有人能让我知道我做错了什么,那就太好了。我对编码很陌生

   # import needed modules
    import quandl
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt

    # get adjusted closing prices of 5 selected companies with Quandl
    quandl.ApiConfig.api_key = 'oskr4yzppjZwxgJ7zNra'
    selected = ['TGT', 'AAPL', 'MSFT', 'FCN', 'TSLA', 'SPY', 'XLV', 'BRK.B', 'WMT', 'JPM']
    data = quandl.get_table('WIKI/PRICES', ticker = selected,
                        qopts = { 'columns': ['date', 'ticker', 'adj_close'] },
                        date = { 'gte': '2009-1-1', 'lte': '2019-12-31'}, paginate=True)

    # reorganize data pulled by setting date as index width
    # columns of tickers and their corresponding adjusted prices
    clean = data.set_index('date')
    table = clean.pivot(columns='ticker')

    # calculate daily and annual returns of the stocks
    returns_daily = table.pct_change()
    returns_annual = returns_daily.mean() * 250

    # get daily and covariance of returns of the stock
    cov_daily = returns_daily.cov()
    cov_annual = cov_daily * 250

    # empty lists to store returns, volatility and weights of imiginary portfolios
    port_returns = []
    port_volatility = []
    sharpe_ratio = []
    stock_weights = []

    # set the number of combinations for imaginary portfolios
    num_assets = len(selected)
    num_portfolios = 50000

    # set random seed for reproduction's sake
    np.random.seed(101)

    # populate the empty lists with each portfolios returns,risk and weights
    for single_portfolio in range(num_portfolios):
        weights = np.random.random(num_assets)
        weights /= np.sum(weights)
        returns = np.dot(weights, returns_annual)
        volatility = np.sqrt(np.dot(weights.T, np.dot(cov_annual, weights)))
        sharpe = returns / volatility
        sharpe_ratio.append(sharpe)
        port_returns.append(returns)
        port_volatility.append(volatility)
        stock_weights.append(weights)

    # a dictionary for Returns and Risk values of each portfolio
    portfolio = {'Returns': port_returns,
                'Volatility': port_volatility,
                 'Sharpe Ratio': sharpe_ratio}

    # extend original dictionary to accomodate each ticker and weight in the portfolio
    for counter,symbol in enumerate(selected):
        portfolio[symbol+' weight'] = [weight[counter] for weight in stock_weights]

    # make a nice dataframe of the extended dictionary
    df = pd.DataFrame(portfolio)

    # get better labels for desired arrangement of columns
    column_order = ['Returns', 'Volatility', 'Sharpe Ratio'] + [stock+' weight' for stock in selected]

    # reorder dataframe columns
    df = df[column_order]

    # find min Volatility & max sharpe values in the dataframe (df)
    min_volatility = df['Volatility'].min()
    max_sharpe = df['Sharpe Ratio'].max()

    # use the min, max values to locate and create the two special portfolios
    sharpe_portfolio = df.loc[df['Sharpe Ratio'] == max_sharpe]
    min_variance_port = df.loc[df['Volatility'] == min_volatility]

    # plot the efficient frontier with a scatter plot
    plt.style.use('seaborn-dark')
    df.plot.scatter(x='Volatility', y='Returns', c='Sharpe Ratio',
                    cmap='RdYlGn', edgecolors='black', figsize=(10, 8), grid=True)
    plt.scatter(x=sharpe_portfolio['Volatility'], y=sharpe_portfolio['Returns'], c='red', marker='D', s=200)
    plt.scatter(x=min_variance_port['Volatility'], y=min_variance_port['Returns'], c='blue', marker='D', s=200)
    plt.xlabel('Volatility (Std. Deviation)')
    plt.ylabel('Expected Returns')
    plt.title('Efficient Frontier')
    plt.show() 

    # print the details of the 2 special portfolios
    print(min_variance_port.T)
    print(sharpe_portfolio.T)
我得到的错误是:
ValueError回溯(最近一次调用)
在里面
42权重=np.random.random(num_资产)
43权重/=np.和(权重)
--->44收益率=np.点(权重、年收益率)
45波动率=np.sqrt(np.dot(权重T,np.dot(cov_年度,权重)))
46夏普=收益率/波动率
ValueError:形状(10,)和(7,)未对齐:10(尺寸0)!=7(尺寸0)
    ValueError                                Traceback (most recent call last)
    <ipython-input-8-3e66668bf017> in <module>
         42     weights = np.random.random(num_assets)
         43     weights /= np.sum(weights)
    ---> 44     returns = np.dot(weights, returns_annual)
         45     volatility = np.sqrt(np.dot(weights.T, np.dot(cov_annual, weights)))
         46     sharpe = returns / volatility

    ValueError: shapes (10,) and (7,) not aligned: 10 (dim 0) != 7 (dim 0)