Calling Amibroker from Python

Hi,

I would like to know if it would be possible to open amibroker from python , import the neccessary ascii files and then closing amibroker

import win32com.client as wcl
AB = wcl.Dispatch( 'Broker.Application' )
print ("Version", AB.Version)

2 Likes

I use this every day:

# -*- coding: utf-8 -*-
#
import os
import sys
import glob
import win32com.client

# import table:
# db - path to the AB database
# data - path and pattern of the files to import
# format - import format file
imp_tbl = [
    {'db': r"C:\Users\xxxx\Documents\AmiBroker\data\EURONEXT-Paris",
    'data': r"C:\Export\EURONEXT-Paris_*.csv",
    'format': r"gpw.format"},
    {'db': r"C:\Users\xxx\Documents\AmiBroker\data\IBEX",
    'data': r"C:\Export\IBEX_*.csv",
    'format': r"gpw.format"},
]


def ImportData(ab, lst):
    for l in lst:
        print("Loading database {}".format(os.path.split(l['db'])[1]))
        ab.LoadDatabase(l['db'])
        f_lst = sorted(set(glob.glob(l['data'])))
        for f in f_lst:
            try:
                print("Importing datafile {}, using format {}".format(f, l['format']))
                ab.Import(0, f, l['format'])
            except e:
                print("Error importing datafile {}".format(f))
            else:
                (newpath, filename) = os.path.split(f)
                os.rename(f, os.path.join(newpath, "archive", filename))
                print("Import complete")

        print("Saving Amibroker")
        ab.RefreshAll()
        ab.SaveDatabase()
        print("OK")


def main():
    oAB = win32com.client.Dispatch("Broker.Application")
    ImportData(oAB, imp_tbl)
    print("Terminated")
    oAB.Quit()
    return 0


if (__name__ == '__main__'):
    sys.exit(main())

Best regards,
Slawomir

10 Likes
# Code adapted from TJ's sample in documentation by pete@ov-trading.com
# File revision: $Revision: 203 $ 

import os
from win32com.client import Dispatch
import time


# START MODIFY TO FIT YOUR SETUP
# These pairs (tuples) contain a data folder and a format file which defines
# how the data is stored

data_folders = ("C:\\Users\\NSGupta\\data1\\20181203\\Files2", ".format")

# END MODIFY TO FIT YOUR SETUP

# Create AmiBroker object 

ab = Dispatch("Broker.Application")

# AB.Visible = True

print("Version",ab.version)

"""
time.sleep(300)

for (data_folder,format_file) in data_folders:
    for file in os.listdir(data_folder):
        print(file)
        
        print("Importing:", file, "using:", format_file)
        
        ab.Import(0, data_folder + "\\" + file, format_file)
        
        #if file[-3:].lower() == "csv":
        #    
        #    ab.Import(0, data_folder + "\\" + file, format_file)
        
ab.SaveDatabase()
"""

I am getting this error :


com_error Traceback (most recent call last)
C:\AnacondaPython3_6\DeepLearning_Udemy\lib\site-packages\win32com\client\dynamic.py in _GetGoodDispatch(IDispatch, clsctx)
88 try:
---> 89 IDispatch = pythoncom.connect(IDispatch)
90 except pythoncom.ole_error:

com_error: (-2147221005, 'Invalid class string', None, None)

During handling of the above exception, another exception occurred:

com_error Traceback (most recent call last)
in ()
21 # Create AmiBroker object
22
---> 23 ab = Dispatch("Broker.Application")
24
25 # AB.Visible = True

C:\AnacondaPython3_6\DeepLearning_Udemy\lib\site-packages\win32com\client_init_.py in Dispatch(dispatch, userName, resultCLSID, typeinfo, UnicodeToString, clsctx)
93 """
94 assert UnicodeToString is None, "this is deprecated and will go away"
---> 95 dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
96 return __WrapDispatch(dispatch, userName, resultCLSID, typeinfo, clsctx=clsctx)
97

C:\AnacondaPython3_6\DeepLearning_Udemy\lib\site-packages\win32com\client\dynamic.py in _GetGoodDispatchAndUserName(IDispatch, userName, clsctx)
112 else:
113 userName = str(userName)
--> 114 return (_GetGoodDispatch(IDispatch, clsctx), userName)
115
116 def _GetDescInvokeType(entry, invoke_type):

C:\AnacondaPython3_6\DeepLearning_Udemy\lib\site-packages\win32com\client\dynamic.py in _GetGoodDispatch(IDispatch, clsctx)
89 IDispatch = pythoncom.connect(IDispatch)
90 except pythoncom.ole_error:
---> 91 IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
92 else:
93 # may already be a wrapped class.

com_error: (-2147221005, 'Invalid class string', None, None)

If anyone can help , it would be welcome

This is some hilarious stuff that I occasionally come across :rofl: :rofl:

Anyway,
see this

import win32com.client
oAB = win32com.client.Dispatch("Broker.Application")

Probably import more stuff other than Dispatch alone

Is your Amibroker properly installed? This error usually means that python cannot find the "Broker.Application" object in your system / registry.

EDIT:
Also, check your Python's win32com and Amibroker's versions. Both must be the same : 32 or 64 bits. I think you won't access 32 bit Amibroker with 64 bit Python but I can't confirm this right now...

Best regards,
Slawomir

http://www.amibroker.com/kb/2015/01/12/ole-automation-scripts-with-32-and-64-bit/