Hello there, I’m using @threads to accelerate my for loop, I don’t know how to push! a variable in if , I ask ChatGPT, it gives the code as following:
# Initialize an empty array to store symbols, shared across threads
lock = ReentrantLock()
low_σ = String[] # Array to store the satisfying codes
@threads for i in code
p = get_prices(
i, startdt = startdt, enddt = enddt, interval = "1d",
divsplits = true, exchange_local_time = true
) |> DataFrame
if p.close[end] < minimum(p.low) + std(p.low)
# Use a lock to safely modify the shared array from multiple threads
lock(lock) do
push!(low_σ, i)
end
end
end
but it throws an error as:
ERROR: TaskFailedException
nested task error: MethodError: objects of type ReentrantLock are not callable
The object of type `ReentrantLock` exists, but no method is defined for this combination of argument types when trying to treat it as a callable object.
It would be helpful if you could post a single-threaded example of what you want to do instead of the chat-GPT answer. Would this solve your problem: Thread-safe array building - #2 by yuyichao ?
The size of code is a little big (>3000), get_prices fetch data from
Yahoo Finance, I think the performance improvement using @threads may not be as significant, but it worth a try.
single-threaded example
using YFinance, Dates, Statistics
code = get_all_symbols("NYSE") # 3127-element Vector{String}
startdt = "2023-01-01"
enddt = today()
low_σ = String[]
for i in code
p = get_prices(
i, startdt = startdt, enddt = enddt, interval = "1d",
divsplits = true, exchange_local_time = true
) |> DataFrame
if p.close[end] < minimum(p.low) + std(p.low) # filter the stock which close price is lower than it's history minimum + standard deviation of history low price
push!(low_σ, i)
end
end
Regarding the error message:
The symbol lock already refers to the lock function exported from Base. In Julia you can’t have a variable named the same as an (imported) function. Changing your very first line to l = ReentrantLock() should make it work.