# -*- coding: utf-8 -*-
"""
Created on May 27, 2026

@author: cting
This file shows you how to read the data file of YahooJap stock prices
correctly, and to plot the prices in a "professional" way.
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import math

###############################################################################

datadir = 'C:\\YahooJap\\stocks\\'

ticker = '1329'

filename = datadir + ticker  + '.csv'
df = pd.read_csv(filename)
# df.dropna(inplace=True, ignore_index=True)   # This line is very important

n = len(df)
spfac = [1.0] * n
for i in range(n):
    if df.Split[i] != 0.0:
        print(df.Date[i], df.Split[i] )
        for j in range(i-1, -1, -1):
            spfac[j] *= df.Split[i]

price = df.Close/spfac

font = {'family' : 'sans-serif',
        'weight' : 'normal',
        'size'   : 12}

plt.rc('font', **font)

xdata = np.array(pd.to_datetime(df.Date, format='%Y%m%d'))
ydata = price
xlims = mdates.date2num([xdata[0], xdata[-1]])

# Construct the mesh for setting gradient
xv, zv = np.meshgrid(np.linspace(0,5000,100), np.linspace(0,5000,100))

ymax = math.ceil(ydata.max()*(1+0.05)) # Add an offset of 5%

# Draw the image over the whole plot area
fig, ax = plt.subplots(figsize=(12,8))
ax.imshow(zv, cmap='Oranges', origin='lower',
          extent=[xlims[0], xlims[1], 0, ymax], aspect='auto', alpha=0.7)

# Set the range of y axis
ax.set_ylim(0, ymax)

# Erase above the data by filling with white
ax.fill_between(xdata, ydata, ymax, color='white')

# Line plot 
ax.plot(xdata, ydata, 'r-', linewidth=1)

plt.ylabel('Yen')
plt.xlabel('')
plt.grid()
plt.legend([ticker], loc="upper left")
plt.show()
