从TWS IB提取的基础数据缺少最后一段代码

2024-06-28 19:42:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我从Stackoverflow中的一个已回答的查询中获取了下面的代码(不幸的是,我无法给出完整的评分,因为我无法再找到该页面)。我把它改了一点以符合我的目的。 我想从路透社的历史数据(基本数据)中提取一系列股票。下面的代码工作正常,但它只获取最后的股票代码数据。我知道我需要建立一个while循环,但我尝试了很多次,都没有成功。我相信这是一个快速解决方案,但由于我对编码和python一般来说都是新手,所以我找不到解决方案。任何帮助都将不胜感激

#Import all libriaries 
from ib.opt import ibConnection, message
from time import sleep
import lxml.etree
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
from IPython.core.debugger import set_trace
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.common import *  
from ibapi.contract import Contract 

#upload excel file of list of company tickers you want to review
us_list= pd.read_excel(r'C:\TWS API\Request Reuters data\Quant Project IB TWS_test.xlsx', engine='openpyxl')

stocksList = us_list[['TICKER']]
stocksList

def fundamentalData_handler(msg):
    global imported
    imported = msg.data

def error_handler(msg):
    pass

# processing of the lines in financial statements
def extractVauleFromLineItem(fiscalperiod, code): 
    stage1 = fiscalperiod.find(name='lineitem', coacode=code)
    if (not stage1 is None):
        stage2 = stage1.get_text()
        if (stage2 == stage2):
            stage3 = float(stage2)
            if (stage3 == stage3):
                return (stage3)
            else:
                return (0.0)
                        
result = pd.DataFrame(columns =['Year', 'Ticker','control','TotalRevenue', 'GrossProfit', 'CommonSharesOutstanding','DilutedNormalizedEPS', 'totalCash', 'TotalDebt','Dividends'])

outcomes = []

for i, row in stocksList.iterrows():
    contract = Contract()
    contract.symbol = row['TICKER']
    contract.secType = "STK"
    contract.currency = "USD"
    contract.exchange = "SMART"


    tws = ibConnection("127.0.0.1",port=7497, clientId=901)
    tws.register(error_handler, message.Error)
    tws.register(fundamentalData_handler, message.fundamentalData)
    tws.connect()
    tws.reqFundamentalData(1,contract,'ReportsFinStatements')
    sleep(1)
    tws.disconnect()
    print(contract.symbol) 
    
    soup = BeautifulSoup(imported) # library for processing of the obtained XML data
    data = []
    print(soup.find(name='issueid', type="Ticker").get_text())
    print(soup.find(name='coid', type="CompanyName").get_text()) 
    
    # I found that IB API is not very stable. 
    # Sometimes it returns data of the wrong company. 
    # So the control is important
    print('Control -',contract.symbol == soup.find(name='issueid', type="Ticker").get_text())
    print()
    
    for fiscalperiod in soup.find_all(name="fiscalperiod", type="Annual"):
        year = fiscalperiod['fiscalyear']
        TotalRevenue = extractVauleFromLineItem(fiscalperiod, 'RTLR')
        GrossProfit = extractVauleFromLineItem(fiscalperiod, 'SGRP')
        CommonSharesOutstanding = extractVauleFromLineItem(fiscalperiod, 'QTCO')
        DilutedNormalizedEPS = extractVauleFromLineItem(fiscalperiod, 'VDES')
        totalCash = extractVauleFromLineItem(fiscalperiod, 'OTLO') 
        TotalDebt = extractVauleFromLineItem(fiscalperiod, 'STLD')
        Dividends = extractVauleFromLineItem(fiscalperiod, 'FCDP')
        
    
        thisYearData = (year,contract.symbol, (contract.symbol == soup.find(name='issueid', type="Ticker").get_text()),TotalRevenue , GrossProfit, CommonSharesOutstanding, totalCash, TotalDebt, Dividends)    
        data.append(thisYearData)
        
    df_data = pd.DataFrame(data, columns =['Year','control','TotalRevenue', 'GrossProfit', 'CommonSharesOutstanding','DilutedNormalizedEPS', 'totalCash', 'TotalDebt','Dividends'])

    df_data = df_data.sort_values(by=['Year'])

Tags: oftextnamefromimportdatagetfind