【发布时间】:2019-05-10 13:52:19
【问题描述】:
我正在尝试从 IBAPI 下载历史数据,由于我对编码不是那么精通,我想出了一个计划,为每只我想要数据的股票编写单独的文件,并让 1 个主文件运行所有这些文件。 问题是我每次只能请求 1 个股票,所以在第一个完成下载后,我希望主文件运行下一个程序。
过去几天我尝试了多种不同的方法,但由于某种原因 Python 没有杀死第一个脚本,我无法让它工作。
到目前为止我所尝试的:
import AAPL
import GOOG
import sys
import sleep
AAPL.main()
time.sleep(10)
sys.exit(AAPL)
GOOG.main()
还有一些不同的变体,例如
terminate, kill()
奇怪的是,当我尝试共享的第一行代码时,却替换了
AAPL.main() & GOOG.main()
与
print("Running") & print("terminate")
我确实收到“终止”作为结果,而 GOOG.main() 不是这种情况
谁能帮我解决这个问题?
编辑: AAPL.py的代码,和GOOG.py一样:
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
import sys
def print_to_file(*args):
with open('AAPL.txt', 'a') as fh:
fh.write(' '.join(map(str,args)))
fh.write('\n')
print = print_to_file
class TestApp(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
Layout = "{!s:1} {!s:2} {!s:3} {!s:4} {!s:5} {!s:6} {!s:7} {!s:8} {!s:8} '\n'"
print(Layout.format("Ticker;", "Date;", "None;", "Time;", "Open;", "High;", "Low;", "Close;", "Volume"))
def historicalData(self, reqId, bar):
print("AAPL", ";", bar.date.replace(' ', '; '), ";", bar.open, ";", bar.high, ";", bar.low, ";", bar.close, ";", bar.volume)
def main():
app = TestApp()
app.connect("127.0.0.1", 7497, 0)
contract = Contract ()
contract.symbol = "AAPL"
contract.secType = "STK"
contract.exchange = "SMART"
contract.currency = "USD"
contract.primaryExchange = "NASDAQ"
app.reqHistoricalData(0, contract, "20180201 10:00:00", "1 D", "1 min", "TRADES", 0, 1, False, [])
app.run()
if __name__ == "__main__":
main()
单独运行它会给我这只股票所需的结果,但因为它不会在几秒钟后停止该功能,所以当我尝试运行多个时它不起作用
【问题讨论】:
-
一切都取决于
main函数的样子。如果AAPL.main()没有自行返回,您将无法在单线程设置中对其进行任何操作。 -
也许您的 AAPL 和 GOOG 中的主要功能根本不会返回。为我们提供这两个文件的主要代码。或者只使用线程,因为线程可以同时运行。
-
谢谢你的回答,我会更新我的帖子并添加AAPL文件,和GOOG一样
-
我已经更新了我的帖子,它现在包含我的代码。我是否必须将我的 main 替换为线程,或者在我想尝试从中运行所有内容的文件中替换?
标签: python python-3.x pycharm interactive-brokers