我正在尝试创建一个python数据框架来跟踪我的股票购买,出售和利润。现在,我有一个熊猫数据框,其中一栏显示价格,另一栏中显示买入-持有-持有触发以及时间戳。
我试图创建一个数据框来跟踪买入卖价和交易利润,但是并没有解决,很难找到要更新的最后一笔交易。在这里,我正在尝试为交易创建数据框架
Tdf.tail的错误和当前输出
Empty DataFrame
Columns: [Buy, Sell, Profit]
Index: []
single positional indexer is out-of-bounds
df是什么样子
timestamp Price decide
2019-08-19 3.0000 1.0
2019-08-20 2.6200 0.0
2019-08-21 2.3200 0.0
2019-08-22 2.1400 0.0
2019-08-23 1.9500 -1.0
Price = [['2019-08-19',3.0000,1.0],['2019-08-20',2.6200,0.0],['2019-08-21',2.3200,0.0],['2019-08-22',2.1400,0.0],['2019-08-23',1.9500,-1.0]]
df = pd.DataFrame(Price,columns = ['timestamp','Price','decide'])
df.set_index('timestamp',inplace=True)
Trades = []
Tdf = pd.DataFrame(Trades,columns = ['Buy','Sell','Profit'])
for y in df.index.values:#Buy = 1.0 , Sell = -1.0
if df['decide'].iloc[y] == 1.0:
Tdf.append({'Buy' : df['Price'][y]},ignore_index=True)
if df['decide'].iloc[y] == -1.0:
profit = df['Price'].iloc[y] - Tdf['Buy'].iloc[-1]
Tdf.at[-1,'Sell'] = df['Price'].iloc[y]
Tdf.at[-1,'Profit'] = profit
预期是看到Tdf看起来像
buy sell profit
0 3.00 1.95 -1.05
答案 0 :(得分:0)
这就是我要做的:
df = df[-30:]
df.reset_index(inplace=True)
try:
for y in df.index.values:
if y == 0 and df['buy_sell'].iloc[y] == 1.0:
Tdf.at[y,'Buy'] = df['Price'].iloc[y]
buyIndex = y
if df['buy_sell_hold'].iloc[y] == 1.0:
Tdf.at[y,'Buy'] = df['Price'].iloc[y]
buyIndex = y
if y == 0 and df['buy_sell_hold'].iloc[y] == -1.0:
print('sold something we did not buy')
elif df['buy_sell_hold'].iloc[y] == -1.0:
profit = df['Price'].iloc[y] - Tdf['Buy'].iloc[-1]
Tdf.at[buyIndex,'Sell'] = df['Price'].iloc[y]
Tdf.at[buyIndex,'Profit'] = profit