【问题标题】:How to compute actions on DataFrame without being repetitive?如何在不重复的情况下计算 DataFrame 上的操作?
【发布时间】:2020-05-26 17:55:25
【问题描述】:

所以我正在尝试制作一种交易算法,到目前为止,它只与一家公司合作,并且运行良好。本质上,它是与 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】:

    让 stock 成为一个元组 b/c 有时可以解决我的问题

    感谢您的宝贵时间

    【讨论】:

    • 感谢您的回复。我尝试将其设为元组,但仍然收到相同的错误。
    猜你喜欢
    • 2012-07-13
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 2014-01-16
    • 2020-11-07
    • 2019-02-22
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多