Is there a way for me to edit the date range shown on my line graph?

import yfinance as yf
import numpy as np
import pandas as pd
import seaborn as sns

SP = yf.Ticker("^GSPC").history(period='1y')
Gold = yf.Ticker("GC=F").history(period='1y')
Oil = yf.Ticker("CL=F").history(period='1y')

SP['Percent Change'] = SP['Close'].pct_change()*100
Gold['Percent Change'] = Gold['Close'].pct_change()*100
Oil['Percent Change'] = Oil['Close'].pct_change()*100

sns.lineplot(data=SP, x='Date', y=SP['Percent Change'])
sns.lineplot(data=Gold, x='Date', y=Gold['Percent Change'])
sns.lineplot(data=Oil, x='Date', y=Oil['Percent Change'])

To prevent my graph from displaying data from back in 1970 when I set xlim(0,12), what method can I use to limit the X-axis values to specific date ranges?

Answer №1

One efficient way to plot graphs using datetime index slicing df[start:end] is to only display the necessary data instead of plotting all and then adjusting the xlim:

import yfinance as yf
import numpy as np
import pandas as pd
import seaborn as sns

start_date = '2022-02-01'
end_date = '2022-04-01'

SP_data = yf.Ticker("^GSPC").history(period='1y')
Gold_data = yf.Ticker("GC=F").history(period='1y')
Oil_data = yf.Ticker("CL=F").history(period='1y')

SP_data['Percent Change'] = SP_data['Close'].pct_change() * 100
Gold_data['Percent Change'] = Gold_data['Close'].pct_change() * 100
Oil_data['Percent Change'] = Oil_data['Close'].pct_change() * 100

sns.lineplot(data=SP_data.loc[start_date:end_date], x='Date', y='Percent Change')
sns.lineplot(data=Gold_data.loc[start_date:end_date], x='Date', y='Percent Change')
sns.lineplot(data=Oil_data.loc[start_date:end_date], x='Date', y='Percent Change')

Expected Output:

https://i.stack.imgur.com/eXcQm.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Python - finding characters located between repeated specific characters within a string

Currently, I'm dealing with a large string that contains approximately 270 million lines as shown below: <DOC> <DOC>+BDTag <S> <S>+BSTag --- ---- --- ---- </S> </S>+ESTag <S> <S>+BSTag --- ---- --- ---- ...

What is the method to retrieve a string from a specific element in Selenium using Python?

I'm facing a challenge in extracting a specific string from the following HTML element: <textarea class="FormTextArea__textarea form-control" aria-label="Photo Caption" aria-describedby="photo-caption__help" id="photo-caption" rows="3">Exterior ...

Discover the secret to determining 95% confidence intervals through the innovative Bootstrap approach

Currently, I am working on determining the confidence interval for the mean value through the bootstrap method in Python. To elaborate, let's assume I have a vector called 'a' containing 100 entries, and my objective is to compute the averag ...

I need assistance with adding an icon to a qinputdialog in my pyqt4 application. Can someone provide

Below is the code snippet I am currently working with: languages = ['English', 'rus', 'uk', 'fr', 'germ'] s, ok = QtGui.QInputDialog.getItem(window, 'title', 'help', languages, curre ...

Locate element using value in Selenium with Python

Currently, I am utilizing Selenium in conjunction with Python to autonomously extract data from various power plants. One challenge I am facing is the need to click on an element within each plant's unique interface. The difficulty lies in the fact th ...

The issue with the selenium WebDriverWait arises when the expected condition fails to return the element

While I have experience using selenium, I have not had the opportunity to utilize WebDriverWait until now. I am currently facing a situation where I need to click on a Back button, which appears to be available immediately but may not be accessible for a b ...

Error: Unable to import the specified name 'string_int_label_map_pb2'

After running the compilation command below, the files were successfully compiled into .py files. protoc object_detection/protos/*.proto --python_out=. Despite this success, an error code was encountered: ~/Documents/imgmlreport/inception/classification ...

Determine the total count of distinct combinations within a Pandas data frame

I seem to be facing some difficulties (mental block) when it comes to creating basic summary statistics for my dataset. What I am trying to accomplish is counting the instances of co-occurring "code" values across all "id"s. The data is structured as foll ...

Gathering data from a string delimited by two distinct characters, including the final value

For instance: x=0, y=0, width=1920, height=1080, width_mm=531, height_mm=299, name='\\\\\\\\.\\\\DISPLAY4', is_primary=True I am interested in extracting all the values after the "=" si ...

What is the reason behind django-south not being a part of django.contrib?

Is Django's Built-In Migration Feature Good Enough? Does core django support migration without django-south or a similar app? django-south has become the standard for database migrations in Django, as Django itself does not natively support them. ...

What is the best way to create a Phrases model using a vast collection of articles (such as those from Wikipedia)?

To enhance the results in topic detection and text similarity, I am eager to create a comprehensive gensim dictionary for the French language. My strategy involves leveraging a Wikipedia dump with the following approach: Extracting each article from frwi ...

Execute a Perl script with integer inputs using a Python program

I need to execute the Perl script rtpc.pl from a Python script in the command line with two input arguments. Typically, I run the Perl script using this command line format with two arguments: perl rtpc.pl [ARG1] [ARG2] What I am looking for is a separate ...

"Troubleshooting Issues with NCBI's blastp Command Line Tool

My goal is to automate the process of performing blast outputs from multiple files within a directory. While the variables are currently hardcoded, they will eventually be defined by users. The plan involves changing the input files through a loop in Pytho ...

Locate child elements within a parent class that includes the term "hijack" using

Check out this page: Extract data from: <tr> <td class="event_type">Possible Hijack</td> <td class="country"> </td> <td class="asn">; <i>Expected Origin AS:</i ...

How can I substitute the characters r'xb0' with r'260' in Python?

Is there a way to replace the characters r'\xb0' with r'\260' in a string? I have attempted it using the following code: test = u'\xb0C' test = test.encode('latin1') test = test.replace(r'\x ...

Utilize Pandas to back fill values from a different column in a DataFrame

Looking at a dataframe like this: val1 val2 9 3 2 . 9 4 1 . 5 1 I'm trying to fill in the missing values in 'val2' by referencing 'val1', resulting in: val1 val2 9 3 2 9 9 4 1 3 5 1 Essentially, I wa ...

Encountering Error 405 with Django-Sentry while attempting to transfer error data to localhost on port 9000 at /store

My experience with Django-sentry has been challenging. I am attempting to send errors to localhost:9000/store but facing issues. Here is the error message: jamis$ python manage.py runserver Validating models... 0 errors found Django version 1.3.1, using ...

What is the process for implementing the base class method in a subclass of a derived class?

I'm struggling to understand how to use the method of a base class in my Python program. Despite reading numerous documents, I still can't wrap my head around how super works in situations like the one below. class Car: time = 2 def __in ...

Utilizing a functional approach in Python to create a histogram with a time complexity of O

Is there a better way to phrase this question? Please feel free to correct me. If I wanted to create a histogram using functional programming in Python without any external libraries, how would it be done? def add_value(bins, x): i = int(x // 10) ...

Python Error message regarding choice field in Django Model Forms

Seeking assistance with utilizing ChoiceField in ModelForms. Below is the code snippet from my forms.py file: Format_Choices=[('Line Numbering','Line Numbering'),('Header Numbering','Header Numbering')] class E ...