Creating a fucntion that takes as input multible csv files and converts them into arrays
1 次查看(过去 30 天)
显示 更早的评论
So i am creating a program for financial analysis, and i want to extend my analysis for more stocks. The following code describes how i input historical data for each company ((:,5) contains close price.). But my analysis has to be done for nearly 70 stocks so doing this 70 times is very time cosnuming. Thus i want to create a fucntion that takes all the csv files as inputs and gives back the final arrays with the closing prices. My initial idea was the following but it does not seem to work and i don't know how to make a fuction with variable inputs and outputs!
Thanks in advance!
%Apple
AAPL1=readtable('AAPL.csv');
Close=AAPL1(:,5);
AAPL=table2array(Close);
%Adobe
ADBE1=readtable('ADBE.csv');
Close=ADBE1(:,5);
ADBE=table2array(Close);
%Applied Materials
AMAT1=readtable('AMAT.csv');
Close=AMAT1(:,5);
AMAT=table2array(Close);
%Advanced Micro Devices
AMD1=readtable('AMD.csv');
Close=AMD1(:,5);
AMD=table2array(Close);
%Fucntion
function [Array] = ConvertTablesToArrays(Table)
Table1=readtable(Table)
Close=Table1(:,5);
Array=table2array(Close)
end
1 个评论
Stephen23
2020-7-7
One of the main problems with your approach is that you have forced meta-data into variable names. While this is easy to do by hand, it makes any kind of loop over those variables slow, complex, liable to bugs, and difficult to debug:
Instead of forcing meta-data into variable names, you should note that meta-data is data, and data should be stored in variables (not in variable names). For example your code would be simpler and much more efficient using indexing and simple cell arrays or numeric arrays. Then writing your loop will also be much simpler.
回答(1 个)
bharath pro
2020-7-7
D = 'path_to_folder';
S = dir(fullfile(D,'*.xlsx'));
for k = 1:numel(S)
F = fullfile(D,S(k).name);
[S(k).num,S(k).txt,S(k).raw] = csvread(F);
This line stores all csv files data in a directory to the variable S. You can then access the data of each sheet by looping and getting S(i).num form which you can get the desired values.
7 个评论
Stephen23
2020-7-8
编辑:Stephen23
2020-7-8
This answer and the comments above mix up different functions.
The function xlsread has three outputs, corresponding to numeric, text, and raw data.
The functions csvread and readmatrix only have one output.
Swapping csvread for readmatrix will not fix an incorrect number of output arguments.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Financial Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!