Qu'est-ce que BaZi ?
BaZi (八字), litteralement "huit caracteres", est un systeme astrologique chinois qui relie une destinee a la date et a l'heure de naissance. Il produit quatre piliers (Year, Month, Day, Hour). Chaque pilier contient deux caracteres : un Heavenly Stem (天干 / Tiān Gān) et une Earthly Branch (地支 / Dì Zhī).
Ces huit caracteres decrivent l'energie du moment de naissance et servent a analyser personnalite, carriere, relations et cycles de vie.
Les briques de base
Les 10 Heavenly Stems (天干)
| Stem | Pinyin | Element | Polarity |
|---|---|---|---|
| 甲 | Jiǎ | Wood | Yang |
| 乙 | Yǐ | Wood | Yin |
| 丙 | Bǐng | Fire | Yang |
| 丁 | Dīng | Fire | Yin |
| 戊 | Wù | Earth | Yang |
| 己 | Jǐ | Earth | Yin |
| 庚 | Gēng | Metal | Yang |
| 辛 | Xīn | Metal | Yin |
| 壬 | Rén | Water | Yang |
| 癸 | Guǐ | Water | Yin |
Les 12 Earthly Branches (地支)
| Branch | Pinyin | Zodiac | Element |
|---|---|---|---|
| 子 | Zǐ | Rat | Water |
| 丑 | Chǒu | Ox | Earth |
| 寅 | Yín | Tiger | Wood |
| 卯 | Mǎo | Rabbit | Wood |
| 辰 | Chén | Dragon | Earth |
| 巳 | Sì | Snake | Fire |
| 午 | Wǔ | Horse | Fire |
| 未 | Wèi | Goat | Earth |
| 申 | Shēn | Monkey | Metal |
| 酉 | Yǒu | Rooster | Metal |
| 戌 | Xū | Dog | Earth |
| 亥 | Hài | Pig | Water |
Le cycle sexagesimal (六十甲子)
Les 10 Stems et les 12 Branches se combinent pour former un cycle de 60 unites. Ce cycle sert a representer les annees, mois, jours et heures dans les calendriers chinois.
Le cycle commence par 甲子 (Jiǎ Zǐ) et se termine par 癸亥 (Guǐ Hài). Trouver le couple Stem-Branch d'un moment precis demande une bonne precision astronomique, surtout pour les termes solaires qui definissent les limites de mois.
Calculer les Quatre Piliers en Python
La solution Python la plus pratique est la librairie lunar-python. Elle gere les conversions entre calendrier gregorien, calendrier lunaire chinois et cycle sexagesimal.
Installation
pip install lunar-pythonCalcul de base
from lunar_python import Solar
# Birth data: May 15, 1990 at 10:30 AM
year, month, day = 1990, 5, 15
hour, minute = 10, 30
# Create a Solar (Gregorian) date object
solar = Solar.fromYmdHms(year, month, day, hour, minute, 0)
# Convert to Lunar and then to BaZi (EightChar)
lunar = solar.getLunar()
eight_char = lunar.getEightChar()
# Extract the Four Pillars
print("Year Pillar:", eight_char.getYear()) # e.g., 庚午
print("Month Pillar:", eight_char.getMonth()) # e.g., 辛巳
print("Day Pillar:", eight_char.getDay()) # e.g., 丙寅
print("Hour Pillar:", eight_char.getTime()) # e.g., 癸巳Sortie :
Year Pillar: 庚午
Month Pillar: 辛巳
Day Pillar: 丙寅
Hour Pillar: 癸巳Extraire stems et branches
Pour une analyse plus fine, vous pouvez extraire separement le Stem (Gan) et la Branch (Zhi) de chaque pilier :
# Stems (天干)
print("Year Stem:", eight_char.getYearGan()) # 庚
print("Month Stem:", eight_char.getMonthGan()) # 辛
print("Day Stem:", eight_char.getDayGan()) # 丙
print("Hour Stem:", eight_char.getTimeGan()) # 癸
# Branches (地支)
print("Year Branch:", eight_char.getYearZhi()) # 午
print("Month Branch:", eight_char.getMonthZhi()) # 巳
print("Day Branch:", eight_char.getDayZhi()) # 寅
print("Hour Branch:", eight_char.getTimeZhi()) # 巳Hidden Stems (藏干)
Chaque Earthly Branch contient des Heavenly Stems caches qui representent des energies latentes. lunar-python y donne acces :
# Hidden stems for each pillar
print("Year Hidden:", eight_char.getYearHideGan()) # ['丁', '己']
print("Month Hidden:", eight_char.getMonthHideGan()) # ['丙', '庚', '戊']
print("Day Hidden:", eight_char.getDayHideGan()) # ['甲', '丙', '戊']
print("Hour Hidden:", eight_char.getTimeHideGan()) # ['丙', '庚', '戊']Ten Gods (十神)
Le systeme des Ten Gods decrit la relation entre chaque element du theme et le Day Master. Il est central dans l'interpretation BaZi.
# The Day Master is the Day Stem
day_master = eight_char.getDayGan()
print(f"Day Master: {day_master}") # 丙 (Bing Fire)
# Ten Gods for each pillar's stem
print("Year Ten God:", eight_char.getYearShiShenGan()) # Direct Wealth
print("Month Ten God:", eight_char.getMonthShiShenGan()) # Indirect Wealth
print("Hour Ten God:", eight_char.getTimeShiShenGan()) # Direct ResourceCalculer le Luck Cycle (大运)
Les Luck Pillars de 10 ans (Da Yun) sont calcules a partir du theme et du genre :
# 1 = Male, 0 = Female
sex = 1
yun = eight_char.getYun(sex)
print(f"Luck cycle starts at age: {yun.getStartYear()}")
print(f"Direction: {'Forward' if yun.isForward() else 'Backward'}")
for da_yun in yun.getDaYun():
if da_yun.getIndex() == 0:
continue # Skip the base period
print(f"Age {da_yun.getStartAge()}-{da_yun.getEndAge()}: {da_yun.getGanZhi()}")Fuseaux horaires et vrai temps solaire
Un point delicat du calcul BaZi est le choix de l'heure locale. Beaucoup de praticiens utilisent le vrai temps solaire, fonde sur la position reelle du soleil, plutot que l'heure civile.
L'algorithme comprend :
- Longitude Correction : ajustement selon la position dans le fuseau.
- Equation of Time : correction liee a l'orbite terrestre.
from datetime import datetime, timedelta
def get_true_solar_time(dt, longitude, timezone_meridian):
"""
Calculate True Solar Time from civil time.
Args:
dt: datetime object in local civil time
longitude: Birth location longitude (degrees, East positive)
timezone_meridian: Standard meridian for the timezone (e.g., 120 for UTC+8)
Returns:
Adjusted datetime representing True Solar Time
"""
# Longitude correction: 4 minutes per degree from standard meridian
long_correction_minutes = (longitude - timezone_meridian) * 4
# Equation of Time approximation (simplified)
# E = 9.87 * sin(2B) - 7.53 * cos(B) - 1.5 * sin(B)
import math
day_of_year = dt.timetuple().tm_yday
b = (2 * math.pi / 365) * (day_of_year - 81)
eot_minutes = 9.87 * math.sin(2*b) - 7.53 * math.cos(b) - 1.5 * math.sin(b)
total_correction = timedelta(minutes=long_correction_minutes + eot_minutes)
return dt + total_correctionExemple complet
Voici un exemple qui construit un chart BaZi structure :
from lunar_python import Solar
def calculate_bazi_chart(year, month, day, hour, minute, sex=1):
"""
Calculate a complete Bazi chart.
Returns a dictionary with all four pillars and their components.
"""
solar = Solar.fromYmdHms(year, month, day, hour, minute, 0)
lunar = solar.getLunar()
eight_char = lunar.getEightChar()
pillars = []
labels = ["year", "month", "day", "hour"]
stems = [
eight_char.getYearGan(),
eight_char.getMonthGan(),
eight_char.getDayGan(),
eight_char.getTimeGan()
]
branches = [
eight_char.getYearZhi(),
eight_char.getMonthZhi(),
eight_char.getDayZhi(),
eight_char.getTimeZhi()
]
for i, label in enumerate(labels):
pillars.append({
"label": label,
"stem": stems[i],
"branch": branches[i],
"pillar": f"{stems[i]}{branches[i]}"
})
return {
"day_master": eight_char.getDayGan(),
"pillars": pillars,
"lunar_date": f"{lunar.getYearInChinese()}年 {lunar.getMonthInChinese()}月 {lunar.getDayInChinese()}"
}
# Example usage
chart = calculate_bazi_chart(1990, 5, 15, 10, 30, sex=1)
print(f"Day Master: {chart['day_master']}")
print(f"Lunar Date: {chart['lunar_date']}")
for p in chart['pillars']:
print(f"{p['label'].capitalize()} Pillar: {p['pillar']}")DIY ou API ?
Calculer BaZi en Python est un bon exercice, mais une application de production ajoute plusieurs contraintes :
- Maintenance : bases de fuseaux horaires et ajustements changent regulierement.
- Precision : le vrai temps solaire demande des coordonnees exactes et des donnees d'ephemerides solides, comme NASA JPL DE405.
- Cas limites : heure du Rat, Early vs Late limit, Blind Years et autres details demandent une vraie expertise.
Si vous avez besoin d'une precision fiable et de fonctions professionnelles, une API specialisee evite une grande partie de cette maintenance.
Librairies open source
Notre API s'appuie sur ces librairies :
| Library | Purpose | License |
|---|---|---|
| lunar-python | Chinese calendar and Bazi calculations | MIT |
| pytz | Timezone handling | MIT |
| timezonefinder | Timezone lookup from coordinates | MIT |
Essayer notre API BaZi gratuite
L'endpoint /api/v1/chinese/bazi fournit :
- Complete Four Pillars avec romanisation Pinyin
- Ten Gods relationships pour chaque stem
- Hidden Stems avec analyse elementaire
- Symbolic Stars (Shen Sha) comme Nobleman et Peach Blossom
- Branch interactions : Combinations, Clashes, Harmonies, Punishments
- 10-year Luck Cycle
- Professional features : Day Master strength, Chart Structure, Yong Shen analysis
Exemple rapide
import requests
url = "https://api.freeastroapi.com/api/v1/chinese/bazi"
payload = {
"year": 1990,
"month": 5,
"day": 15,
"hour": 10,
"minute": 30,
"lat": 28.6139,
"lng": 77.2090,
"sex": "M",
"include_pinyin": True,
"include_stars": True,
"include_interactions": True,
"include_professional": True
}
headers = {
"Content-Type": "application/json",
"x-api-key": "YOUR_API_KEY"
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())Lire la documentation complete →
Commencer
Pour apprendre, utilisez lunar-python. Pour un produit, utilisez Bazi API et concentrez votre temps sur l'interface, l'interpretation et l'experience utilisateur.