% MATLAB Script to Fetch Last Month of Daily Stock Prices for TSM from Finnhub

% --- USER INPUT ---
api_key = 'd1ku1khr01qt8foqcp80d1ku1khr01qt8foqcp8g';  % Replace with your actual Finnhub API key
symbol = 'TSM';                 % Stock symbol for Taiwan Semiconductor

% --- DATE RANGE ---
end_date = datetime('today');             % Today
start_date = end_date - calmonths(1);     % One month ago

% Convert to UNIX timestamps (seconds since Jan 1, 1970)
from_unix = posixtime(datetime(start_date));
to_unix   = posixtime(datetime(end_date));

% --- Finnhub Endpoint ---
base_url = 'https://finnhub.io/api/v1/stock/candle';

% --- Query Parameters ---
params = {
    'symbol', symbol, ...
    'resolution', 'D', ...    % Daily bars
    'from', num2str(floor(from_unix)), ...
    'to', num2str(floor(to_unix)), ...
    'token', api_key
};

% --- Make Web Request ---
url = base_url + "?" + join(string(join(params, "=")), "&");

try
    data = webread(url);
catch ME
    error('Failed to fetch data: %s', ME.message);
end

% --- Check Status ---
if isfield(data, 's') && strcmp(data.s, 'ok')
    % Convert timestamps to datetime
    dates = datetime(data.t, 'ConvertFrom', 'posixtime');
    
    % Extract closing prices
    close_prices = data.c;
    
    % --- Plotting ---
    figure;
    plot(dates, close_prices, '-o');
    title(['TSM Daily Closing Prices - Last 1 Month']);
    xlabel('Date');
    ylabel('Price (USD)');
    grid on;
else
    error('API returned error status or no data.');
end