Python 如何在不重复的情况下计算数据帧上的操作?

Python 如何在不重复的情况下计算数据帧上的操作?,python,pandas,dataframe,algorithmic-trading,pandas-datareader,Python,Pandas,Dataframe,Algorithmic Trading,Pandas Datareader,因此,我正在尝试制定一个交易算法,到目前为止,我只与一家公司合作,而且效果良好。本质上,这是一个移动平均线交叉与2和14天移动平均线。到目前为止,代码如下: import pandas as pd import pandas_datareader as web import datetime as dt import yfinance as yf import numpy as np start = dt.datetime(2018, 1, 1) end = dt.datetime(2020,

因此,我正在尝试制定一个交易算法,到目前为止,我只与一家公司合作,而且效果良好。本质上,这是一个移动平均线交叉与2和14天移动平均线。到目前为止,代码如下:

import pandas as pd
import pandas_datareader as web
import datetime as dt
import yfinance as yf
import numpy as np

start = dt.datetime(2018, 1, 1)
end = dt.datetime(2020, 1, 1)
d = web.DataReader('AMD', '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']
d
_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(df)
print(d)

我将收到一个问题,因为我需要为每个公司创建一个单独的数据框架,然后本质上为每个公司重新编写代码。有没有什么办法可以让我通过任意数量的公司,而不必重写整个代码,这样我就不会收到错误?有没有一种方法可以组合数据帧,这样就不必为每个数据帧创建列?

有时将stock设置为元组b/c,这样可以解决我的问题


感谢您抽出时间来解决我的问题。

在某些情况下,让库存成为元组b/c


感谢您抽出时间

感谢您的回复。我试着把它做成一个元组,但仍然收到同样的错误。谢谢你的回复。我试着把它变成一个元组,但仍然收到同样的错误。
stocks = ['AMD', 'BA', 'URI']
start = dt.datetime(2018, 1, 1)
end = dt.datetime(2020, 1, 1)
d = web.DataReader(stocks, 'yahoo', start, end)