PySwissEphe - Swiss Ephemeris
PySwissEphe is a Python extension providing access to the powerful Swiss Ephemeris library, a high-precision astronomical calculation engine. It allows for calculation of planetary positions, houses, aspects, and other celestial data. Currently at version 2.10.3.2, the library maintains a steady release cadence, often updating to reflect new versions of the underlying Swiss Ephemeris C code.
Warnings
- gotcha The `swe.swe_set_ephe_path()` function must be called with a valid path to the Swiss Ephemeris data files (.se1). Without these files, calculations will fail, often with cryptic error messages or silently incorrect results.
- gotcha The library exposes numerous constants (e.g., `swe.SE_JUL_CAL`, `swe.SE_SUN`, `swe.SEFLG_SWIEPH`) that control calculation parameters and celestial bodies. Misunderstanding or incorrect use of these constants can lead to inaccurate astronomical calculations without explicit Python errors.
- breaking As a wrapper for the Swiss Ephemeris C library, `pyswisseph` versions directly correspond to the upstream library's version. Updates to the C library can introduce breaking changes, bug fixes, or new features that subtly affect calculation precision or behavior, especially in edge cases.
Install
-
pip install pyswisseph
Imports
- swisseph
import swisseph as swe
Quickstart
import swisseph as swe
import os
# IMPORTANT: For accurate calculations, you need to download the Swiss Ephemeris
# data files (e.g., 'se1900-2050.se1', 'seasr.se1') from the official website
# (www.astro.com/swisseph/sweph_e.htm) and place them in a directory.
# For this example, we create an empty 'swefiles' directory in the current
# working directory. Calculations will fail or return errors without the actual files.
ephe_dir = 'swefiles'
if not os.path.exists(ephe_dir):
os.makedirs(ephe_dir)
print(f"Created directory '{ephe_dir}'. Please populate it with Swiss Ephemeris data files.")
# Set the path to the ephemeris data files
swe.swe_set_ephe_path(ephe_dir)
# Define a Julian Day (UT - Universal Time) for calculation
# January 1, 2024, 12:00 UT
jd_ut = swe.swe_julday(2024, 1, 1, 12.0, swe.SE_GREG_CAL)
# Define calculation flags: use default Swiss Ephemeris, calculate speed
flags = swe.SEFLG_SWIEPH | swe.SEFLG_SPEED
# Calculate Mars' position (SE_MARS)
# xx will contain: [longitude, latitude, distance, speed_longitude, speed_latitude, speed_distance]
xx, ret = swe.swe_calc_ut(jd_ut, swe.SE_MARS, flags)
if ret >= 0:
print(f"Mars' position on 2024-01-01 12:00 UT:")
print(f" Longitude: {xx[0]:.4f}°")
print(f" Latitude: {xx[1]:.4f}°")
print(f" Distance: {xx[2]:.4f} AU")
print(f" Speed Longitude: {xx[3]:.4f}°/day")
else:
print(f"Error calculating Mars' position. Make sure '{ephe_dir}' contains required '.se1' files.")
print(f"Swiss Ephemeris error: {swe.swe_get_serr_string(ret)}")