Getting Single Stock Closing Price with Python and OLE

I've tried and adapted some codes that was shared here for getting single stock price through python and OLE with no success. Here is my python codes:

dataBasePath = "C:\\Amibroker\\DATAFEED\\JUC"

import win32com.client as wcl

# create an instance of Amibroker
try:
    AB = wcl.Dispatch("Broker.Application")
    print("[INFO] Amibroker instance created successfully.")
except Exception as e:
    print("[ERROR] Exception occurred while creating Amibroker instance: ", e)

# open a database
try:
    retLoadDatabase = AB.LoadDatabase(dataBasePath)
    if retLoadDatabase == True:
        print(f"[INFO] Database loaded successfully for dataBasePath={dataBasePath}")
    else:
        print(f"[ERROR] Error loading database dataBasePath={dataBasePath}.")
except Exception as e:
    print(f"[ERROR] Exception occurred while loading database dataBasePath={dataBasePath}: ", e)

# get the price of a stock
_ForDate = "20250528"
symbol = "BBCA"
stks = AB.Stocks
st = stks.Item( symbol )
qts = st.Quotations
qt = qts.Item( _ForDate )
OptC = qt.Close

print(f"[INFO] Stock Price is: {OptC}")

It throws error like this:

[INFO] Amibroker instance created successfully.
[INFO] Database loaded successfully for dataBasePath=C:\Amibroker\DATAFEED\JUC
Traceback (most recent call last):
  File "C:\Amibroker\Automation\get_price\get_price_juc.py", line 26, in <module>
    st = stks.Item( symbol )
TypeError: 'NoneType' object is not callable

I also made JS script version like this:

// This is NOT AFL but jscript
// Source: https://www.amibroker.com/guide/objects.html
// Amibroker OLE script for Check Price

var AB = new ActiveXObject("Broker.Application"); // creates AmiBroker object
var symbol = "BBCA" // get the active symbol name


// Get the stock price for the given symbol and date
stks = AB.Stocks
st = stks.Item( symbol )
qts = st.Quotations
qt = qts.Item( _ForDate )
OptC = qt.Close

WScript.echo("The stock price for " + symbol + " on " + _ForDate + " is: " + OptC);

And it also throws error like this:

Error: Unable to get property 'Close' of undefined or null or reference

At the end, I want loop ticker list from a csv file using python, check if those ticker touch closing price which is defined in my csv file and notify me regularly using windows task scheduler. But, using those two scripts above, they don't work because OptC value is null.

@BetaMaster In JScript, to avoid potential date ambiguities, you should pass the date as a string in the format "YYYY-MM-DD", e.g., "2025-05-22".

// This is NOT AFL but jscript

function padZero(n) {
    if (n < 10) {
        return "0" + n;
    } else {
        return "" + n;
    }
}

AB = new ActiveXObject("Broker.Application"); 

symbol = "QQQ"; 
y = 2008;
m = 2;
d = 6;
// if you get y,m,d from a JScript Date object keep in mind that months are numbered 0..11

stks = AB.Stocks;
st = stks.Item( symbol );
qts = st.Quotations;
dts = padZero(y) + "-" + padZero(m) + "-" + padZero(d); // NEED to pass as unambiguous string 
// iQty = qts.Count;
// WScript.Echo(" " + symbol + " has " + iQty + " bars - Requested date: " + dts);
qt = qts( dts);
if (qt != null)
{
	cl = qt.Close;
	WScript.Echo("The stock price for " + symbol + " on " + dts + " is: " + cl);
} 
else
{
	WScript.Echo("No stock price for " + symbol + " on " + dts);

}

This was discussed here long time ago.

I vaguely recall that Python's OLE implementation had some trouble with this type of variant conversion ((maybe I'm wrong... better try it).
If it does not work, a workaround is to perform a binary search through the quote collection (accessing each quote by numeric index) until you locate the desired date, or confirm that it’s not present.

2 Likes

@BetaMaster, reading your post more carefully, it seems that you're trying to retrieve recent quotes. In this case, whether you're using Python or JScript, you could loop from the most recent quote (i.e., the last one) - especially if you also need to check a few previous bars - or simply access the last quotation via its index if that's all you need.

1 Like

Thank you so much for your tips @beppe! Yes, you're right. I only need last quotation. I've deleted date variable and use the index instead. Here is my working Jscript codes for getting closing price through OLE:

// This is NOT AFL but jscript
// Source: https://www.amibroker.com/guide/objects.html
// Amibroker OLE script for Checking Closing Price of a Stock

var AB = new ActiveXObject("Broker.Application"); // creates AmiBroker object
var symbol = "BBRI" // get the active symbol name
var dataBasePath = "C:\\Amibroker\\DATAFEED\\JUC"

// Get the stock price for the given symbol
AB.LoadDatabase( dataBasePath ); // set the database path
stks = AB.Stocks
st = stks.Item( symbol )
qts = st.Quotations
qt = qts.Item( qts.Count - 1 ) // get the last quotation
closingprice = qt.Close

WScript.echo("The closing price for " + symbol + " stock is: " + closingprice);

And here is working python codes with OLE:

dataBasePath = "C:\\Amibroker\\DATAFEED\\JUC"

import win32com.client as wcl

# create an instance of Amibroker
try:
    AB = wcl.Dispatch("Broker.Application")
    print("[INFO] Amibroker instance created successfully.")
except Exception as e:
    print("[ERROR] Exception occurred while creating Amibroker instance: ", e)

# open a database
try:
    retLoadDatabase = AB.LoadDatabase(dataBasePath)
    if retLoadDatabase == True:
        print(f"[INFO] Database loaded successfully for dataBasePath={dataBasePath}")
    else:
        print(f"[ERROR] Error loading database dataBasePath={dataBasePath}.")
except Exception as e:
    print(f"[ERROR] Exception occurred while loading database dataBasePath={dataBasePath}: ", e)

# get the closing price of a stock
symbol = "BBRI"
stks = AB.Stocks( symbol )
qts = stks.Quotations
qt = qts.Count - 1  # Get the last quotation
closingprice = qts(qt).Close

print(f"[INFO] Stock Price is: {"{:,.0f}".format(closingprice)}")
1 Like