pexels-photo-187041-187041.jpg

Machine learning is all about two things 

  • to classify things – Classification
  • to make quantitative predictions – Regression

 

Let’s say there is a huge dataset on the weather forecast

CLASSIFICATION is used to classify whether it will rain tomorrow or not.

REGRESSION is used when a quantitative prediction has to be made like the precipitation percentage.

I have taken a dataset of a particular stock.  

This is the first 5 samples of the data. (Sample: it is the data in a single row i.e. a single instance of the data)

Then I analyse the data by plotting different histograms to find the uniqueness of each attribute of the data. (Attribute is the property i.e. the column)

Next, the dataset needs to be divided into training, validation and testing subsets.

I am placing the split in the dataset in such a way that the first 60% of the data is in the train set, the following 20% is in the valid set and the remaining 20% is in the test set.

Training dataset:

As the name implies it is used to train the model. So, the difference in the output predicted and the actual output called the loss is fed into the model to make corrections.

Validation dataset:

Again, as the name implies this dataset is used to validate the model after it has been trained. It checks whether the output predicted corresponds to the real output.

Testing dataset:

This is used to test the model as a final step to check the correctness of the model. 

The dataset I have taken is unbalanced, the difference in the number of “yes” and “no” in the “worked?” attribute is high.

This can be resolved by either oversampling the one less in numbers or undersampling the one more in number.

Since generally more data is good, I am oversampling by creating a function. As the data in my dataset has some attributes in 1000s and some in 10s I am also normalising the dataset using “StandardScalar()” which brings the values of each column between 0 and 1. 

I am also splitting each subset into “x” and “y” where “x” is the input and “y” is the output. 

I have split the respective subsets and also created the F1 Score, Precision, and Accuracy array to compare their values later.

F1 Score:

It is a measure to understand the values of precision and recall with just one value. The traditional F-measure or balanced F-score (F1 score) is the harmonic mean of precision and recall.

First Classification for “worked?” (Class: “Yes” or “No”):

K-Nearest Neighbors:

The K-NN model follows the following algorithm:

  • Select the number ‘K’ of the neighbors(number of neighbors).
  • Calculate the Euclidean distance between the data point and the ‘K’ number of neighbors.
  • Take the ‘K’ nearest neighbors as per the calculated Euclidean distance.
  • Among these ‘K’ neighbors, count the number of the data points in each class.
  • Assign the new data points to that class for which the number of neighbors is maximum. 

Naive Bayes:

Bayes’ Theorem finds the probability of an event occurring given the probability of another event that has already occurred. The mathematical representation of Bayes’ theorem is as follows:

P(A|B) = P(B|A) * P(A) / P(B)

Support Vector Machine:

The goal of the SVM algorithm is to create the best line or decision boundary that can segregate n-dimensional space into classes so that I can easily put the new data point in the correct category in the future. This best decision boundary is called a hyperplane. 

I have used three classification models and now I can compare their accuracy, precision and F1 scores.

Here, the KNN model has high accuracy, precision and f1 score. Therefore is better suited for this particular dataset.

Subsequently, Regression for “percentage_return” (quantitative prediction):

I have defined a similar scalar and normalisation function for “percentage return”. 

Now I can use the regression models.

For regression models, I validate the model by mean squared error and R-squared(like precision, F1 score)

Mean Squared Error(MSE): 

The Mean Squared Error measures how close a regression line is to a set of data points. It is a risk function corresponding to the expected value of the squared error loss.

MSE = (1/n) * Σ(actual – forecast)^2

R-Squared:

It evaluates the scatter of the data points around the fitted regression line. For the same data set, higher R-squared values represent smaller differences between the observed data and the fitted values.

Linear Regression:

Linear regression analysis is used to predict the value of a variable based on the value of another variable. The variable that has to be predicted is called the dependent variable. The variable used to predict the other variable is called the independent variable. 

Random Forest :

Random Forest contains a number of decision trees (hence the name forest) on various subsets of the given dataset and takes the average to improve the predictive accuracy of that dataset. 

Now I compare the MSE and R-squared values of the Models.

The random forest model has a low MSE and a high R- squared value. Therefore it is best suited for this dataset.

The performance of the model can be improved to get a better result.

Find the Python Notebook here.

216 thoughts on “Predicting The Stock Value”

  1. Howdy! shrinivas.tech

    Did you know that it is possible to send message comСЂetently lawful? We submit a legitimate method of sending messages through feedback forms.
    Messages sent via Feedback Forms are unlikely to get into spam, as they are viewed as important.
    You can now test out our service without having to pay.
    On your behalf, we can deliver up to 50,000 messages.

    The cost of sending one million messages is $59.

    This offer is automatically generated.

    We only use chat for communication.

    Contact us.
    Telegram – https://t.me/FeedbackFormEU
    Skype live:contactform_18
    WhatsApp – +375259112693
    WhatsApp https://wa.me/+375259112693

  2. Hello

    I have just took an in depth look on your shrinivas.tech for the current search visibility and saw that your website could use an upgrade.

    We will enhance your ranks organically and safely, using only state of the art AI and whitehat methods, while providing monthly reports and outstanding support.

    More info:
    https://www.digital-x-press.com/unbeatable-seo/

    Regards
    Mike Jerome

    Digital X SEO Experts

  3. Good Day

    This is Mike Holiday

    Let me introduce to you our latest research results from our constant SEO feedbacks that we have from our plans:

    https://www.strictlydigital.net/product/semrush-backlinks/

    The new Semrush Backlinks, which will make your shrinivas.tech SEO trend have an immediate push.
    The method is actually very simple, we are building links from domains that have a high number of keywords ranking for them. 

    Forget about the SEO metrics or any other factors that so many tools try to teach you that is good. The most valuable link is the one that comes from a website that has a healthy trend and lots of ranking keywords.
    We thought about that, so we have built this plan for you

    Check in detail here:
    https://www.strictlydigital.net/product/semrush-backlinks/

    Cheap and effective

    Try it anytime soon

    Regards
    Mike Holiday

    mike@strictlydigital.net

  4. Hi there,

    My name is Mike from Monkey Digital,

    Allow me to present to you a lifetime revenue opportunity of 35%
    That’s right, you can earn 35% of every order made by your affiliate for life.

    Simply register with us, generate your affiliate links, and incorporate them on your website, and you are done. It takes only 5 minutes to set up everything, and the payouts are sent each month.

    Click here to enroll with us today:
    https://www.monkeydigital.org/affiliate-dashboard/

    Think about it,
    Every website owner requires the use of search engine optimization (SEO) for their website. This endeavor holds significant potential for both parties involved.

    Thanks and regards
    Mike Baldwin

    Monkey Digital

  5. This service is perfect for boosting your local business’ visibility on the map in a specific location.

    We provide Google Maps listing management, optimization, and promotion services that cover everything needed to rank in the Google 3-Pack.

    More info:
    https://www.speed-seo.net/ranking-in-the-maps-means-sales/

    Thanks and Regards
    Mike Fisher

    PS: Want a ONE-TIME comprehensive local plan that covers everything?
    https://www.speed-seo.net/product/local-seo-bundle/

  6. Hi there,

    I have reviewed your domain in MOZ and have observed that you may benefit from an increase in authority.

    Our solution guarantees you a high-quality domain authority score within a period of three months. This will increase your organic visibility and strengthen your website authority, thus making it stronger against Google updates.

    Check out our deals for more details.
    https://www.monkeydigital.co/domain-authority-plan/

    NEW: Ahrefs Domain Rating
    https://www.monkeydigital.co/ahrefs-seo/

    Thanks and regards
    Mike Enderson

  7. Howdy

    This is Mike Thompson

    Let me introduce to you our latest research results from our constant SEO feedbacks that we have from our plans:

    https://www.strictlydigital.net/product/semrush-backlinks/

    The new Semrush Backlinks, which will make your shrinivas.tech SEO trend have an immediate push.
    The method is actually very simple, we are building links from domains that have a high number of keywords ranking for them. 

    Forget about the SEO metrics or any other factors that so many tools try to teach you that is good. The most valuable link is the one that comes from a website that has a healthy trend and lots of ranking keywords.
    We thought about that, so we have built this plan for you

    Check in detail here:
    https://www.strictlydigital.net/product/semrush-backlinks/

    Cheap and effective

    Try it anytime soon

    Regards
    Mike Thompson

    mike@strictlydigital.net

  8. Для записи на подачу документов на визу в Италию можно использовать онлайн-сервисы визового центра или консульства. Запись предварительная и требует подтверждения доступных дат и времени.
    Виза Италия цена https://www.visa-v-italiyu.ru/ .

  9. Hi there,

    I have reviewed your domain in MOZ and have observed that you may benefit from an increase in authority.

    Our solution guarantees you a high-quality domain authority score within a period of three months. This will increase your organic visibility and strengthen your website authority, thus making it stronger against Google updates.

    Check out our deals for more details.
    https://www.monkeydigital.co/domain-authority-plan/

    NEW: Ahrefs Domain Rating
    https://www.monkeydigital.co/ahrefs-seo/

    Thanks and regards
    Mike Oldridge

  10. Профессиональный ремонт автомобилей Ниссан, где качество обслуживания на высоте.
    Надежный автосервис Ниссан для Вашего авто, где техника в надежных руках.
    Автосервис Ниссан с безупречной репутацией, которые знают все особенности этой марки.
    Обслуживание автомобилей Ниссан на высшем уровне, с гарантией качества и доступными ценами.
    Где Ваш автомобиль Ниссан будет в надежных руках, с учетом всех особенностей марки.
    Автосервис Nissan Москва http://nissan-remont-1.ru/ .

  11. This service is perfect for boosting your local business’ visibility on the map in a specific location.

    We provide Google Maps listing management, optimization, and promotion services that cover everything needed to rank in the Google 3-Pack.

    More info:
    https://www.speed-seo.net/ranking-in-the-maps-means-sales/

    Thanks and Regards
    Mike Ferguson

    PS: Want a ONE-TIME comprehensive local plan that covers everything?
    https://www.speed-seo.net/product/local-seo-bundle/

  12. Hi there,

    My name is Mike from Monkey Digital,

    Allow me to present to you a lifetime revenue opportunity of 35%
    That’s right, you can earn 35% of every order made by your affiliate for life.

    Simply register with us, generate your affiliate links, and incorporate them on your website, and you are done. It takes only 5 minutes to set up everything, and the payouts are sent each month.

    Click here to enroll with us today:
    https://www.monkeydigital.org/affiliate-dashboard/

    Think about it,
    Every website owner requires the use of search engine optimization (SEO) for their website. This endeavor holds significant potential for both parties involved.

    Thanks and regards
    Mike Lamberts

    Monkey Digital

  13. Задачи и функции технического надзора в строительстве, важность данного процесса.
    Критерии выбора специалистов по техническому надзору, с целью минимизации рисков.
    Основные этапы проведения технического надзора, чтобы быть в курсе.
    Какие проблемы могут возникнуть без проведения технического надзора, и как их предотвратить.
    Как повысить эффективность технического надзора на строительном объекте, которые пригодятся вам.
    Методы технического надзора в строительстве, чтобы добиться успеха.
    Строительный контроль застройщика http://stroitelny-nadzor.ru/ .

  14. Лучший автосервис Toyota в Москве, где заботятся о вашем авто.
    Профессиональный ремонт Toyota в столице, опытные мастера и современное оборудование.
    Toyota в Москве: лучший сервис по доступным ценам, подтвержденное отзывами довольных владельцев.
    Toyota в Москве: надежный сервис с гарантией качества, для тех, кто ценит свое время.
    Топовый сервис для японских автомобилей в столице, где ценят ваше время и деньги.
    Идеальное решение для обслуживания японских автомобилей, подтвержденный репутацией и довольными клиентами.
    Идеальный выбор для японских автомобилей в столице, где каждый клиент важен и ценится.
    Ремонт Тойота Москва toyota-remont.ru .

  15. Good morning! shrinivas.tech

    Did you know that it is possible to send a business offer legally? We are offering a new method of sending business proposals through contact forms.
    Contact Form messages aren’t likely to be sent to spam, since they are regarded as important.
    You’re invited to sample our service at no cost.
    We can send up to 50,000 messages on your behalf.

    The cost of sending one million messages is $59.

    This letter is automatically generated.
    Please use the contact details below to get in touch with us.

    Contact us.
    Telegram – https://t.me/FeedbackFormEU
    Skype live:feedbackform2019
    WhatsApp +375259112693
    WhatsApp https://wa.me/+375259112693

    We only use chat for communication.

  16. Howdy

    I have just took a look on your SEO for shrinivas.tech for its SEO metrics and saw that your website could use a boost.

    We will increase your ranks organically and safely, using only state of the art AI and whitehat methods, while providing monthly reports and outstanding support.

    More info:
    https://www.digital-x-press.com/unbeatable-seo/

    Regards
    Mike Nash

    Digital X SEO Experts

  17. сайт кракен тор

    Не могу понять, как зайти на blacksprut ссылка. Кто-нибудь может помочь? Я слышал, что там много интересных материалов.

    Source:

    https://kraken014.com/

  18. Можно ли применять ботокс для лечения заболеваний? Да, ботокс используется для лечения мигрени, гипергидроза, блефароспазма и других медицинских состояний
    птоз верхнего века после ботокса https://www.botox.b-tox.ru/ .

  19. Какие существуют аналоги биоревитализации? Аналоги включают мезотерапию, плазмолифтинг и процедуры с использованием других увлажняющих и восстанавливающих препаратов
    revi биоревитализация цена biorevitalizacia.com .

  20. Салон автомобиля в Москве: кто лучше всего перетянет?
    Почему стоит обратиться за перетяжкой салона автомобиля именно в Москве?
    Перетяжка салона Москва poshiv-avtosalona.ru .

  21. блэкспрут ссылка

    Эскорт модели Проститутки Москвы, несомненно, являются украшением ночного города. Снять несложно в любом районе столицы, а предлагаемые клиентам интим услуги отличаются доступностью и разнообразием. Элитные проститутки по вызову в Мск позиционируют эротические услуги и секс за деньги, размещая интим объявления на нашем Воспользовавшись этим сайтом, любой москвич или гость столицы сможет найти эскортницу по своему вкусу и кошельку.

    Source:

    блэкспрут ссылка

  22. Индивидуальные медицинские расходные материалы для уникальных потребностей вашей клиники, и позволят вам работать без перебоев.
    Расходные материалы медицинского назначения https://medtovarka.ru/ .

  23. Какие программы могут облегчить процесс проверки сметы на соответствие?.
    Проверка смет на соответствие стандартам помогает избежать ошибок и перерасходов. proverka-smet-msk.ru .

  24. Эргономичные уличные урны для мусора с удобной ручкой, повышают эффективность уборки города.
    Урны для мусора играют важную роль в обеспечении гигиены и предотвращении загрязнения окружающей среды: https://www.urna-dlia-musora.ru .

  25. Профессиональные советы по чистке кожаной мебели на дому, для экономии времени и сил.
    Химчистка кожаной мебели на дому обеспечивает глубокое и эффективное удаление загрязнений и пятен с ваших любимых предметов интерьера: https://ximchistka-kozhanoj-mebeli.ru .

  26. 1win казино — популярная платформа для онлайн азартных игр. Оно предлагает широкий выбор слотов, настольных игр и ставок на спорт в удобном интерфейсе. Бонусы для новых игроков и регулярные акции делают игру выгодной и увлекательной. 1win букмекерская контора официальный предоставляет широкие возможности для ставок на спорт и азартных игр. Стабильная работа сайта и быстрые выплаты делают 1win привлекательным выбором для любителей азарта.

  27. “Можно ли удалять папилломы лазером дома?” – “Удаление папиллом лазером должно проводиться квалифицированным специалистом в медицинских условиях для обеспечения безопасности и эффективности.”
    “Can papillomas be removed with a laser at home?” – “Laser removal of papillomas should be performed by a qualified specialist in a medical setting to ensure safety and effectiveness.”
    лазерное удаление папиллом цена http://www.udalenie.com.ru .

  28. Сколько времени требуется для того, чтобы лечение акне подействовало? – Большинство методов лечения акне требуют нескольких недель для появления улучшений, а максимальные результаты обычно видны через три месяца.
    How long does it take for acne treatments to work? – Most acne treatments take several weeks to show improvement, with maximum results typically seen after three months.
    акне и постакне https://www.almedinfo.ru .

  29. Как проходит процедура лазерного удаления папиллом? – Процедура проводится амбулаторно, начинается с дезинфекции и обезболивания участка, затем лазер направляется на папиллому, чтобы удалить её.
    What is the procedure for laser removal of papillomas? – The procedure is done on an outpatient basis, starting with disinfection and anesthesia of the area, then the laser is directed at the papilloma to remove it.
    удаление папиллом недорого https://laser-removal-of-papillomas.ru .

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top