<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Python and Scikit-learn: Predict the closing value in stocks - Medium]]></title>
        <description><![CDATA[In this article we will work in predict the price of closing value in stocks. But we can predict any value, like maximum, minium, or whatever, this is up to you, the importance is in the different applied techniques to achieve it. - Medium]]></description>
        <link>https://medium.com/python-and-scikit-learn-predict-the-closing-value?source=rss----6f813e578941---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Python and Scikit-learn: Predict the closing value in stocks - Medium</title>
            <link>https://medium.com/python-and-scikit-learn-predict-the-closing-value?source=rss----6f813e578941---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:12:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/python-and-scikit-learn-predict-the-closing-value" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Python and Scikit-learn: Predict the closing value in stocks.]]></title>
            <link>https://medium.com/python-and-scikit-learn-predict-the-closing-value/python-and-scikit-learn-predict-the-closing-value-in-stocks-f2b17bafb341?source=rss----6f813e578941---4</link>
            <guid isPermaLink="false">https://medium.com/p/f2b17bafb341</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[begginer]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Fran Vañó]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 12:01:05 GMT</pubDate>
            <atom:updated>2021-01-26T12:01:05.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*nLa-Cstqw2bW2ZWs693gBg.png" /></figure><p>As we know, the machine learning is one of the most used tools in current days, we can use this subarea of AI to predict values, predict illness, classify species… In our case we will use this tool for predict the closing value of stock, this is the value that will have the share at the end of the day.</p><p>To do it we will follow the next list step by step:</p><ul><li>Importing packages.</li><li>Clean the raw data.</li><li>Select the dependent and independent columns.</li><li>Train the model.</li><li>Make predictions and classify the results.</li></ul><p>Let’s get started.</p><h4><strong>1. Importing packages.</strong></h4><p>First of all, we need some packages that help us to make easier the training, the predictions, plot the results…</p><pre>import numpy as np <br>import pandas as pd<br>import warnings<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression</pre><p>Once we have the required packages imported in our script, we can start with the next step.</p><h4><strong>2. Clean the raw data.</strong></h4><p>Maybe in our dataset we have categorical data, this means that we have values in string type, but we want float values, therefore before to begin we will convert the string values in float values.</p><p>Python help us to convert easily one string value in float value, but the value format should be x.xx or similar, what if we have x,xx?</p><p>In this case we have to replace the comma by dot and finally parse the value to float type. We can make something like this:</p><pre>data = pd.read_csv(&#39;C:\data.csv&#39;)<br>def str_to_float(data, column):<br>    for i in range(data[column].shape[0]):<br>        data[column][i] = data[column][i].replace(&#39;,&#39;, &#39;.&#39;)</pre><pre>    data[column] = data[column].astype(float) </pre><p>In the code above we have defined a function, this function need two arguments, one is the data and the other is the column that we want to convert in float type.</p><p>The function only go through all the values in the column and replace the comma by a dot, once we have the correct format in all the values, we modify the type of column to float type.</p><p>Now only call the function to parse the type of the different columns and we will start to train the model.</p><pre>str_to_float(data,&#39;close&#39;)<br>str_to_float(data,&#39;open&#39;)<br>str_to_float(data,&#39;max&#39;)<br>str_to_float(data,&#39;min&#39;)</pre><h4><strong>3. Select the dependent and independent columns.</strong></h4><p>First we create two variables, the variable x (dependent variable) contains the columns that we will use to predict the value of the variable y (independent variable).</p><pre>x = data[[&#39;open&#39;, &#39;max&#39; ,&#39;min&#39;]].values<br>y = data[&#39;close&#39;].values </pre><p>As we can imagine, we will use the values of columns open, max and min to predict the value of close, but we also could put the close column in the dependent variables and train the model to predict the maximum or whatever column, this is up to you.</p><p>Now, we have to split the data, we will use the 82% of our dataset to train the model, and the other 18% to test this model. To do it we will use the train_test_split() function. We need use the argument random_state to avoid the model get different values every time that we train the model, with this argument we force the model to get always the same values to train our model.</p><pre>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.18 , random_state = 0)</pre><h4>4. Train the model.</h4><p>Finally we are ready to train the model, we will use the linear regression algorithm to do it, but we can use whatever algorithm, in this case this algorithm has get the best results. To train the model we have used the next code:</p><pre>clf = LinearRegression()<br>clf.fit(x_train, y_train)</pre><pre>print(&quot;Accuracy train {:.3f}&quot;.format(clf.score(x_train, y_train)))<br>print(&quot;Accuracy test {:.3f}&quot;.format(clf.score(x_test, y_test)))</pre><p>With clf variable we select the algorithm, and with fit function we train our model with our train variables, but if we want know how well (or bad) is our model performing, we should print the score with three decimals.</p><p>This scores should be very similar, and be close to 1 to say that we have a good trained model.</p><h4>5. Make predictions and classify the results.</h4><p>Now we can use our trained model to make predictions, and compare our predicted close value with the real close value and see the difference between them. We will use the code below to do it.</p><pre>X = [[1.3182, 1.3190, 1.3095]]<br>predicted = clf.predict(X)<br>print(&quot;Predicted value for close value:&quot;, predicted)</pre><p>We put in the variable X the values of open, max and min, in the same order that we was put in the variable x in the dependent variables. And finally we use the function predict to see what is the close value for this values in the variable X and print it.</p><p>Well, this is fine but, how can we know if this predicted value is close to the real close value?</p><p>To test this we can use the next code:</p><pre>predictions = [] #Vector for our predictions<br>realvalues = [] #Vector for real values<br>iter = x_train.shape[0]</pre><pre>for i in range(0, int(iter)):<br>    values = [[x_train[i][0], x_train[i][1], x_train[i][2]]] <br>    pred = clf.predict(values) <br>    predictions.append(pred) <br>    realvalues.append(y_train[i]) #<br>    values = [[]]</pre><p>We create two arrays, one for our predictions and another for the real close values, next we use the iter variable to get the number of rows in the x_train variable, and use it to get the number of iterations we need.</p><p>The next step is put in the values array the values of columns open, max and min, this are the columns 0, 1 and 2 in our dataset, and use this array to make the prediction and insert the predicted value in the predictions array, later we put the real close value in the real values array.</p><p>When the loop finishes we will have in the predictions array all our predicted values, and in our real values array the real close value.</p><p>Now we will use the code below to see the values well predicted and the values bad predicted.</p><pre>bad = []<br>good = []</pre><pre>for i in range(0, len(realvalues)):<br>    sub = realvalues[i] - predictions[i] <br>    abs(sub)<br>    <br>    if(sub &gt; 0.08):<br>        bad.append(sub)<br>    else:<br>        good.append(sub)</pre><pre>print(&quot;The number of well predicted values is: &quot;, len(good))<br>print(&quot;The number of bad predicted values is: &quot;, len(bad))</pre><p>First of all we have created two arrays, one for wrong classified values and other for well classified values, and then we go through all the values and calculate the subtract among the real value and our prediction. If this prediction is greater than 0.08 we put the value in the bad array, if this subtract is less or equals than 0.08 we will assume that the prediction is acceptable.</p><p>In the code above we was print the result calculating the length of each array, but is better if we see the result graphically, for do this we use the code below:</p><pre>labels = &#39;bad&#39;, &#39;good&#39;<br>length = np.array([len(bad), len(good)])<br>plt.pie(length, labels = labels, autopct=&#39;%1.1f%%&#39;)</pre><p>The result of this code is the next:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*H7dZlvazIa4piC5Za7b6cg.png" /></figure><p>As we can see, the 12&#39;4% of values have been classified as bad and the other 87.6% as well.</p><p>Well, we are done. As we can see, we are learned how to train a model that can help us to make our stocks predictions.</p><p>I hope that you are enjoyed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2b17bafb341" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-and-scikit-learn-predict-the-closing-value/python-and-scikit-learn-predict-the-closing-value-in-stocks-f2b17bafb341">Python and Scikit-learn: Predict the closing value in stocks.</a> was originally published in <a href="https://medium.com/python-and-scikit-learn-predict-the-closing-value">Python and Scikit-learn: Predict the closing value in stocks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>