For some reason I don't understand, HOMER seems to prefer using energy from the grid even if I force it to use an electrolyzer and a fuel cell and there is enough excess energy available to refill the hydrogen tanks ... I thought the optimization was based on cost saving and not using grid energy should be cheaper than using it. no?
Yes, HOMER operates the dispatchable power sources in the economically optimal way, subject to its assumptions. In your case, the dispatchable sources are the fuel cell and the grid. Grid power costs $0.17/kWh, but what does fuel cell power cost? That depends on its output, since it has a fixed O&M cost per hour (independent of its output power) and a fuel cost that decreases on a per-kWh basis with increasing output (since its efficiency improves with increasing output). There is also a minimum load ratio of 1% on the fuel cell. The result is that fuel cell power (per kWh) is infinitely expensive at zero output, dropping with increasing output. At some output level, the fuel cell power cost must drop to below the grid power cost because HOMER is using the fuel cell a lot.
The key point is that if HOMER only needs a little bit of power from the dispatchable sources, it will choose the grid. If it needs a lot, it will choose the fuel cell. The following scatterplot proves that. I plotted the grid purchase power versus the net load, which is the primary load minus the PV array output. If positive, that's the amount of power that HOMER needs to get from a dispatchable power source. If negative, it's the surplus electricity available for electrolysis. The graph shows that HOMER buys from the grid only when the net load is either very small (when it does so because grid power is cheaper than fuel cell power) or above 500 kW (when it does so to avoid unmet load, since the fuel cell capacity is 500 kW).
So that's why HOMER is buying power from the grid a few hours of the year.