如何在DataFrame上计算动作而不重复?

问题描述 投票:0回答:1

所以我想做一个交易算法,到目前为止,只用了一家公司,效果还不错。本质上,它是一个移动平均线与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)

如果我想把多家公司的股票进行交叉,然后做一些类似的事情..:

stocks = ['AMD', 'BA', 'URI']
start = dt.datetime(2018, 1, 1)
end = dt.datetime(2020, 1, 1)
d = web.DataReader(stocks, 'yahoo', start, end)

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

python pandas dataframe algorithmic-trading pandas-datareader
1个回答
0
投票

使股票一个元组,因为一些时候,解决我的问题

谢谢你的时间

© www.soinside.com 2019 - 2024. All rights reserved.