Once trying to compare 30 lists and make an edge, if correlation is greater than 0.5, an error was detected at
foreach stock-prices [ prices1 i ]
saying
expecting anonymous command rather than list, block
stock-prices
; A list of lists, where each sub-list contains the price data for one stock
correlations
; A matrix to store correlation coefficients
to compute-correlations
; Initialize the correlations matrix with zeros
set correlations (list (map [ -> n-values 30 [ 0 ] ] range 30))
; Compute the correlation for each pair of stocks
foreach stock-prices [prices1 i] [
foreach stock-prices [prices2 j] [
if i != j [
let corr correlation-coefficient prices1 prices2
set correlations replace-item i correlations replace-item j (item j (item i correlations)) corr
]
]
]
end
to draw-edges
ask turtles [
let my-id stock-id
ask turtles with [stock-id > my-id] [
if item stock-id (item my-id correlations) > 0.5 [
create-link-with myself
]
]
]
end
to-report correlation-coefficient [prices1 prices2]
let n length prices1
let mean1 mean prices1
let mean2 mean prices2
let stddev1 standard-deviation prices1
let stddev2 standard-deviation prices2
let covariance mean (map [ (item ? prices1 - mean1) * (item ? prices2 - mean2) ] n-values n [ ? ])
report covariance / (stddev1 * stddev2)
end
1
I can definitely answer your question about the correct syntax to use if I understand your intention. But it took me a bit of puzzling, in order to figure out what I think you’re trying to do. So, when you write foreach stock-prices [ prices1 i ] [ ... ]
, am I right in thinking that you want to iterate over stock-prices
, referring to current index in stock-prices
as i
and the item at the i
th index as prices1
, in the block of code [ ... ]
? If that’s right, then I think this is the code that you want:
let indices (range length stock-prices)
foreach indices [
i ->
foreach indices [
j ->
if i != j [
let prices1 (item i stock-prices)
let prices2 (item j stock-prices)
let corr correlation-coefficient prices1 prices2
set correlations replace-item i correlations replace-item j (item j (item i correlations)) corr
]
]
]