Home > Software engineering >  Function for tracking trading operations with stock
Function for tracking trading operations with stock

Time:12-24

I have the df with Date, open prices of the stock, buy and sell indicators. I need to make a function that could count all these operations with my budget.

    Date        Open       Buy Sell
0   2019-08-27  36.270000   1   0
1   2019-10-11  31.740000   0   1
2   2020-03-18  28.320000   1   0
3   2020-06-03  41.380001   0   1
4   2020-11-12  61.610001   1   0
5   2020-12-02  69.120003   0   1
6   2021-03-24  64.500000   1   0
7   2021-06-07  67.269997   0   1

So if I have 1 in Buy column I need to buy stocks with all the money in budget. After it I need to sell all at open price where df['Buy'] == 0. I have tried to create such but it's wrong and I don't have a clue how to fix it.

def profit(x):
    budget = 100000
    stocks = 0
    for i in df['Buy_ind']:
        if x == 1:
            budget = budget % df['Open'][i]
            stocks = budget // df['Open'][i]
        if x == 0:
            budget  = stocks * df['Open'][i]
    return i
profit()

CodePudding user response:

A simple version, cross validated with excel, but check anyways.:

import pandas as pd

df_stock = pd.DataFrame({'Date':['8/27/2019','10/11/2019','3/18/2020','6/3/2020','11/12/2020','12/2/2020','3/24/2021','6/7/2021'],
 'Open':[36.27,31.74,28.32,41.380001,61.610001,69.120003,64.5,67.269997,],  
'Buy':[1,0,1,0,1,0,1,0],
'Sell':[0,1,0,1,0,1,0,1],
})


def profit(df, budget):
    stocks = 0
    for idx, r in df.iterrows():
        if r['Buy'] ==1:
            stocks = round(budget//r['Open'],3)
            budget = round(budget%r['Open'] , 3)
            print(f'Buy {stocks} stocks at ', round(r['Open'],3), f'Remaining budget {budget}')

        if r['Sell'] == 1:
            budget = round(stocks*r['Open']   budget,3)
            stocks = 0
            print('Sold at ', round(r['Open'],3), 'new budget is ', budget)
            
    return budget


print(df_stock)
print('')

profit(df_stock, 10000)

**Output**

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/XdJWu.png

CodePudding user response:

budget = 100000
stocks = 0
for inx, row in df.iterrows():
    if row['Buy'] == 1:   
        stocks = budget // row['Open']
        budget = budget % row['Open']
    if row['Buy'] == 0:
        budget  = stocks * row['Open']
display(budget)

The answer was simple. I just didn't know how to work with each row in df: 'for inx, row' - is easy solution.

  • Related