0

I wanted to ask if anyone could help me out - I have looked at similar threads earlier but really cant find a solution for this one. I have a problem with below code, specifically I get error df_name.loc[ticker.time] = ticker.last NameError: name 'df_name' is not defined. It seems that code is not recognising variable name for the dataframe which I have created earlier within the function, the odd thing is that it seems to work if I create the dataframe outside of the function first, but I really need it to be inside of the function as it would allow me just to call a couple of variables to initiate the whole thing. Would appreciate any help, code below. For some reason below snippet seems to have indentation a bit off, in real version it's all correct.Thank you, Leo


def five_min_momentum_stock(contract_ticker, df_name):
contract_name = Stock(contract_ticker, 'SMART', 'USD')
ib.qualifyContracts(contract_name)
ib.reqMktData(contract_name)

df_name = pd.DataFrame(columns=['date', 'last'])
df_name.set_index('date', inplace=True)

def new_data(tickers):
    for ticker in tickers:
        global df_name
        df_name.loc[ticker.time] = ticker.last
    print(df_name)
    five_mins_ago = df_name.index[-1] - pd.Timedelta(minutes=1)

    if df_name.index[0] < five_mins_ago:
        df_name = df_name[five_mins_ago:]

        price_min = df_name['last'].min()
        price_max = df_name['last'].max()

        if df_name['last'].iloc[-1] > price_min * 1.001:
            place_order('BUY')

        elif df_name['last'].iloc[-1] < price_max * 0.999:
            place_order('SELL')

def place_order(direction):
    contract_order = MarketOrder(direction, 1)
    trade = ib.placeOrder(contract_name, contract_order)
    time.sleep(3)
    #ib.sleep(3)
    if trade.orderStatus.status == 'PendingSubmit':
        ib.disconnect()
        quit(0)

ib.pendingTickersEvent += new_data

five_min_momentum_stock('GME', 'gme_frame')

ib.run()

1 Answers1

0

As suggested by Amit Vikram Singh above, using nonlocal in front of the variable that sits in a different function worked for me!