# -*- coding: utf-8 -*-
"""
Created on Wed Jun 11 13:33:00 2025

@author: cting
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import math as math

datadir = 'C:\\YahooJap\\updated1\\'

def read_YahooJapan(ticker):
        
    filename = datadir + ticker  + '.csv'
    df = pd.read_csv(filename)

    if type(df.Open[0]) == str:
        print('There are stock splits in the data.')
        splitdate, splitfactor = list(), list()
      
        n = len(df)
        for i in range(n):
            if np.isnan(df.High[i]):
                l = df.Open[i].split('->')
                a = float(l[0].replace(':', ''))
                b = float(l[1])
                print(df.Date[i], a, 'for', b, 'shares')
                splitdate.append(df.Date[i])
                r = b/a
                splitfactor.append(r)
        
        df.dropna(inplace=True, ignore_index=True)     
        m = len(df)
        op = np.zeros(m) 
        for i in range(m):
            op[i] = float(df.Open[i])
            
        odf = pd.DataFrame(data=op, columns=['Open'])
        df.Open = odf
        
        s = len(splitfactor)
        if s > 0:
            splitdate.append(df.Date.iloc[-1])
    
            cumaf = np.ones(s+1)
            splitfactor = np.flipud(splitfactor)
            for j in range(1,s+1):
                cumaf[j] = cumaf[j-1]*splitfactor[j-1]
            cumaf = np.flipud(cumaf)    
 
            n = len(df) 
            adjfac, k = np.ones(n), 0
            for j in range(s):
                while df.Date[k] < splitdate[j]:
                    adjfac[k] = cumaf[j] 
                    k += 1
        df['ADJFAC'] = adjfac
        df['AOpen'] = df.iloc[:, 1]/adjfac
        df['AHigh'] = df.iloc[:, 2]/adjfac
        df['ALow'] = df.iloc[:, 3]/adjfac
        df['AClose'] = df.iloc[:, 4]/adjfac
        df['AVolume'] = df.iloc[:, 5]/adjfac
    else:
        n = len(df) 
        df['ADJFAC'] = np.ones(n)
        df['AOpen'] = df.iloc[:, 1]
        df['AHigh'] = df.iloc[:, 2]
        df['ALow'] = df.iloc[:, 3]
        df['AClose'] = df.iloc[:, 4]
        df['AVolume'] = df.iloc[:, 5]   
 
    return df


###############################################################################

ticker = '1515.T'


df = read_YahooJapan(ticker)
Close = df.AClose

xdata = np.array(pd.to_datetime(df.Date, format='%Y%m%d'))
ydata = Close
xlims = mdates.date2num([xdata[0], xdata[-1]])

font = {'family' : 'sans-serif',
        'weight' : 'normal',
        'size'   : 12}
plt.rc('font', **font)

# Construct the mesh for setting gradient
xv, zv = np.meshgrid(np.linspace(0,5000,100), np.linspace(0,5000,100))

nmax = len(str(int(ydata.max())))
factor = 10**(nmax-1)
ymax = math.ceil ( math.ceil (ydata.max())/factor)*factor

# 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()       
        