【发布时间】:2020-09-12 11:16:55
【问题描述】:
所以我尝试使用 pandas 和 panadas 数据阅读器获取多个股票价格。如果我只尝试导入一个代码,它将运行良好,但如果我使用多个,则会出现错误。代码是:
import pandas as pd
import pandas_datareader as web
import datetime as dt
stocks = ['BA', 'AMD']
start = dt.datetime(2018, 1, 1)
end = dt.datetime(2020, 1, 1)
d = web.DataReader(stocks, 'yahoo', start, end)
虽然我得到了错误:
ValueError: Wrong number of items passed 2, placement implies 1
那么我该如何绕过它只允许通过 1 只股票。
到目前为止,我已经尝试使用 quandl 和 google,但它们也不起作用。我也尝试过pdr.get_data_yahoo,但我得到了相同的结果。我也尝试过yf.download(),但仍然遇到同样的问题。有没有人有任何想法来解决这个问题?谢谢。
编辑:完整代码:
import pandas as pd
import pandas_datareader as web
import datetime as dt
import yfinance as yf
import numpy as np
stocks = ['BA', 'AMD', 'AAPL']
start = dt.datetime(2018, 1, 1)
end = dt.datetime(2020, 1, 1)
d = web.DataReader(stocks, 'yahoo', start, end)
d['sma50'] = np.round(d['Close'].rolling(window=2).mean(), decimals=2)
d['sma200'] = np.round(d['Close'].rolling(window=14).mean(), decimals=2)
d['200-50'] = d['sma200'] - d['sma50']
_buy = -2
d['Crossover_Long'] = np.where(d['200-50'] < _buy, 1, 0)
d['Crossover_Long_Change']=d.Crossover_Long.diff()
d['buy'] = np.where(d['Crossover_Long_Change'] == 1, 'buy', 'n/a')
d['sell'] = np.where(d['Crossover_Long_Change'] == -1, 'sell', 'n/a')
pd.set_option('display.max_rows', 5093)
d.drop(['High', 'Low', 'Close', 'Volume', 'Open'], axis=1, inplace=True)
d.dropna(inplace=True)
#make 2 dataframe
d.set_index(d['Adj Close'], inplace=True)
buy_price = d.index[d['Crossover_Long_Change']==1]
sell_price = d.index[d['Crossover_Long_Change']==-1]
d['Crossover_Long_Change'].value_counts()
profit_loss = (sell_price - buy_price)*10
commision = buy_price*.01
position_value = (buy_price + commision)*10
percent_return = (profit_loss/position_value)*100
percent_rounded = np.round(percent_return, decimals=2)
prices = {
"Buy Price" : buy_price,
"Sell Price" : sell_price,
"P/L" : profit_loss,
"Return": percent_rounded
}
df = pd.DataFrame(prices)
print('The return was {}%, and profit or loss was ${} '.format(np.round(df['Return'].sum(), decimals=2),
np.round(df['P/L'].sum(), decimals=2)))
d
【问题讨论】:
-
@Trenton McKinney 感谢您的回复,我已经看过该页面并尝试过,但我仍然收到无法传递 2 个对象的相同错误。
-
对不起,我不明白这个问题 - 你不是通过了 2 只股票 ['BA', 'AMD'] 并且这段代码不工作吗?
标签: python pandas yahoo-finance pandas-datareader