With high energy demand and large available area, agricultural farms offer significant potential for renewable energy investments, like photovoltaic systems and electrical energy storages. However, the profitability of such investments depends strongly on self-consumption, so accurate planning requires computation-intensive simulation and optimization considering local consumption. This study presents a novel methodology for the optimal dimensioning and configuration of photovoltaic systems and electrical energy storages using efficient techniques from continuous non-linear optimization. Combining physical and economic models with measured consumption data, an investment’s net present value over 20 years is maximized. Using gradient-based solver WORHP, the simulation, optimal control, and optimal dimensioning of the local energy system are calculated simultaneously, allowing for efficient computation over an entire year of hourly data to capture both daily and seasonal variations.The approach is demonstrated with simple use cases, including an exemplary day of a dairy farm’s consumption, for which optimal systems with and without storage achieve 77% and 43% of autarky, respectively. Saturation effects of optimal plant size can be observed when sizes are large enough for optimal self-consumption but not expanded further for grid export. With energy storage, this saturation is reached at higher values. Optimizing photovoltaic plants with different orientations to match the specific consumption patterns characteristic of the dairy farm achieves similar autarky as a single plant while reducing investment costs by more than 20%. While thorough validation and comparison against heuristic methods predominantly used in the field is part of ongoing research, the presented use cases demonstrate the flexibility and efficiency of the proposed method and highlight its promise as a planning tool in the agricultural domain and beyond.