I have a python script that creates a DataFrame df, conencts to an API, and appends data to the DataFrame in a function. However the dataframe is empty outside of the function.
The function is "get_stock_price(client, ticker, option_dates, df)" I've shortened the code to show the part where I try appending to the df.
#rewrite with one reqMktData and tickType only
from datetime import datetime
from threading import Thread
import time
from ibapi.client import EClient, Contract
from ibapi.wrapper import EWrapper
from ibapi.utils import iswrapper
import math
import pandas as pd
import numpy as np
df = pd.DataFrame([], columns=['Underlying', 'Expiry', 'Strike', 'Right'])
class TestApp(EWrapper,EClient):
def __init__(self, addr, port, client_id):
EWrapper.__init__(self)
EClient. __init__(self, self)
# Initialize variables
# Connect to TWS API
#--functions that connect to API to get data---
def get_stock_price(client, ticker, option_dates, df):
#set contract and call API functions
#get strikes between q_up and q_down, append to df?
for x in range(len(option_dates)):
for strike in client.strikes:
if strike > q_down[x] and strike < q_up[x]:
df=df.append({
'Underlying': ticker,
'Expiry': option_dates[x],
'Strike': strike,
'Strike': strike,
'Right' : 'C',
}, ignore_index=True)
return df
df=df.reindex(df.index.repeat(2))
df=df.reset_index(drop=True)
print(df)
df['Underlying']='test'
return(df)
def main():
client = TestApp('127.0.0.1', 7497, 126)
ticker = 'AMD'
option_dates = ['20200821', '20200918', '20201016']
get_stock_price(client, ticker, option_dates, df)
client.done=True
client.disconnect()
print('try df again')
print(df)
if __name__ == "__main__":
main()
From reading answers on another question I tried adding
return df
After the append, also tried:
return df.append({
'Underlying': ticker,
'Expiry': option_dates[x],
'Strike': strike,
'Strike': strike,
'Right' : 'C',
}, ignore_index=True)
and as a test:
df['Underlying']='test'
return(df)
None of these seemed to work, when I print(df) at the end of the main() function it's empty.
Here's the output:
...
288 AMD 20201016 108.0 P
289 AMD 20201016 108.0 C
290 AMD 20201016 109.0 P
291 AMD 20201016 109.0 C
[292 rows x 4 columns]
try printing df again
Empty DataFrame
Columns: [Underlying, Expiry, Strike, Right]
Index: []
...