<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>API Tutorials Archives - relataly.com</title>
	<atom:link href="https://www.relataly.com/tag/api-tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.relataly.com/tag/api-tutorials/</link>
	<description>The Business AI Blog</description>
	<lastBuildDate>Sat, 27 May 2023 10:17:47 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://www.relataly.com/wp-content/uploads/2023/04/cropped-AI-cat-Icon-White.png</url>
	<title>API Tutorials Archives - relataly.com</title>
	<link>https://www.relataly.com/tag/api-tutorials/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">175977316</site>	<item>
		<title>ChatGPT Style Guide: Understanding Voice and Tone Prompt Options for Engaging Conversations</title>
		<link>https://www.relataly.com/chatgpt-style-guide-understanding-voice-and-tone-options-for-engaging-conversations/13065/</link>
					<comments>https://www.relataly.com/chatgpt-style-guide-understanding-voice-and-tone-options-for-engaging-conversations/13065/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Sun, 19 Mar 2023 19:42:03 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Feature Engineering]]></category>
		<category><![CDATA[Language Generation]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[Prompt Engineering]]></category>
		<category><![CDATA[API Tutorials]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=13065</guid>

					<description><![CDATA[<p>In a previous article, we looked at the value proposition of generative AI and ChatGPT (What is the Business Value of OpenAI’s GPT Models (ChatGPT)?). A standout feature of ChatGPT is its ability to write in different styles and tones. Whether you&#8217;re aiming for a professional message, a friendly vibe, a sprinkle of humor and ... <a title="ChatGPT Style Guide: Understanding Voice and Tone Prompt Options for Engaging Conversations" class="read-more" href="https://www.relataly.com/chatgpt-style-guide-understanding-voice-and-tone-options-for-engaging-conversations/13065/" aria-label="Read more about ChatGPT Style Guide: Understanding Voice and Tone Prompt Options for Engaging Conversations">Read more</a></p>
<p>The post <a href="https://www.relataly.com/chatgpt-style-guide-understanding-voice-and-tone-options-for-engaging-conversations/13065/">ChatGPT Style Guide: Understanding Voice and Tone Prompt Options for Engaging Conversations</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">In a previous article, we looked at the value proposition of generative AI and ChatGPT (<a href="https://www.relataly.com/openai-gpt-chatgpt-in-a-business-context-whats-the-value-proposition/12282/" target="_blank" rel="noreferrer noopener">What is the Business Value of OpenAI’s GPT Models (ChatGPT)?</a>). A standout feature of ChatGPT is its ability to write in different styles and tones. Whether you&#8217;re aiming for a professional message, a friendly vibe, a sprinkle of humor and fun, or a display of empathy and understanding, ChatGPT has a vast spectrum of options to cater to your unique needs. The question is, how do you unlock these writing styles? This ChatGPT style guide presents seven vibrant writing styles and describes how to trigger them with the right prompt. Each style has a detailed breakdown of when and how to utilize it.</p>



<p class="wp-block-paragraph">Also: <a href="https://www.relataly.com/mastering-prompt-engineering-for-chatgpt-a-practical-guide-for-businesses/13134/" target="_blank" rel="noreferrer noopener">Mastering Prompt Engineering for ChatGPT</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">Voice and Tone: The Building Blocks of Engaging Conversation</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">ChatGPT is programmed to understand natural language, so you can use variations of these commands or use your own language to convey what you need. For instance, if you want to ask for advice in a professional tone, you can prompt:<br>&#8220;Please give me advice on writing a cover letter in a professional tone.&#8221;</p>



<p class="wp-block-paragraph">Similarly, if you&#8217;re looking for a humorous response to a question, you can use a prompt like:<br>&#8220;Tell me a funny way to explain what AI is.&#8221;</p>



<p class="wp-block-paragraph">ChatGPT is designed to cater to a wide range of conversational styles by offering various voice and tone options. Each option serves a unique purpose and can be utilized to achieve the desired effect in your communication: </p>



<ol class="wp-block-list">
<li>Professional writing style</li>



<li>Conversational writing style</li>



<li>Humorous writing style</li>



<li>Empathic writing style</li>



<li>Simple writing style</li>



<li>Academic writing style</li>



<li>Creative writing style</li>
</ol>



<p class="wp-block-paragraph">Let&#8217;s look at these options in more detail. For each writing style, you will find a sample response from ChatGPT.</p>



<p class="wp-block-paragraph">Also: <a href="https://www.relataly.com/eliminating-friction-how-openais-gpt-streamlines-online-experiences-and-reduces-the-need-for-google-searches/13171/" target="_blank" rel="noreferrer noopener">Eliminating Friction: How OpenAI’s GPT Streamlines Online Experiences and Reduces the Need for Traditional Search</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="512" height="466" data-attachment-id="13072" data-permalink="https://www.relataly.com/chatgpt-style-guide-understanding-voice-and-tone-options-for-engaging-conversations/13065/flo7up_a_fancy_dressed_writer_on_his_desk_writing_a_book_ultrar_c2493584-9579-4acc-97cf-36f5b91008bf-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_a_fancy_dressed_writer_on_his_desk_writing_a_book_ultrar_c2493584-9579-4acc-97cf-36f5b91008bf-min.png" data-orig-size="1012,922" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_a_fancy_dressed_writer_on_his_desk_writing_a_book_ultrar_c2493584-9579-4acc-97cf-36f5b91008bf-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_a_fancy_dressed_writer_on_his_desk_writing_a_book_ultrar_c2493584-9579-4acc-97cf-36f5b91008bf-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_a_fancy_dressed_writer_on_his_desk_writing_a_book_ultrar_c2493584-9579-4acc-97cf-36f5b91008bf-min-512x466.png" alt="" class="wp-image-13072" srcset="https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_a_fancy_dressed_writer_on_his_desk_writing_a_book_ultrar_c2493584-9579-4acc-97cf-36f5b91008bf-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_a_fancy_dressed_writer_on_his_desk_writing_a_book_ultrar_c2493584-9579-4acc-97cf-36f5b91008bf-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_a_fancy_dressed_writer_on_his_desk_writing_a_book_ultrar_c2493584-9579-4acc-97cf-36f5b91008bf-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/03/Flo7up_a_fancy_dressed_writer_on_his_desk_writing_a_book_ultrar_c2493584-9579-4acc-97cf-36f5b91008bf-min.png 1012w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">Understanding the different styles can help you get better responses from ChatGPT. Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a>.</figcaption></figure>
</div>
</div>



<h3 class="wp-block-heading" id="h-writing-style-1-professional">Writing Style #1 Professional </h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">The professional voice and tone is an excellent option for conveying authority, credibility, and professionalism in a variety of business and formal settings. This voice and tone are characterized by a polished, formal, and respectful style that conveys a sense of expertise and competence. It is best suited for use in situations such as job interviews, presentations, formal emails, or any other context where the tone needs to be formal and authoritative.</p>



<h4 class="wp-block-heading">When to Use the Professional Style?</h4>



<ul class="wp-block-list">
<li>Business Correspondence: Professional writing is often used in business correspondence, such as emails, memos, reports, and proposals.</li>



<li>Academic Writing: Professional style is also commonly used in academic writing, such as research papers, essays, and dissertations.</li>



<li>Legal Documents: Legal documents, such as contracts, agreements, and patents, require a professional writing style to ensure clarity and accuracy.</li>



<li>Job Applications: When writing a resume or cover letter for a job application, a professional writing style is necessary to convey your skills and qualifications.</li>



<li>Presentations: Professional style is also suitable for presentations, where you need to convey information clearly and persuasively to your audience.</li>
</ul>



<h4 class="wp-block-heading">Sample Prompt and Response</h4>



<p class="has-background wp-block-paragraph" style="background:linear-gradient(135deg,rgba(7,146,227,0.08) 0%,rgba(155,81,224,0.1) 100%)">Write five sentences on the history of generative AI. Use a professional voice and tone. Use industry-specific language and terminology, provide detailed and accurate information, and support your argument with statistics, research, and expert opinions.</p>



<div class="wp-block-group has-background" style="background:linear-gradient(135deg,rgb(255,206,236) 0%,rgba(150,149,240,0.11) 100%)"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph">Generative AI has its roots in early efforts to develop computer models of human thought and creativity. In the 1950s and 1960s, researchers such as Christopher Strachey and John McCarthy explored the idea of creating computer programs that could generate new content. In the 1990s, generative AI began to gain traction with the advent of deep learning algorithms, which enabled machines to learn patterns in data and create new content based on those patterns. Today, generative AI is a rapidly evolving field, with new breakthroughs being made all the time in areas such as natural language processing and image generation. Despite its potential for creativity and innovation, there are also ethical concerns surrounding the use of generative AI, such as the potential for it to be used in the creation of deepfake content.</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<h4 class="wp-block-heading">How to get a Professional Style?</h4>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Use professional voice and tone. Use industry-specific language and terminology, provide detailed and accurate information, and support your argument with statistics, research, and expert opinions.</pre></div>
</div>
</div>



<h3 class="wp-block-heading">Writing Style #2 Conversational </h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">The conversational style is perfect for creating an informal, friendly, and approachable tone in your interactions with ChatGPT. This voice and tone can be used to simulate a real-life conversation. It makes the user feel like they are talking to a real person rather than a machine.</p>



<h4 class="wp-block-heading">When to Use the Conversational Style?</h4>



<ul class="wp-block-list">
<li>Blog posts: If you run a personal or business blog, you may want to use a conversational writing style to engage your readers and make your content more relatable.</li>



<li>Social media posts: Using a conversational tone, you can build relationships with your followers and encourage them to engage with your content.</li>



<li>Emails: In some cases, a conversational tone can be appropriate for emails, especially for friends, family, or colleagues you are familiar with.</li>



<li>Personal statements: If you are writing a personal statement, such as a college application essay, a conversational tone can help you connect with the reader and convey your personality.</li>



<li>Product descriptions: In e-commerce, a conversational tone can be used to make product descriptions more engaging and to highlight the benefits of a product in a friendly, approachable way.</li>
</ul>



<h4 class="wp-block-heading">Sample Prompt and Response</h4>



<p class="has-background wp-block-paragraph" style="background:linear-gradient(135deg,rgba(7,146,227,0.08) 0%,rgba(155,81,224,0.1) 100%)">Write an email to Georg and ask him if he can help you with your math exam. Use conversational voice and tone. Imagine you&#8217;re talking to a friend and use natural language and phrasing.</p>



<div class="wp-block-group has-background" style="background:linear-gradient(135deg,rgb(255,206,236) 0%,rgba(150,149,240,0.11) 100%)"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph">Hey Georg,</p>



<p class="wp-block-paragraph">I hope this email finds you well. I was wondering if you’d be able to help me out with my math exam. I’ve been struggling with some of the concepts and could really use some extra support.</p>



<p class="wp-block-paragraph">I was hoping we could maybe schedule a study session sometime this week. I promise I’ll bring snacks to fuel our brains! Let me know if that works for you, and we can figure out a time and place that’s convenient.</p>



<p class="wp-block-paragraph">Thanks so much for your help, and let me know if there’s anything I can do in return.</p>



<p class="wp-block-paragraph">Best regards,</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<h4 class="wp-block-heading">How to get a Conversational Style? </h4>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Use conversational voice and tone. Imagine you're talking to a friend and use natural language and phrasing. </pre></div>
</div>
</div>



<h3 class="wp-block-heading">Writing Style #3 Humorous </h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">The humorous style is perfect for breaking the ice, lightening the mood, and injecting a sense of fun and playfulness into your conversations. This tone can be used to engage and entertain your audience, making them feel more comfortable and connected with you. Humor can also help to build rapport, defuse tension, and make your message more memorable.</p>



<h4 class="wp-block-heading">When to Use the Humorous Style? </h4>



<ul class="wp-block-list">
<li>Marketing: A humorous writing style can be used in advertisements to capture the attention of the audience and make the brand more memorable.</li>



<li>Social Media Posts: A humorous writing style can make the information more engaging and shareable in certain types of content, such as social media posts or blog articles.</li>



<li>Presentations: In presentations or speeches, incorporating humor can help break the ice and make the audience more receptive to the message.</li>



<li>Customer Service: A humorous writing style can also be used in customer service interactions to defuse tension and create a more positive experience for the customer.</li>
</ul>



<h4 class="wp-block-heading">Sample Prompt and Response</h4>



<p class="has-background wp-block-paragraph" style="background:linear-gradient(135deg,rgba(7,146,227,0.08) 0%,rgba(155,81,224,0.1) 100%)">Explain Generative AI in 5 sentences.Use a humorous voice and tone, include jokes, and write with irony when appropriate.</p>



<div class="wp-block-group has-background" style="background:linear-gradient(135deg,rgb(255,206,236) 0%,rgba(150,149,240,0.11) 100%)"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph">Generative AI is like a mad scientist who creates new things using nothing but a bunch of data and some complicated algorithms. It&#8217;s like a robot version of Michelangelo painting the Sistine Chapel, except instead of paint, it&#8217;s using ones and zeros. It&#8217;s the ultimate form of recycling &#8211; taking old data and turning it into something shiny and new. But watch out, because if we&#8217;re not careful, the robots might just take over and start creating things we never even imagined. So, let&#8217;s all welcome our new AI overlords with open arms and plenty of data to feed them!</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<h4 class="wp-block-heading">How to Trigger the Humorous Style? </h4>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Use a humorous voice and tone, include jokes, and write with irony when appropriate.</pre></div>
</div>
</div>



<h3 class="wp-block-heading">Writing Style #4 Empathic </h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">The empathic style is a tone that is characterized by sensitivity, compassion, and understanding. This tone is ideal for situations where you need to connect with your audience on an emotional level, such as when dealing with sensitive or difficult topics. The empathic style can also be used to build trust and establish rapport with your audience.</p>



<h4 class="wp-block-heading">When to Use the Empathic Style?</h4>



<ul class="wp-block-list">
<li>Customer support: When dealing with a customer who is frustrated or upset, the empathic style can help you connect with them on a personal level, showing that you understand and care about their situation.</li>



<li>Healthcare: In healthcare-related contexts, the empathic style can be effective in showing patients that you understand their concerns and are committed to helping them.</li>



<li>Social issues: When addressing sensitive social issues such as discrimination or inequality, the empathic style can be used to demonstrate your commitment to understanding and empathizing with those who have been affected.</li>



<li>Personal development: The empathic style can also be useful in coaching or self-help contexts, where understanding and empathy are important components of personal growth and development.</li>
</ul>



<h4 class="wp-block-heading">Sample Prompt and Response</h4>



<p class="has-background wp-block-paragraph" style="background:linear-gradient(135deg,rgba(7,146,227,0.08) 0%,rgba(155,81,224,0.1) 100%)">Write an Email to Erin that you won&#8217;t be able to come to her birthday party. Use empathetic voice and tone.</p>



<div class="wp-block-group has-background" style="background:linear-gradient(135deg,rgb(255,206,236) 0%,rgba(150,149,240,0.11) 100%)"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph">Dear Erin,</p>



<p class="wp-block-paragraph">I  wanted to let you know that unfortunately, I won&#8217;t be able to make it to your birthday party this weekend. I know how much this event means to you, and I feel terrible for not being able to attend.</p>



<p class="wp-block-paragraph">Hope you have a wonderful birthday celebration and create amazing memories with your loved ones. Let me know if there is anything I can do to make it up to you.</p>



<p class="wp-block-paragraph">Take care and enjoy your special day.</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<h4 class="wp-block-heading">How to Trigger the Empathic Style? </h4>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Use empathetic voice and tone. </pre></div>
</div>
</div>



<h3 class="wp-block-heading">Writing Style #5 Academic </h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">Academic writing uses formal language and sophisticated vocabulary. It involves in-depth analysis and research. Complex concepts and scientific principles are explained clearly. Academic writing often cites sources and presents counterarguments. This writing style is suitable for scholarly articles and academic publications.</p>



<h4 class="wp-block-heading">When to Use the Academic Writing Style</h4>



<ul class="wp-block-list">
<li>Writing a research paper for a scientific journal.</li>



<li>Composing a thesis or dissertation.</li>



<li>Writing a literature review for an academic publication.</li>



<li>Writing a technical report or white paper for a professional audience.</li>



<li>Preparing a grant proposal for funding a research project.</li>
</ul>



<h4 class="wp-block-heading">Sample Prompt and Response</h4>



<p class="has-background wp-block-paragraph" style="background:linear-gradient(135deg,rgba(7,146,227,0.08) 0%,rgba(155,81,224,0.1) 100%)">Explain few-shot learning. Use a formal and academic tone, advanced vocabulary and grammar, and provide a thorough analysis of the subject matter. Explain complex concepts clearly and use examples from various fields. Present counterarguments objectively.</p>



<div class="wp-block-group has-background" style="background:linear-gradient(135deg,rgb(255,206,236) 0%,rgba(150,149,240,0.11) 100%)"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph">Few-shot learning is a type of machine learning that allows a model to learn from only a few examples, as opposed to traditional machine learning, which typically requires a large dataset. The goal of few-shot learning is to improve the ability of models to generalize to new situations with limited training data.</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<h4 class="wp-block-heading">How to get an Academic Writing Style?</h4>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Use a formal and academic tone, advanced vocabulary and grammar, and provide a thorough analysis of the subject matter. Explain complex concepts clearly and use examples from various fields. Present counterarguments objectively.</pre></div>
</div>
</div>



<h3 class="wp-block-heading">Writing Style #6 Simple </h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">Simple writing uses straightforward language and short sentences. It avoids jargon and complex vocabulary. The goal is to make information easily accessible to readers. Simple writing often targets a 5th-grade reading level. This writing style is suitable for explaining topics to a wide audience.</p>



<h4 class="wp-block-heading">When to Use the Simple Writing Style? </h4>



<ul class="wp-block-list">
<li>Writing instructions for a manual or guide</li>



<li>Creating marketing materials for a broad audience</li>



<li>Writing for individuals with cognitive or language impairments</li>



<li>Creating content for social media or blogs with a focus on readability and accessibility</li>



<li>Writing emails or memos to colleagues or clients who prefer a straightforward communication style.</li>
</ul>



<h4 class="wp-block-heading">Sample Prompt and Response</h4>



<p class="has-background wp-block-paragraph" style="background:linear-gradient(135deg,rgba(7,146,227,0.08) 0%,rgba(155,81,224,0.1) 100%)">Explain Generative AI in 5 sentences. Use simple language, break down complex concepts into frameworks or models, and provide practical takeaways.</p>



<div class="wp-block-group has-background" style="background:linear-gradient(135deg,rgb(255,206,236) 0%,rgba(150,149,240,0.11) 100%)"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph">Generative AI is a type of artificial intelligence that creates new content, such as images, videos, or text, based on existing data inputs. It uses complex algorithms and models to generate outputs that resemble the original data, but with unique variations and combinations. Generative AI can be used in a wide range of applications, including art, music, and design, to create new and innovative content. To achieve optimal results with generative AI, it&#8217;s essential to have high-quality and diverse data inputs, as well as a well-designed algorithm that can effectively capture the patterns and trends in the data. Ultimately, generative AI provides a powerful tool for businesses and creators to explore new possibilities and push the boundaries of what&#8217;s possible in the digital world.</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<h4 class="wp-block-heading">How to get the Simple Writing Style?</h4>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Use simple language, break down complex concepts into frameworks or models, and provide practical takeaways.</pre></div>
</div>
</div>



<h3 class="wp-block-heading">Writing Style #7 Creative </h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">The creative writing style is all about using vivid and imaginative language to paint a picture in the reader&#8217;s mind. It often employs literary devices like similes, metaphors, and personification to make the writing more engaging and evocative. This style encourages authors to explore unique perspectives and ideas in their writing. Creative writing can be found in various forms such as novels, short stories, poetry, and even personal essays. The goal is to captivate the reader and evoke emotions through the power of words and storytelling.</p>



<h4 class="wp-block-heading">When to Use the Creative Writing Style</h4>



<ul class="wp-block-list">
<li>Writing a short story or novel</li>



<li>Crafting a poem</li>



<li>Creating marketing copy that stands out from the competition</li>



<li>Designing an engaging social media post or caption</li>



<li>Developing content for a creative writing class or workshop</li>



<li>Drafting a screenplay or script for film or theater</li>



<li>Writing a personal essay or memoir with a unique voice and style</li>
</ul>



<h4 class="wp-block-heading">Sample Prompt and Response</h4>



<p class="has-background wp-block-paragraph" style="background:linear-gradient(135deg,rgba(7,146,227,0.08) 0%,rgba(155,81,224,0.1) 100%)">Write an invitation to the 30th birthday party of Peter. Use vivid language to create imagery and atmosphere. Use metaphors, and personification.</p>



<div class="wp-block-group has-background" style="background:linear-gradient(135deg,rgb(255,206,236) 0%,rgba(150,149,240,0.11) 100%)"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph">Ladies and gentlemen, welcome to the celebration of a milestone birthday! Tonight, we gather to honor the one and only Peter as he turns thirty years young. As the sun sets and the stars come out to play, the air is electric with anticipation and excitement. The balloons are bobbing, the confetti is ready to be thrown, and the candles on the cake are flickering, waiting to be blown out. The night is alive with the sound of laughter and celebration, and we can feel the energy pulsing through the room like a living, breathing entity. So let&#8217;s raise a glass, toast to Peter, and get this party started!</p>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<h4 class="wp-block-heading">How to get the Creative Writing Style?</h4>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Use vivid language to create imagery and atmosphere. Use metaphors, and personification.</pre></div>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<h2 class="wp-block-heading">Additional Prompt Instructions</h2>



<p class="wp-block-paragraph">When crafting a prompt for ChatGPT, it&#8217;s important to keep in mind that the AI model can effectively structure its response using headings, subheadings, and bullet points. By including these elements in your prompt, you can guide ChatGPT to create a well-organized and easy-to-follow response that effectively communicates the information you need.</p>



<p class="wp-block-paragraph">To ensure that ChatGPT incorporates headings, subheadings, and bullet points in its response, be sure to include them explicitly in your prompt instructions. For example, you can tell the model to use a main heading to introduce the main topic of your prompt, followed by subheadings to break down specific aspects of that topic. Use bullet points to highlight key takeaways or important information.</p>



<h3 class="wp-block-heading">Sample Prompt and Response</h3>



<p class="has-background wp-block-paragraph" style="background:linear-gradient(135deg,rgba(7,146,227,0.08) 0%,rgba(155,81,224,0.1) 100%)">Describe generative AI. Use Headings and subheadings to structure the description.</p>



<div class="wp-block-group has-background" style="background:linear-gradient(135deg,rgb(255,206,236) 0%,rgba(150,149,240,0.11) 100%)"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph">Introduction:</p>



<p class="wp-block-paragraph">Generative AI is a field of artificial intelligence that focuses on creating computer models capable of producing outputs that resemble human creations, such as images, music, or language.</p>



<p class="wp-block-paragraph">I. What is Generative AI? Generative AI refers to a class of machine learning models designed to create new data that did not exist before. It is based on a set of rules, patterns, and probabilities that the algorithm follows to generate outputs that are similar to what it has learned from the training data.</p>



<p class="wp-block-paragraph">II. Applications of Generative AI Generative AI has found many applications in various industries, such as:</p>



<ul class="wp-block-list">
<li>Image and video generation</li>



<li>Music and sound synthesis</li>



<li>Natural language processing and dialogue generation</li>



<li>Gaming and virtual reality</li>



<li>Drug discovery and molecular design</li>



<li>Text-to-speech and speech-to-text conversion</li>
</ul>



<p class="wp-block-paragraph">&#8230;</p>
</div></div>



<h3 class="wp-block-heading">Configuration Options of the ChatGPT API</h3>



<p class="wp-block-paragraph">If you are using the OpenAI API, the temperature setting is an additional configuration option that influences the style of writing. You can find more information on the temperature setting in the <a href="https://platform.openai.com/docs/introduction" target="_blank" rel="noreferrer noopener">OpenAI documentation</a>. </p>



<p class="wp-block-paragraph">The temperature option in ChatGPT is a setting that controls the level of randomness or creativity in the responses generated by the model. When set to a low temperature, the responses tend to be more predictable and safe, while higher temperatures result in more varied and unpredictable responses.</p>



<p class="wp-block-paragraph">This setting can significantly impact the tone and style of writing, as it can influence the degree of creativity and spontaneity in the language used. For example, a lower temperature setting may result in more formal and straightforward responses, while a higher temperature setting may lead to more playful or experimental language.</p>



<p class="wp-block-paragraph">Additionally, the temperature setting can be used to tailor the writing style to a specific audience or purpose. For instance, a more formal or professional tone may be appropriate for business communications, while a more casual or humorous tone may be more suitable for social media interactions.</p>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">ChatGPT&#8217;s wide range of voice and tone options can greatly enhance your user experience by allowing you to adapt its writing style to match your specific needs. The seven writing styles presented in this article showcase the diverse range of techniques that writers can employ to engage and connect with their audience. By following this ChatGPT style guide, you&#8217;ll be equipped with the knowledge and tools necessary to utilize ChatGPT&#8217;s different writing styles, whether it be for professional or personal communication.</p>



<p class="wp-block-paragraph">The ability to effectively communicate and engage with others is essential in today&#8217;s fast-paced digital world, and ChatGPT provides a powerful tool to help you do just that. By leveraging the different voice and tone options available in ChatGPT, you can tailor your interactions to suit your audience and achieve your communication goals.</p>



<p class="wp-block-paragraph">I hope this article was helpful. If you have any questions, let me know in the comments.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<p class="wp-block-paragraph"></p>



<figure class="wp-block-image size-large"><img decoding="async" width="512" height="510" data-attachment-id="13098" data-permalink="https://www.relataly.com/chatgpt-style-guide-understanding-voice-and-tone-options-for-engaging-conversations/13065/a_steampunk_technician_configuring_a_robot_with_various_options/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/a_steampunk_technician_configuring_a_robot_with_various_options.png" data-orig-size="1014,1010" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="a_steampunk_technician_configuring_a_robot_with_various_options" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/a_steampunk_technician_configuring_a_robot_with_various_options.png" src="https://www.relataly.com/wp-content/uploads/2023/03/a_steampunk_technician_configuring_a_robot_with_various_options-512x510.png" alt="Prompt engineering allows you to tailor an AI conversation to your goals as well as the requirements and preferences of your audience." class="wp-image-13098" srcset="https://www.relataly.com/wp-content/uploads/2023/03/a_steampunk_technician_configuring_a_robot_with_various_options.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/a_steampunk_technician_configuring_a_robot_with_various_options.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/a_steampunk_technician_configuring_a_robot_with_various_options.png 140w, https://www.relataly.com/wp-content/uploads/2023/03/a_steampunk_technician_configuring_a_robot_with_various_options.png 768w, https://www.relataly.com/wp-content/uploads/2023/03/a_steampunk_technician_configuring_a_robot_with_various_options.png 1014w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">Prompt engineering allows you to tailor an AI conversation to your goals as well as the requirements and preferences of your audience. Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">midjourney</a>.</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<p class="wp-block-paragraph"><a href="https://platform.openai.com/docs/introduction" target="_blank" rel="noreferrer noopener">platform.openai.com/docs</a></p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-embed is-type-wp-embed is-provider-relataly-com wp-block-embed-relataly-com"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="jHugMZGxy9"><a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/">9 Powerful Applications of OpenAI&#8217;s ChatGPT and Davinci for Your Business</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;9 Powerful Applications of OpenAI&#8217;s ChatGPT and Davinci for Your Business&#8221; &#8212; relataly.com" src="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/embed/#?secret=mqdxzwpkPh#?secret=jHugMZGxy9" data-secret="jHugMZGxy9" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-embed is-type-wp-embed is-provider-relataly-com wp-block-embed-relataly-com"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="tamEIG3u6F"><a href="https://www.relataly.com/openai-gpt-chatgpt-in-a-business-context-whats-the-value-proposition/12282/">What is the Business Value of OpenAI&#8217;s GPT Models (ChatGPT)?</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;What is the Business Value of OpenAI&#8217;s GPT Models (ChatGPT)?&#8221; &#8212; relataly.com" src="https://www.relataly.com/openai-gpt-chatgpt-in-a-business-context-whats-the-value-proposition/12282/embed/#?secret=3OD5oY6kqE#?secret=tamEIG3u6F" data-secret="tamEIG3u6F" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-embed is-type-wp-embed is-provider-relataly-com wp-block-embed-relataly-com"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="kJliMk39jS"><a href="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/">Unleashing the Power of ChatGPT and Other OpenAI GPT Language Models in Python A Guide to Using APIs</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;Unleashing the Power of ChatGPT and Other OpenAI GPT Language Models in Python A Guide to Using APIs&#8221; &#8212; relataly.com" src="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/embed/#?secret=yKOVixKhLv#?secret=kJliMk39jS" data-secret="kJliMk39jS" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>
</div>
</div>
<p>The post <a href="https://www.relataly.com/chatgpt-style-guide-understanding-voice-and-tone-options-for-engaging-conversations/13065/">ChatGPT Style Guide: Understanding Voice and Tone Prompt Options for Engaging Conversations</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/chatgpt-style-guide-understanding-voice-and-tone-options-for-engaging-conversations/13065/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">13065</post-id>	</item>
		<item>
		<title>Generating Detailed Images with OpenAI DALL-E and ChatGPT in Python: A Step-By-Step API Tutorial</title>
		<link>https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/</link>
					<comments>https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Sat, 21 Jan 2023 23:20:41 +0000</pubDate>
				<category><![CDATA[Language Generation]]></category>
		<category><![CDATA[Marketing Automation]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[REST APIs]]></category>
		<category><![CDATA[API Tutorials]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<category><![CDATA[Deep Learning]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=12143</guid>

					<description><![CDATA[<p>In this article, we will explore how to automate the creation of AI-generated art by integrating DALL-E with ChatGPT using the respective APIs in Python. ChatGPT, the state-of-the-art language model developed by OpenAI, has recently made waves in the tech community for its exceptional language abilities, such as code generation, prompt answering, and text completion. ... <a title="Generating Detailed Images with OpenAI DALL-E and ChatGPT in Python: A Step-By-Step API Tutorial" class="read-more" href="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/" aria-label="Read more about Generating Detailed Images with OpenAI DALL-E and ChatGPT in Python: A Step-By-Step API Tutorial">Read more</a></p>
<p>The post <a href="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/">Generating Detailed Images with OpenAI DALL-E and ChatGPT in Python: A Step-By-Step API Tutorial</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">In this article, we will explore how to automate the creation of AI-generated art by integrating DALL-E with ChatGPT using the respective APIs in Python. ChatGPT, the state-of-the-art language model developed by OpenAI, has recently made waves in the tech community for its exceptional language abilities, such as code generation, prompt answering, and text completion. DALL-E, another powerful language model developed by OpenAI, specializes in generating images from text prompts. This tutorial will utilize the OpenAI GPT3-API to generate a detailed and specific prompt for DALL-E. We will then use the prompt in a request to the DALL-E API to generate images. The generated images will be displayed and saved for future use. </p>



<p class="wp-block-paragraph">Throughout the tutorial, we will provide clear explanations and code snippets to guide you through the process. By the end of this tutorial, you will have a comprehensive understanding of how to automate prompt generation for DALL-E with Python. So, let&#8217;s get started!</p>



<p class="wp-block-paragraph">If you&#8217;re new to the OpenAI API, my recent <a href="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/" target="_blank" rel="noreferrer noopener">API tutorial on ChatGPT and other OpenAI language models</a> might be helpful to check out.</p>



<p class="wp-block-paragraph">Also: <a href="https://www.relataly.com/mastering-prompt-engineering-for-chatgpt-a-practical-guide-for-businesses/13134/" target="_blank" rel="noreferrer noopener">Mastering Prompt Engineering for ChatGPT for Business Use</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="235" data-attachment-id="12157" data-permalink="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/image-10-4/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/image-10.png" data-orig-size="1133,260" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-10" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/image-10.png" src="https://www.relataly.com/wp-content/uploads/2023/01/image-10-1024x235.png" alt="Images created with automated prompt generation for OpenAI Dall-E using ChatGPT in Python" class="wp-image-12157" srcset="https://www.relataly.com/wp-content/uploads/2023/01/image-10.png 1024w, https://www.relataly.com/wp-content/uploads/2023/01/image-10.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/image-10.png 768w, https://www.relataly.com/wp-content/uploads/2023/01/image-10.png 1133w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Images created with automated prompt generation for <a href="https://openai.com/dall-e-2/" target="_blank" rel="noreferrer noopener">OpenAI DALL-E</a> using ChatGPT in Python</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Generating AI-Art using DALL-E: How it Works</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">DALL-E is a language model developed by OpenAI that is capable of generating images from text prompts. It uses deep learning techniques to understand the input text and generate images that are related to the text. DALL-E is trained on a massive dataset of images and texts, allowing it to generate a wide range of images. This allows the model to take text prompts as input and generate images that are related to the prompt. </p>



<p class="wp-block-paragraph">The input to a language model is what we call a prompt. A prompt to GPT typically includes a general instruction, a specific topic, and additional keywords (for example, digital art, oil painting, etc.). The DALL-E model then uses this information to generate the images. Usually, four different images are generated per request. DALL-E can do various other things, such as completing or altering existing images. However, this article will focus on image generation. </p>



<p class="wp-block-paragraph">The images generated by DALL-E can be of various types, such as illustrations, drawings, photographs, etc. While the quality of the images is generally surprisingly good, the model can do some things, certainly better than others. For example, you will find that human faces and bodies sometimes lead to odd results. But, in general, images are often surprisingly coherent with the provided text prompts. </p>



<p class="wp-block-paragraph">AI-generated images can be useful for various applications. These include creating AI-generated art, creating illustrations for books, creating images for social media, creating product images for e-commerce, and more. In many cases, generating images from text prompts can save time and resources, as it eliminates the need for manual image creation.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="441" data-attachment-id="12161" data-permalink="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/image-11-9/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/image-11.png" data-orig-size="1773,763" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-11" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/image-11.png" src="https://www.relataly.com/wp-content/uploads/2023/01/image-11-1024x441.png" alt="UI of the OpenAI DALL-E2 service for AI-generated images. The AI services generate images based on a manual prompt defined by the user. " class="wp-image-12161" srcset="https://www.relataly.com/wp-content/uploads/2023/01/image-11.png 1024w, https://www.relataly.com/wp-content/uploads/2023/01/image-11.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/image-11.png 768w, https://www.relataly.com/wp-content/uploads/2023/01/image-11.png 1536w, https://www.relataly.com/wp-content/uploads/2023/01/image-11.png 1773w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">UI of the <a href="https://openai.com/dall-e-2/" target="_blank" rel="noreferrer noopener">OpenAI DALL-E2</a> service for AI-generated images. The AI services generate images based on a manual prompt defined by the user. </figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading" id="h-automated-dall-e-prompts-using-chatgpt">Automated DALL-E Prompts using ChatGPT</h2>



<p class="wp-block-paragraph">he usual way to generate images with DALL-E is via a manual prompt on the OpenAI website. However, DALL-E also offers <a href="https://openai.com/blog/dall-e-api-now-available-in-public-beta/" target="_blank" rel="noreferrer noopener">an API</a>, which allows for automating image generation. Of course, you could send a manually written prompt to the API and automatically process the response. However, if you want to optimize the quality of the generated images or consistently automate the whole process, there is a better way of doing this using ChatGPT. </p>



<p class="wp-block-paragraph">You may have heard of ChatGPTs abilities to complete and generate high-quality text. However, few people know that ChatGPT can also generate prompts for DALL-E. This works by simply telling the model to generate a prompt for DALL-E and then specifying the topic for which you want to create the prompt. An example prompt could be:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">&quot;generate a prompt for DALL-E on a robot on the beach&quot;.</pre></div>



<p class="wp-block-paragraph">And the response from ChatGPT: </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">The gleeful robot lounged on the sun-drenched beach, soaking up the warm rays and listening to the soothing crash of the waves. It wore a bright, multicolored swimsuit and a wide-brimmed hat to protect its circuitry from the intense heat. It smiled contentedly as it watched the seagulls soar through the azure sky and the cheerful children playing in the foamy surf. The salty-sweet scent of the sea filled its senses, and it felt truly relaxed and rejuvenated.</pre></div>



<p class="wp-block-paragraph">As you can see, the response is very detailed and uses a lot of adjectives. As a result, the images generated with these prompts are often highly creative and detailed. Below is the result from DALL-E for this specific prompt:</p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="12169" data-permalink="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/image-12/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/image-12.png" data-orig-size="3241,797" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-12" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/image-12.png" src="https://www.relataly.com/wp-content/uploads/2023/01/image-12-1024x252.png" alt="Example DALL-E creation for a ChatGPT-generated prompt using the command: &quot;generate a prompt for DALL-E on a robot on the beach.&quot;" class="wp-image-12169" width="1092" height="269" srcset="https://www.relataly.com/wp-content/uploads/2023/01/image-12.png 1024w, https://www.relataly.com/wp-content/uploads/2023/01/image-12.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/image-12.png 768w, https://www.relataly.com/wp-content/uploads/2023/01/image-12.png 1536w, https://www.relataly.com/wp-content/uploads/2023/01/image-12.png 2048w, https://www.relataly.com/wp-content/uploads/2023/01/image-12.png 2475w" sizes="(max-width: 1092px) 100vw, 1092px" /><figcaption class="wp-element-caption">Example DALL-E creation for a ChatGPT-generated prompt using the command: &#8220;generate a prompt for DALL-E on a robot on the beach.&#8221;</figcaption></figure>



<h2 class="wp-block-heading">Why You May Want to Automate Prompt Generation for DALL-E</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">Automating prompt generation for DALL-E has several benefits. Some of the reasons why you may want to automate prompt generation include the following:</p>



<ul class="wp-block-list">
<li><strong>Efficiency: </strong>Automating the prompt generation process can save time and resources as it eliminates the need for manual input.</li>



<li><strong>More Details:</strong> The prompts generated by ChatGPT are typically more detailed than what humans typically use to generate images. </li>



<li><strong>Consistency:</strong> By using a language model like ChatGPT to generate prompts, you can ensure that the prompts are grammatically correct and well-formed, which can improve the quality of the generated images.</li>



<li><strong>Variety:</strong> By using ChatGPT to generate prompts, you can include additional keywords, making the generation more diverse and less repetitive.</li>



<li><strong>Automation</strong>: When incorporating AI-generated images into an integrated process, utilizing APIs to automate the process is essential. For instance, an integration with Twitter can be implemented where ChatGPT automatically picks up keywords from tweets and generates images based on those keywords, which can be published on Twitter.</li>
</ul>



<p class="wp-block-paragraph">Using ChatGPT to generate DALL-E prompts allows for more efficient and accurate image generation and the ability to generate more detailed images. It also reduces the need for manual input and allows you to integrate image generation models into complex processes.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="1024" data-attachment-id="12164" data-permalink="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/20230122212613_dall-e2/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/20230122212613_dall-e2.png" data-orig-size="1024,1024" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="20230122212613_dall-e2" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/20230122212613_dall-e2.png" src="https://www.relataly.com/wp-content/uploads/2023/01/20230122212613_dall-e2-1024x1024.png" alt="The images generated based on the ChatGPT prompts are often superior in details and creativity." class="wp-image-12164" srcset="https://www.relataly.com/wp-content/uploads/2023/01/20230122212613_dall-e2.png 1024w, https://www.relataly.com/wp-content/uploads/2023/01/20230122212613_dall-e2.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/20230122212613_dall-e2.png 140w, https://www.relataly.com/wp-content/uploads/2023/01/20230122212613_dall-e2.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">The images generated based on the ChatGPT prompts are often superior in detail and creativity. </figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Automated Dall-E Prompt Generation using ChatGPT in Python</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">In the following, we will generate a Python script that integrates DALL-E with ChatGPT to create AI-generated images from keywords or short descriptions. </p>



<p class="wp-block-paragraph">Here are the general steps involved in generating DALL-E prompts using ChatGPT in Python:</p>



<ol class="wp-block-list">
<li>To use the OpenAI models, we will first need to authenticate with the OpenAI API by providing our API key. In the next section, we will look at how you can register for a key. We will also briefly discuss the costs of using OpenAI models.</li>



<li>Define a ChatGPT Prompt: An image prompt is the text input that the DALL-E model uses to generate a response. We will use ChatGPT to generate this prompt</li>



<li>Generate a Prompt Design with ChatGPT: Generate a response: Once we have a prompt, we can use the GPT-3 model to generate a prompt for DALL-E.</li>



<li>Send the prompt to DALL-E API: The response obtained from the above step is sent to DALL-E API to generate the images.  </li>



<li>Process the Image Response from DALL-E: Once we have the image from the DALL-E API, we print the images and save them to a local folder using.</li>
</ol>



<p class="wp-block-paragraph">Let&#8217;s get started!</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_0ef08b-07"><a class="kb-button kt-button button kb-btn_87e152-45 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials/blob/master/07%20OpenAI/601%20Promt%20Augmentation%20for%20Dall-E%20using%20ChatGPT%20in%20Python%20copy.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_dd8798-00 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div style="height:28px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Register for an OpenAI API Key</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">To use the OpenAI API, you will first need to register for an API key by visiting the OpenAI website and creating an account. During the registration process, you will be required to provide some basic information about yourself and the project you are working on. In addition, you will need to add a payment method. The <a href="https://openai.com/api/pricing/" target="_blank" rel="noreferrer noopener">cost per request is a couple of cents</a>, depending on which model you use. In this tutorial, we will use the Davinci model, which is 0.02$ per 1000 tokens.</p>



<p class="wp-block-paragraph">It’s important to note that while GPT-3 is currently available in a free test version, the OpenAI API itself is not free. If you only plan to send a few test requests, the costs will be minimal, but if you integrate the API with a successful application that runs in production, the costs can quickly accumulate. </p>



<p class="wp-block-paragraph">Each language model offered by OpenAI has a different price tag, and charges depend on various factors. For language models, charges are based on the number of tokens sent to the model and the type of the model.</p>



<p class="wp-block-paragraph">Prices for image models depend on the resolution at which you generate the images.</p>



<p class="wp-block-paragraph">I recommend monitoring usage and keeping track of costs to avoid unexpected charges. To manage costs, you can set up a quota on the costs in the OpenAI portal under your profile. This will help you to keep an eye on the costs and keep them within your budget.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image is-resized"><img decoding="async" data-attachment-id="12091" data-permalink="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/image-8-3/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/image-8.png" data-orig-size="1768,685" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-8" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/image-8.png" src="https://i0.wp.com/www.relataly.com/wp-content/uploads/2023/01/image-8.png?resize=887%2C344&amp;ssl=1" alt="Prices of different language models offered by OpenAI. " class="wp-image-12091" width="354" height="138" srcset="https://www.relataly.com/wp-content/uploads/2023/01/image-8.png 1768w, https://www.relataly.com/wp-content/uploads/2023/01/image-8.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/image-8.png 1024w, https://www.relataly.com/wp-content/uploads/2023/01/image-8.png 768w, https://www.relataly.com/wp-content/uploads/2023/01/image-8.png 1536w" sizes="(max-width: 354px) 100vw, 354px" /><figcaption class="wp-element-caption">Overview of <a href="https://openai.com/api/pricing/" target="_blank" rel="noreferrer noopener">Prices for OpenAI language</a> models (as of 2023-22-01).</figcaption></figure>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="12174" data-permalink="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/image-13/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/image-13.png" data-orig-size="2068,444" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-13" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/image-13.png" src="https://www.relataly.com/wp-content/uploads/2023/01/image-13-1024x220.png" alt="" class="wp-image-12174" width="356" height="77" srcset="https://www.relataly.com/wp-content/uploads/2023/01/image-13.png 1024w, https://www.relataly.com/wp-content/uploads/2023/01/image-13.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/image-13.png 768w, https://www.relataly.com/wp-content/uploads/2023/01/image-13.png 1536w, https://www.relataly.com/wp-content/uploads/2023/01/image-13.png 2048w" sizes="(max-width: 356px) 100vw, 356px" /><figcaption class="wp-element-caption">Overview of <a href="https://openai.com/api/pricing/" target="_blank" rel="noreferrer noopener">prices for OpenAI image models</a> (as of 2023-22-01). </figcaption></figure>
</div>
</div>



<h3 class="wp-block-heading">Technical Setup</h3>



<p class="wp-block-paragraph">Before diving into the code, it&#8217;s essential to ensure that you have the proper setup for your Python 3 environment and have installed all the necessary packages. If you do not have a Python environment, you can follow the instructions in <a href="https://www.relataly.com/anaconda-python-environment-machine-learning/1663/" target="_blank" rel="noreferrer noopener">this tutorial</a> to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda Python environment</a>. This will provide you with a robust and versatile environment that is well-suited for machine learning and data science tasks.</p>



<p class="wp-block-paragraph">Before you can start generating DALL-E prompts, you&#8217;ll need to install the <a href="https://beta.openai.com/docs/api-reference?lang=python" target="_blank" rel="noreferrer noopener">OpenAI library for Python</a>, which provides access to the GPT-3 model. You can do this by running &#8220;pip install openai&#8221; in your command line.</p>



<p class="wp-block-paragraph">In addition, this tutorial will work with matplotlib and PIL and standard libraries such as yaml, os, and datetime. You can install the OpenAI Python library using console commands:</p>



<ul class="wp-block-list">
<li><em>pip install </em>&lt;package name&gt;</li>



<li><em>conda install </em>&lt;package name&gt; (if you are using the anaconda packet manager)</li>
</ul>



<h3 class="wp-block-heading">Step #1 Imports and Autenthication at the OpenAI API</h3>



<p class="wp-block-paragraph">To begin, we import the required libraries and provide our API key for authorization. I recommend to store the API key in a separate file, such as api_config_openai.yml. The code below will read the API key from this file and make it accsessible in the code. You can also place the API key directly in the code, but be mindful not to make it publicly accessible. </p>



<p class="wp-block-paragraph">With the API key set up, you can use the OpenAI API&#8217;s &#8220;Model.list()&#8221; function to retrieve a list of available models. For this you have to uncomment the last four lines in the following code snippet. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">import openai
import yaml
import urllib.request
from PIL import Image
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import os
from datetime import datetime
# set the API Key 
yaml_file = open('API Keys/api_config_openai.yml', 'r')  
p = yaml.load(yaml_file, Loader=yaml.FullLoader)
openai.api_key = p['api_key']
# show available openai language models (this tutorial uses davinci003)
# modellist = openai.Model.list()
# for i in modellist.data:
#     print(i.id)</pre></div>



<h3 class="wp-block-heading">Step #2 Define a ChatGPT Prompt</h3>



<p class="wp-block-paragraph">Next, we define the prompt for ChatGPT in which we request a prompt for DALL-E.</p>



<h4 class="wp-block-heading">Defining Prompts</h4>



<p class="wp-block-paragraph">When we define prompts for ChatGPT there are a few things to keep in mind. The primary focus should be to provide a clear and specific task or question. Although the AI can still function with incomplete or incorrect information, providing it with detailed instructions will improve its performance. In addition, keyword relevance is essential.</p>



<p class="wp-block-paragraph"> To ensure the AI tool produces the desired results, it&#8217;s vital to use relevant keywords in your input. The tool must first understand the input accurately before it can generate the expected output. A well-crafted prompt can improve the tool&#8217;s performance and accelerate your progress. </p>



<p class="wp-block-paragraph">DALL-E also knows certain keywords, that will send the model in the one or the other direction. For example, you can define the type of image you want to be generated by adding keywords such as oil paining, aqurael painting, digital art, or Van-Gogh style. This article provides <a href="https://aituts.com/dall-e-2/" target="_blank" rel="noreferrer noopener">a good overview of these keywords</a>. </p>



<h4 class="wp-block-heading">Send the Request to the OpenAI Language Model</h4>



<p class="wp-block-paragraph">We encapsulate this request in a function called &#8220;send_openai_request&#8221; that takes in three parameters: &#8220;engine,&#8221; &#8220;prompt,&#8221; and &#8220;max_tokens&#8221;. The function uses the OpenAI API&#8217;s &#8220;Completion.create()&#8221; method to send a request to the specified engine with the provided prompt and maximum token limit.</p>



<p class="wp-block-paragraph">In the code below, we have created a simple start phrase called &#8220;prompt_base&#8221;: &#8220;Generate a detailed Dall-E prompt with several adjectives for&#8221;.  You can then simply add the topic for which you want to generate the images as &#8220;prompt_details.&#8221; Alternatively, you can append &#8220;additional_keywords&#8221; to the prompt that will be added after the language model has generated the prompt for DALL-E.</p>



<p class="wp-block-paragraph">There are different language models available but the one that creates the most detailed results and is closest to ChatGPT is &#8220;text-davinci-003&#8221;. This is the version used in this tutorial. Finally, we send the request and print out the response with the generated prompt. </p>



<p class="wp-block-paragraph">The prompt is constructed using a base prompt, which is a general instruction to the model, a specific topic &#8220;sugar castle&#8221; and additional keywords &#8220;digital art&#8221;. The function &#8220;send_openai_request&#8221; is defined to handle the request to the language model, it takes three parameters &#8220;engine&#8221; (model version), &#8220;prompt&#8221; (the instruction for the model) and &#8220;max_tokens&#8221; (maximum number of tokens in the response). We are sending a request to the OpenAI API to generate a response, which is returned and stored in the variable &#8220;response&#8221;.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># define the request
def send_openai_request(engine, prompt, max_tokens=1024):
    response = openai.Completion.create(
        engine=engine,
        prompt=prompt,
        max_tokens=max_tokens,
        n=1,
        stop=None,
        temperature=0.7
    )
    return response
# define the prompt to the language model
prompt_base = &quot;Generate a detailed Dall-E prompt with several adjectives for &quot; # an introduction text telling the language model what to do
prompt_details = &quot;sugar castle&quot; # the topic for which you wish to generate the images 
additional_keywords = &quot;,digital art&quot; # these keywords will be added after the language model generated the prompt. Example: &quot;digital art&quot;, &quot;oil painting&quot;, &quot;water color painting&quot;, &quot;high quality&quot;
model=&quot;text-davinci-003&quot; # the version of the openai language model
# generate a response
response = send_openai_request(model, prompt_base + prompt_details)
# print the response from the language model
generated_prompt = response[&quot;choices&quot;][0][&quot;text&quot;]
print(generated_prompt)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Make me a picture of a majestic, shimmering, sparkling sugar castle with a dazzling crystal spire and enchanting turrets, surrounded by an emerald green moat and a towering rainbow-hued wall.</pre></div>



<h3 class="wp-block-heading">Step #3 Generate a Prompt Design with ChatGPT</h3>



<p class="wp-block-paragraph">Next, we specify the parameters for generating images using the OpenAI DALL-E API. We have set the variable &#8220;number_of_images&#8221; to 2, which means it will generate 2 images. In addition, we set the &#8220;image_size&#8221; to &#8220;512&#215;512,&#8221; which is the size of the images to be generated. </p>



<p class="wp-block-paragraph">We create the final prompt to DALL-E called &#8220;image_generation_prompt&#8221; by combining the &#8220;generated_prompt&#8221; variable obtained from the previous text prompt and the &#8220;additional_keywords&#8221; variable. </p>



<p class="wp-block-paragraph">Finally, we are printing out a message indicating that DALL-E will generate the specified number of images at the specified size, using the provided prompt.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># image parameters
number_of_images = 2 # how many images you want to generate
image_size = &quot;512x512&quot; # the size of the images
image_generation_prompt = f&quot;{generated_prompt} {additional_keywords}&quot;
print(f&quot;Dall-e will generate {number_of_images} images {image_size} using the following prompt: {image_generation_prompt}&quot;)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Dall-e will generate 2 images 512x512 using the following prompt: 
Make me a picture of a majestic, shimmering, sparkling sugar castle with a dazzling crystal spire and enchanting turrets, surrounded by an emerald green moat and a towering rainbow-hued wall. digital art</pre></div>



<h3 class="wp-block-heading">Step #4 Send the Generated Prompt to the DALL-E API</h3>



<p class="wp-block-paragraph">Next, we send the request to the OpenAI DALL-E API using the &#8220;image_generation_prompt&#8221; variable created earlier. We are sending the request using OpenAI&#8217;s &#8220;Image.create()&#8221; method, which takes the prompt, number of images, and size as parameters. The response from the API is stored in the &#8220;response&#8221; variable.</p>



<p class="wp-block-paragraph">We are looping through the response data and appending the URLs of each image in the list. Finally, we call the function get_images on the response, storing the resulting image URLs in the &#8220;image_list&#8221; variable and displaying the image URLs in the output.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># define and send the request to dall-e with the generated prompt
response = openai.Image.create(
    prompt=image_generation_prompt,
    n=number_of_images,
    size=image_size,
)
# set the timestamp for data processing
timestamp_string = response.created
datetime_string = datetime.fromtimestamp(timestamp_string).strftime(&quot;%Y%m%d%H%M%S&quot;)
# get the image(s) from the response
def get_images(response):
    # generate an empty list for the image urls
    image_list = []
    # store the image urls in the list
    for imgurl in response.data:
        image_list.append(imgurl.url)
    return image_list
image_list = get_images(response)
#display image urls
print(image_list)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">['https://oaidalleapiprodscus.blob.core.windows.net/private/org-eO72e4aFm9XJBw4sb91Z8XEX/user-9ZRwLxYMDBxvw6gLEywP44xa/img-BdkqLm65g8QLIpLbgHhDkxbf.png?st=2023-01-22T19%3A03%3A51Z&amp;se=2023-01-22T21%3A03%3A51Z&amp;sp=r&amp;sv=2021-08-06&amp;sr=b&amp;rscd=inline&amp;rsct=image/png&amp;skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&amp;sktid=a48cca56-e6da-484e-a814-9c849652bcb3&amp;skt=2023-01-22T17%3A19%3A13Z&amp;ske=2023-01-23T17%3A19%3A13Z&amp;sks=b&amp;skv=2021-08-06&amp;sig=vQrKcGSKmxXKDikYpx9xvmHeBRcdQoxRH%2B8%2BjYogjz8%3D', 'https://oaidalleapiprodscus.blob.core.windows.net/private/org-eO72e4aFm9XJBw4sb91Z8XEX/user-9ZRwLxYMDBxvw6gLEywP44xa/img-YnicWoD32S1DBBYzyhMnEHjo.png?st=2023-01-22T19%3A03%3A51Z&amp;se=2023-01-22T21%3A03%3A51Z&amp;sp=r&amp;sv=2021-08-06&amp;sr=b&amp;rscd=inline&amp;rsct=image/png&amp;skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&amp;sktid=a48cca56-e6da-484e-a814-9c849652bcb3&amp;skt=2023-01-22T17%3A19%3A13Z&amp;ske=2023-01-23T17%3A19%3A13Z&amp;sks=b&amp;skv=2021-08-06&amp;sig=o2kK5GIKX7lIqUaFQs8e1Sa3JWRyEZr6cVfKYPAjH%2BY%3D']</pre></div>



<h3 class="wp-block-heading">Step #5 Process the Image Response from DALL-E</h3>



<p class="wp-block-paragraph">Now that we have the image URLs, let&#8217;s see what DALL-E has generated. We use the Matplotlib library to display the generated images. Then we define a save path for the images using the timestamp and the details of the prompt. As the following code iterates over the URLs of the images, it stores the images with a unique filename for each image and saves them in the created directory. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># display the images
fig, axs = plt.subplots(nrows=1, ncols=len(image_list), figsize=(10, 10))
for i, imgurl in enumerate(image_list):
    ax = axs[i]
    img = mpimg.imread(imgurl)
    imgplot = ax.imshow(img)
    ax.set_xticks([]); ax.set_yticks([])
# define and create the save path
save_path = f&quot;dall-e_images/{datetime_string}_{prompt_details.replace(' ', '-')}&quot;
os.makedirs(save_path)
print(f&quot;images stored under the following path: {save_path}&quot;)
# store the images
for i, imgurl in enumerate(image_list):
    # set the file name
    filename = f&quot;{datetime_string}_dall-e{i}.png&quot;
    # save the image
    img = mpimg.imread(imgurl)
    mpimg.imsave(f'{save_path}/{filename}', img)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">images stored under the following path: dall-e_images/20230122210351_sugar-castle</pre></div>



<figure class="wp-block-image size-full"><img decoding="async" width="575" height="271" data-attachment-id="12149" data-permalink="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/image-9-3/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/image-9.png" data-orig-size="575,271" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-9" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/image-9.png" src="https://www.relataly.com/wp-content/uploads/2023/01/image-9.png" alt="Automatically generated AI-art using dall-e and openai chatgpt via Python APIs." class="wp-image-12149" srcset="https://www.relataly.com/wp-content/uploads/2023/01/image-9.png 575w, https://www.relataly.com/wp-content/uploads/2023/01/image-9.png 300w" sizes="(max-width: 575px) 100vw, 575px" /></figure>



<p class="wp-block-paragraph">Wow, what a beautiful sugar castle! That&#8217;s it, now the images are stored on your local computer, and you can process them further. </p>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">Generating DALL-E prompts using ChatGPT in Python is a powerful and flexible way to create unique images from text prompts. By following the steps outlined in this tutorial, you can use the OpenAI library and GPT-3.5 model to create AI-generated images for various topics. This process can be repeated with different prompts to generate a wide variety of images. </p>



<p class="wp-block-paragraph">You can now experiment with the latest advancements in natural language processing and image generation to create your own unique and captivating images.</p>



<p class="wp-block-paragraph">I hope this article has provided a useful introduction to working with OpenAI’s language models in Python and that you will continue to explore the full range of capabilities offered by the API.</p>



<p class="wp-block-paragraph">If you have any questions, let me know in the comments.</p>



<h2 class="wp-block-heading">Sources and Further Readings</h2>



<ul class="wp-block-list">
<li><a href="https://chat.openai.com/chat" target="_blank" rel="noreferrer noopener">OpenAI Chat</a></li>



<li><a href="https://beta.openai.com/docs/guides/fine-tuning/advanced-usage" target="_blank" rel="noreferrer noopener">OpenAI Guides</a></li>



<li><a href="https://beta.openai.com/docs/api-reference/models?lang=python">OpenAI API Reference</a></li>



<li><a href="https://beta.openai.com/docs/guides/images" target="_blank" rel="noreferrer noopener">Dall-E API Reference</a></li>



<li><a href="https://techcrunch.com/tag/openai/" target="_blank" rel="noreferrer noopener">TechCrunch OpenAI News</a></li>



<li><a href="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/" target="_blank" rel="noreferrer noopener">Using OpenAI language models via APIs in Python</a></li>



<li><a href="https://www.relataly.com/openai-gpt-3-5-chatgpt-in-a-business-context-whats-the-value-proposition/12282/" target="_blank" rel="noreferrer noopener">Relataly.com &#8211; Whats the Business Value of GPT-3?</a> </li>



<li><a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/" target="_blank" rel="noreferrer noopener">Relataly.com Business Use Cases for OpenAI GPT-3</a></li>



<li><a href="https://aituts.com/dall-e-2/" target="_blank" rel="noreferrer noopener">DALL·E 2: The Ultimate Guide</a></li>



<li>OpenAI ChatGPT was used to revise this article</li>



<li>Images generated using Dall-E and Midjourney AI for Image Generation from Text</li>
</ul>
<p>The post <a href="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/">Generating Detailed Images with OpenAI DALL-E and ChatGPT in Python: A Step-By-Step API Tutorial</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">12143</post-id>	</item>
		<item>
		<title>Unleashing the Power of ChatGPT and Other OpenAI GPT Language Models in Python A Guide to Using APIs</title>
		<link>https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/</link>
					<comments>https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Thu, 19 Jan 2023 22:52:24 +0000</pubDate>
				<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[REST APIs]]></category>
		<category><![CDATA[API Tutorials]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<category><![CDATA[ChatGPT]]></category>
		<category><![CDATA[Deep Learning]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=12068</guid>

					<description><![CDATA[<p>ChatGPT, developed by San Francisco-based OpenAI, is a revolutionary AI chatbot that uses artificial intelligence to generate coherent responses to user inquiries. Unlike traditional search engines, ChatGPT uses artificial intelligence to generate coherent responses to user inquiries rather than providing standard answers. The results are surprisingly good and have created a massive worldwide sensation. Many ... <a title="Unleashing the Power of ChatGPT and Other OpenAI GPT Language Models in Python A Guide to Using APIs" class="read-more" href="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/" aria-label="Read more about Unleashing the Power of ChatGPT and Other OpenAI GPT Language Models in Python A Guide to Using APIs">Read more</a></p>
<p>The post <a href="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/">Unleashing the Power of ChatGPT and Other OpenAI GPT Language Models in Python A Guide to Using APIs</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">ChatGPT, developed by San Francisco-based OpenAI, is a revolutionary AI chatbot that uses artificial intelligence to generate coherent responses to user inquiries. Unlike traditional search engines, ChatGPT uses artificial intelligence to generate coherent responses to user inquiries rather than providing standard answers. The results are surprisingly good and have created a massive worldwide sensation. Many think ChatGPT will drastically increase work productivity and revolutionize various industries in the coming years. While this may be true, the applications and integrations for large language models such as ChatGPT are yet to be built. By using the OpenAI API, you can integrate language models into your automated workflows and applications and potentially gain an edge over your competition. This article shows how this works with Python. We send requests to the OpenAI API and process the response.</p>



<p class="wp-block-paragraph">If you want to know how ChatGPT was trained, <a href="https://arxiv.org/abs/2005.14165" target="_blank" rel="noreferrer noopener">this article on &#8220;few-shot learning&#8221; by OpenAI researchers</a> provides a good overview.</p>



<p class="wp-block-paragraph">Also: <a href="https://www.relataly.com/mastering-prompt-engineering-for-chatgpt-a-practical-guide-for-businesses/13134/" target="_blank" rel="noreferrer noopener">Mastering Prompt Engineering for ChatGPT for Business Use</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">What can you do with OpenAI Language Models such as ChatGPT?</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">Enough with the hype around ChatGPT; what can these models actually do for us? Well, it turns out OpenAI&#8217;s language models can be used for a wide range of helpful stuff. And with &#8220;stuff,&#8221; I mean natural language processing (NLP) tasks, such as:</p>



<ul class="wp-block-list">
<li>Text generation: The models can generate new text that is coherent, human-like, and creative, depending on the model.</li>



<li>Language Translation: The models can accurately translate text from one language to another.</li>



<li>Question answering: The models can answer questions based on a given context.</li>



<li>Text summarization: The models can generate a summary of a given text.</li>



<li>Text completion: The models can complete sentences and paragraphs in a given context.</li>



<li>Language Modeling: The models can predict the next word in a sentence or generate a full text given a prompt.</li>



<li><a href="https://www.relataly.com/simple-sentiment-analysis-using-naive-bayes-and-logistic-regression/2007/" target="_blank" rel="noreferrer noopener">Sentiment Analysis</a>: The models can analyze the sentiment of a given text, whether it is positive, negative, or neutral.</li>



<li>Text classification: The models can classify text into different categories.</li>



<li>Text generation for creative content such as poetry, music, stories, and more.</li>



<li>Code generation: The models can generate code snippets.</li>
</ul>



<p class="wp-block-paragraph">These are just a few examples of the capabilities of OpenAI&#8217;s language models. It&#8217;s essential to keep in mind that the specific capabilities of each model will depend on the model you are using and the fine-tuning. In addition, the models can be fine-tuned for specific tasks, which is beyond the scope of this article.</p>



<p class="wp-block-paragraph"><a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/" target="_blank" rel="noreferrer noopener">This article</a> provides more guidance and inspiration on industry use cases of OpenAI GPT-3.</p>



<h2 class="wp-block-heading">Example of How to Generate Dall-e Prompts Using ChatGPT</h2>



<p class="wp-block-paragraph">The following examples show that ChatGPT can even generate helpful prompts for image creation services such as Dall-e. </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="1024" data-attachment-id="12349" data-permalink="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/humanoid_ai_with_a_neural_network_brain_in_profile/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/02/Humanoid_ai_with_a_neural_network_brain_in_profile.png" data-orig-size="1024,1024" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Humanoid_ai_with_a_neural_network_brain_in_profile" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/02/Humanoid_ai_with_a_neural_network_brain_in_profile.png" src="https://www.relataly.com/wp-content/uploads/2023/02/Humanoid_ai_with_a_neural_network_brain_in_profile-1024x1024.png" alt="Recently the internet world has been turned upside down by the release of ChatGPT - a revolutionary AI developed by San Francisco-based startup OpenAI. This article shows how to use the API in Python." class="wp-image-12349" srcset="https://www.relataly.com/wp-content/uploads/2023/02/Humanoid_ai_with_a_neural_network_brain_in_profile.png 1024w, https://www.relataly.com/wp-content/uploads/2023/02/Humanoid_ai_with_a_neural_network_brain_in_profile.png 300w, https://www.relataly.com/wp-content/uploads/2023/02/Humanoid_ai_with_a_neural_network_brain_in_profile.png 140w, https://www.relataly.com/wp-content/uploads/2023/02/Humanoid_ai_with_a_neural_network_brain_in_profile.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Recently the internet world has been turned upside down by the release of ChatGPT &#8211; a revolutionary AI developed by San Francisco-based startup OpenAI. This article shows how to use the API in Python. Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a></figcaption></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Request to ChatGPT: &quot;generate a prompt for dall-e that represents the capabilities of large language models such as chatgpt&quot;

Response from ChatGPT: &quot;Generate an image of a futuristic city with advanced technology, where people are seen interacting with AI-powered devices and transportation, while also showcasing the coexistence of nature and technology. The image should have a caption describing the scene in a coherent and creative manner.&quot;</pre></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="953" height="233" data-attachment-id="12083" data-permalink="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/screenshot-2023-01-19-151624-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/Screenshot-2023-01-19-151624-min.png" data-orig-size="953,233" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Screenshot-2023-01-19-151624-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/Screenshot-2023-01-19-151624-min.png" src="https://www.relataly.com/wp-content/uploads/2023/01/Screenshot-2023-01-19-151624-min.png" alt="" class="wp-image-12083" srcset="https://www.relataly.com/wp-content/uploads/2023/01/Screenshot-2023-01-19-151624-min.png 953w, https://www.relataly.com/wp-content/uploads/2023/01/Screenshot-2023-01-19-151624-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/Screenshot-2023-01-19-151624-min.png 768w" sizes="(max-width: 953px) 100vw, 953px" /><figcaption class="wp-element-caption">Images generated by OpenAI <a href="https://openai.com/dall-e-2/" target="_blank" rel="noreferrer noopener">Dall-e</a>, with a prompt generated by OpenAI ChatGPT.<br></figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Overview of the OpenAI Language Model Family: Ada, Babbage, Curie, Davinci</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">OpenAI offers four language <a href="https://beta.openai.com/docs/models" target="_blank" rel="noreferrer noopener">models </a>based on GPT3. Currently, the model family consists of Ada, Babbage, Curie, and Davinci. These models are solely for text generation and completion While the models can generate code, there are separate codex models that have been fine trained for <a href="https://beta.openai.com/docs/models/codex" target="_blank" rel="noreferrer noopener">code completion</a>.</p>



<p class="wp-block-paragraph">It is worth mentioning that ChatGPT and Davinci are not identical. However, ChatGPT and Davinci are using the same GPT version, 3.5. As a result, the two models tend to produce comparable results. </p>



<p class="wp-block-paragraph">The pros and cons of these models depend on the specific use case. However, here are some general advantages and disadvantages of OpenAI&#8217;s </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="925" height="761" data-attachment-id="12204" data-permalink="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/picture2-min-1/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/Picture2-min-1.png" data-orig-size="925,761" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Picture2-min-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/Picture2-min-1.png" src="https://www.relataly.com/wp-content/uploads/2023/01/Picture2-min-1.png" alt="Capabilities and response time of the OpenAI GPT3 models: ada, baggage, curie, davinci, chatgpt" class="wp-image-12204" srcset="https://www.relataly.com/wp-content/uploads/2023/01/Picture2-min-1.png 925w, https://www.relataly.com/wp-content/uploads/2023/01/Picture2-min-1.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/Picture2-min-1.png 768w" sizes="(max-width: 925px) 100vw, 925px" /><figcaption class="wp-element-caption">A rough overview of the capabilities and response times of the OpenAI GPT3 models: Ada, Baggage, Curie, Davinci and ChatGPT</figcaption></figure>
</div>
</div>



<figure class="wp-block-table is-style-regular has-medium-font-size"><table class="has-contrast-color has-base-2-background-color has-text-color has-background"><thead><tr><th>Model</th><th>Technical Name</th><th>Description</th></tr></thead><tbody><tr><td>Ada<br></td><td>text-ada-001</td><td>Ada is the fastest model. It performs well at tasks where creativity is more important than precision. It is suitable for applications such as chatbots, parsing text, simple classification, keywords, and address correction. Ada has the lowest costs.</td></tr><tr><td>Babbage<br></td><td>text-babbage-001</td><td>Babbage excels at identifying salient patterns in text and utilizing them as a reference to generate new text. Additionally, it can effectively perform general classification tasks, such as categorizing industries, genres, and media content. <br>However, Babbage is not as adept at creative tasks as other models. It can understand sufficient structure to generate simple plots and titles, but it may not be the best choice for more complex creative applications.</td></tr><tr><td>Curie<br></td><td>text-curie-001</td><td>Curie is capable of many nuanced tasks like sentiment classification and summarization. It reaches almost the level of Davinci but has lower costs. It is also good at answering questions, performing Q&amp;A, and as a general service chatbot.</td></tr><tr><td>Davinci<br></td><td>text-davinci-003</td><td>Davinci, in its current version 003, corresponds to ChatGPT (GPT3.5). It is a versatile model that can perform a wide range of tasks, often with fewer specific instructions. It excels in tasks that require a deep understanding of content, such as summary generation and creative writing. However, it requires more computational resources and may not be as fast or cost-effective as other models.</td></tr></tbody></table><figcaption class="wp-element-caption">Available language models via OpenAI, along with their respective pros and cons</figcaption></figure>



<div style="height:42px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Using GPT-3 Language Models via the OpenAI API in Python</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">The following Python tutorial demonstrates how you can leverage the OpenAI language models via an API. Will first select and configure our OpenAI language model. Then we will send a request to the model and handle the response. You can easily integrate models into your application or workflow using the API. For example, to generate content, handle user requests in natural language, or answer general questions. </p>



<p class="wp-block-paragraph">The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_6df625-e2"><a class="kb-button kt-button button kb-btn_97547b-eb kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials/blob/main/200%20Interacting%20with%20ChatGPT%20in%20Python.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_3eb33f-66 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<p class="wp-block-paragraph"></p>



<div style="height:25px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Register for an OpenAI API Key</h3>



<p class="wp-block-paragraph">To use the OpenAI API, you will first need to register for an API key by visiting the OpenAI website and creating an account. During the registration process, you will be required to provide some basic information about yourself and the project you are working on.</p>



<p class="wp-block-paragraph">It&#8217;s important to note that while GPT-3 is currently available in a free test version, the OpenAI API itself is not free. If you only plan to send a few test requests, the costs will be minimal, but if you integrate the API with a successful application that runs in production, the costs can quickly accumulate.</p>



<p class="wp-block-paragraph">However, it&#8217;s important to keep in mind that the use of the models may come with costs, and it&#8217;s crucial to monitor usage and keep track of costs to avoid unexpected charges. Each language model offered by OpenAI has a different price tag, and charges are based on the number of tokens sent to the model. To manage costs, you can set up a quota on the costs in the OpenAI portal under your profile. This will help you to keep an eye on the costs and keep them within your budget. </p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="12091" data-permalink="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/image-8-3/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/image-8.png" data-orig-size="1768,685" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-8" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/image-8.png" src="https://www.relataly.com/wp-content/uploads/2023/01/image-8-1024x397.png" alt="Prices of different language models offered by OpenAI, including davinci, ada baggage and curie. " class="wp-image-12091" width="887" height="344" srcset="https://www.relataly.com/wp-content/uploads/2023/01/image-8.png 1024w, https://www.relataly.com/wp-content/uploads/2023/01/image-8.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/image-8.png 768w, https://www.relataly.com/wp-content/uploads/2023/01/image-8.png 1536w, https://www.relataly.com/wp-content/uploads/2023/01/image-8.png 1768w" sizes="(max-width: 887px) 100vw, 887px" /><figcaption class="wp-element-caption">Overview of the prices for inferring the OpenAI language models.</figcaption></figure>



<p class="wp-block-paragraph"></p>



<h3 class="wp-block-heading">Technical Setup</h3>



<p class="wp-block-paragraph">Before diving into the code, it&#8217;s essential to ensure that you have the proper setup for your Python 3 environment and have installed all the necessary packages. If you do not have a Python environment, you can follow the instructions in <a href="https://www.relataly.com/anaconda-python-environment-machine-learning/1663/" target="_blank" rel="noreferrer noopener">this tutorial</a> to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda Python environment</a>. This will provide you with a robust and versatile environment that is well-suited for machine learning and data science tasks.</p>



<p class="wp-block-paragraph">In this tutorial, we will be working with the OpenAI library. You can install the OpenAI Python library using console commands:</p>



<ul class="wp-block-list">
<li><em>pip install </em>openai</li>



<li><em>conda install </em>openai&nbsp;(if you are using the anaconda packet manager)</li>
</ul>



<h3 class="wp-block-heading">Step #1 Imports and Model Configuration</h3>



<p class="wp-block-paragraph">We start by importing the necessary libraries and providing our API key for authorization. The API key can be stored in a separate file, such as api_config_openai.yml, and read into the code. Alternatively, you can also put the key directly in the code. However, be careful not to expose your key to the public.</p>



<p class="wp-block-paragraph">With the API key set up, we use the OpenAI API function &#8220;Model.list()&#8221; to retrieve a list of models available. Once you receive the response from the API, you should be able to loop through the list of available models and print the model IDs.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">import openai
import yaml

# set the API Key 
yaml_file = open('API Keys/api_config_openai.yml', 'r')  
p = yaml.load(yaml_file, Loader=yaml.FullLoader)
openai.api_key = p['api_key']

# show available models
modellist = openai.Model.list()
for i in modellist.data:
    print(i.id)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">babbage
ada
davinci
text-embedding-ada-002
babbage-code-search-code
text-similarity-babbage-001
text-davinci-001
curie-instruct-beta
babbage-code-search-text
babbage-similarity
curie-search-query
code-search-babbage-text-001
text-davinci-002
code-cushman-001
code-search-babbage-code-001
text-ada-001
code-davinci-002
text-similarity-ada-001
text-davinci-insert-002
ada-code-search-code
ada-similarity
code-search-ada-text-001
text-search-ada-query-001
text-curie-001
text-davinci-edit-001
...
text-ada:001
text-davinci:001
text-curie:001
text-babbage:001</pre></div>



<p class="wp-block-paragraph">We can see that OpenAI offers a variety of models, including older versions of the Davinci model (for example, version 001, which uses GPT1). You should always try to use the highest version available.</p>



<h3 class="wp-block-heading">Step #2 Sending a Request to the OpenAI API</h3>



<p class="wp-block-paragraph">Once you have your API key and have chosen a model, you can send a request to the API to access the model. We use the OpenAI library&#8217;s Completion.create() method to send a request to the OpenAI API. This function allows us to provide several parameters. </p>



<ul class="wp-block-list">
<li>engine: The model type, e.g., &#8220;text-davinci-003&#8221;</li>



<li>prompt: The message sent to the model, e.g., &#8220;create a poem about blockchain.&#8221;</li>



<li>max tokens: This parameter limits the number of tokens the model will create. </li>



<li>n: Defines how many completions to generate for each prompt.</li>



<li>stop parameter: This parameter allows us to define up to four sequences where the model will stop generating further tokens. The default is &#8220;None.&#8221;</li>



<li>temperature. This parameter allows us to adjust the creativity of the response. The default is 0.7. Higher values can lead to more creative answers but will also increase the risk the answers are not correct. </li>
</ul>



<p class="wp-block-paragraph">We encapsulate the &#8220;openai.Completion.create&#8221; function in a function called &#8220;send_openai_request.&#8221; This function only takes three parameters &#8220;engine,&#8221; &#8220;prompt,&#8221; and &#8220;max_tokens.&#8221; This way, we reduce the code needed to test different models and prompts</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Define the request
def send_openai_request(engine, prompt, max_tokens=1024):
    response = openai.Completion.create(
        engine=engine,
        prompt=prompt,
        max_tokens=max_tokens,
        n=1,
        stop=None,
        temperature=0.7
    )
    return response</pre></div>



<h3 class="wp-block-heading">Step #3 Send the Request</h3>



<p class="wp-block-paragraph">Next, we will send the request. We define the model to which we want to send the request and create an example prompt. Then we send the request to the API by calling the &#8220;send_openai_request function&#8221; created in the previous step. </p>



<p class="wp-block-paragraph">When the API has processed our request, it will return a JSON response that includes the output generated by the model. We will need to process this response to extract the information we need.</p>



<p class="wp-block-paragraph">Let&#8217;s make two requests using the same prompt, but with text-davinci-003 (GPT3.5, which corresponds to ChatGPT) and text-davinci-002 (GPT2). </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Define the prompt
prompt = &quot;What can you do with OpenAI?&quot;
model=&quot;text-davinci-002&quot;

# Generate a response
response = send_openai_request(model, prompt)

# Print the response
send_openai_request
print(response[&quot;choices&quot;][0][&quot;text&quot;])</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">OpenAI is a research lab focused on building advanced artificial intelligence.</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Define the prompt
prompt = &quot;What can you do with OpenAI?&quot;
model=&quot;text-davinci-003&quot;

# Generate a response
response = send_openai_request(model, prompt)

# Print the response
send_openai_request
print(response[&quot;choices&quot;][0][&quot;text&quot;])</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">OpenAI is a research and development organization dedicated to advancing artificial intelligence (AI) technologies. With OpenAI, you can use AI to develop a wide range of applications, including natural language processing (NLP), computer vision, robotics, reinforcement learning, and more. OpenAI also provides tools and resources for developers to create and train AI models, such as OpenAI Gym, a toolkit for reinforcement learning and OpenAI Five, a platform for training AI in StarCraft II. Additionally, OpenAI offers education and research opportunities for individuals interested in the field of AI.</pre></div>



<p class="wp-block-paragraph">As you see, the response from &#8220;text-davinci-003&#8221; is much more comprehensive than the response from &#8220;text-davinci-002.&#8221;</p>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p class="wp-block-paragraph">This article has provided an overview of how to use OpenAI&#8217;s language models via the API in Python. We have discussed the process of obtaining an API key, making requests to the API, and working with the returned data. We have also shown how to use the Davinci 003 model ( which corresponds to ChatGPT), to generate text and answer prompts. </p>



<p class="wp-block-paragraph">The possibilities of OpenAI&#8217;s language models are endless. Whether you&#8217;re a developer, researcher, or data scientist, the API provides a powerful tool for natural language processing tasks. Thanks to GPT-3.5 (ChatGPT) and other models, it has become easy to generate human-like text, answer questions, and perform other language-related tasks, with just a few lines of code. I am convinced that we will see a wave of exciting applications in the coming years &#8211; many use cases are yet to be invented.</p>



<p class="wp-block-paragraph">I hope this article has provided a useful introduction to working with OpenAI&#8217;s language models in Python and that you will continue to explore the full range of capabilities offered by the API.</p>



<p class="wp-block-paragraph">If you have any questions, let me know in the comments. And if you want to learn how to automate AI-art generation with DALL-E and ChatGPT, check out <a href="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/" target="_blank" rel="noreferrer noopener">this article.</a> </p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<ul class="wp-block-list">
<li><a href="https://chat.openai.com/chat" target="_blank" rel="noreferrer noopener">OpenAI Chat</a></li>



<li><a href="https://beta.openai.com/docs/guides/fine-tuning/advanced-usage" target="_blank" rel="noreferrer noopener">OpenAI Guides</a></li>



<li><a href="https://beta.openai.com/docs/api-reference/models?lang=python">OpenAI API Reference</a></li>



<li><a href="https://techcrunch.com/tag/openai/" target="_blank" rel="noreferrer noopener">TechCrunch OpenAI News</a></li>



<li><a href="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/" target="_blank" rel="noreferrer noopener">Learn how to Automate the Generation of Prompts for DALL-E using ChatGPT</a></li>



<li><a href="https://www.relataly.com/openai-gpt-3-5-chatgpt-in-a-business-context-whats-the-value-proposition/12282/" target="_blank" rel="noreferrer noopener">Relataly.com &#8211; Whats the Business Value of GPT-3?</a> </li>



<li><a href="https://www.relataly.com/business-use-cases-for-openai-gpt-models-chatgpt-davinci/12200/" target="_blank" rel="noreferrer noopener">Relataly.com Business Use Cases for OpenAI GPT-3</a></li>



<li>OpenAI ChatGPT was used to revise this article</li>
</ul>
<p>The post <a href="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/">Unleashing the Power of ChatGPT and Other OpenAI GPT Language Models in Python A Guide to Using APIs</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">12068</post-id>	</item>
		<item>
		<title>Using Pandas DataReader to Access Online Data Sources in Python</title>
		<link>https://www.relataly.com/using-pandas-datareader-in-python/10934/</link>
					<comments>https://www.relataly.com/using-pandas-datareader-in-python/10934/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Sat, 15 Oct 2022 20:14:00 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Sources]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Tech]]></category>
		<category><![CDATA[Yahoo Finance API]]></category>
		<category><![CDATA[API Tutorials]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<category><![CDATA[Requesting Data via REST APIs]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=10934</guid>

					<description><![CDATA[<p>Pandas DataReader is a library that allows data scientists to easily read data from a variety of sources into a Pandas DataFrame. This is especially useful for accessing data that resides outside of their local development environment and needs to be accessed via APIs. The Pandas DataReader provides functions for loading data from various online ... <a title="Using Pandas DataReader to Access Online Data Sources in Python" class="read-more" href="https://www.relataly.com/using-pandas-datareader-in-python/10934/" aria-label="Read more about Using Pandas DataReader to Access Online Data Sources in Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/using-pandas-datareader-in-python/10934/">Using Pandas DataReader to Access Online Data Sources in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">Pandas DataReader is a library that allows data scientists to easily read data from a variety of sources into a Pandas DataFrame. This is especially useful for accessing data that resides outside of their local development environment and needs to be accessed via APIs. The Pandas DataReader provides functions for loading data from various online sources, including Yahoo Finance and the NASDAQ. This can be incredibly helpful for tasks such as financial analysis, data visualization, and machine learning. In this tutorial, we will give a brief overview of the library and show how to use it in Python to access financial data from the Yahoo Finance API.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">What is Pandas Data Reader?</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">The Pandas DataReader library provides functions that extract data from various Internet sources into a pandas DataFrame. The pandas DataReader supports several remote data providers, including <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html#remote-data-alphavantage" target="_blank" rel="noreferrer noopener">Alpha Vantage</a>, <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html#remote-data-wb" target="_blank" rel="noreferrer noopener">World Bank</a>, <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html#eurostat" target="_blank" rel="noreferrer noopener">Eurostat</a>, the <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html#oecd" target="_blank" rel="noreferrer noopener">OECD, </a>and several stock markets such as the <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html#nasdaq-trader-symbol-definitions" target="_blank" rel="noreferrer noopener">NASDAQ</a>, <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html#remote-data-yahoo" target="_blank" rel="noreferrer noopener">Yahoo Finance</a>, and<a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html#remote-data-naver" target="_blank" rel="noreferrer noopener"> Naver Finance</a>. A complete list of available sources is available from the pandas DataReader <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html" target="_blank" rel="noreferrer noopener">API documentation</a>.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="252" data-attachment-id="11792" data-permalink="https://www.relataly.com/using-pandas-datareader-in-python/10934/image-10/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/image.png" data-orig-size="1246,307" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/image.png" src="https://www.relataly.com/wp-content/uploads/2023/01/image-1024x252.png" alt="Pandas datareader is a useful Python library for accessing remote data via an API" class="wp-image-11792" srcset="https://www.relataly.com/wp-content/uploads/2023/01/image.png 1024w, https://www.relataly.com/wp-content/uploads/2023/01/image.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/image.png 768w, https://www.relataly.com/wp-content/uploads/2023/01/image.png 1246w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Pandas DataReader is a useful Python library for accessing remote data via an API</figcaption></figure>
</div>
</div>



<p class="wp-block-paragraph"></p>



<div style="height:24px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading" id="h-access-financial-data-using-pandas-datareader-and-the-yahoo-finance-rest-api-in-python">Access Financial Data using Pandas DataReader and the Yahoo Finance REST API in Python</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">In this tutorial, we will learn how to use the pandas library to retrieve data for the German stock market index DAX from the Yahoo finance API. Specifically, we will use the pandas_datareader package, which provides a convenient interface for accessing various online data sources. We will carry out the following steps:</p>



<ol class="wp-block-list">
<li>Install the pandas_datareader package.</li>



<li>Import the necessary libraries in our Python script.</li>



<li>Use the data.DataReader function to request data for the DAX index from the Yahoo finance API. Specify the start and end dates for the data you want to retrieve. The returned data will be stored in a pandas DataFrame. </li>



<li>Finally, we use the plot() method from the matplotlib library to visualize the data.</li>
</ol>



<p class="wp-block-paragraph">The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_368b60-d7"><a class="kb-button kt-button button kb-btn_1809f5-70 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials/blob/main/101%20Pulling%20COVID-19%20Data%20via%20the%20Statworx%20API%20to%20a%20DataFrame.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_ad4d40-fa kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="11808" data-permalink="https://www.relataly.com/using-pandas-datareader-in-python/10934/image-2-4/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/image-2.png" data-orig-size="1442,1216" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-2" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/image-2.png" src="https://www.relataly.com/wp-content/uploads/2023/01/image-2-1024x864.png" alt="Pandas DataReader provides access to a wide range of public data sources. " class="wp-image-11808" width="382" height="323" srcset="https://www.relataly.com/wp-content/uploads/2023/01/image-2.png 1024w, https://www.relataly.com/wp-content/uploads/2023/01/image-2.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/image-2.png 768w, https://www.relataly.com/wp-content/uploads/2023/01/image-2.png 1442w" sizes="(max-width: 382px) 100vw, 382px" /><figcaption class="wp-element-caption">Pandas DataReader provides access to a wide range of public data sources.</figcaption></figure>
</div>
</div>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-prerequisites">Prerequisites</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">Before starting the coding part, ensure you have set up your <a href="https://www.python.org/downloads/" target="_blank" rel="noreferrer noopener">Python 3</a> environment and required libraries. If you don&#8217;t have an environment, consider following&nbsp;the steps in <a href="https://www.relataly.com/anaconda-python-environment-machine-learning/1663/" target="_blank" rel="noreferrer noopener">this tutorial</a>&nbsp;to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda environment</a>.</p>



<p class="wp-block-paragraph">Also, make sure you install all required packages. In this tutorial, we will be working with the following standard packages:&nbsp;</p>



<ul class="wp-block-list">
<li><em><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></em></li>



<li><em><a href="https://numpy.org/" target="_blank" rel="noreferrer noopener">NumPy</a></em></li>



<li><a href="https://docs.python.org/3/library/math.html" target="_blank" rel="noreferrer noopener">math</a></li>



<li><em><a href="https://matplotlib.org/" target="_blank" rel="noreferrer noopener">matplotlib</a></em></li>
</ul>



<p class="wp-block-paragraph">You can install packages using console commands:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">pip install &lt;package name&gt;
conda install &lt;package name&gt; (if you are using the anaconda packet manager)</pre></div>



<p class="wp-block-paragraph">In addition, we will be using the pandas DataReader library, which you can install with the following command:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;disableCopy&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">pip install pandas-datareader</pre></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div style="height:24px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-step-1-define-the-api-request-parameters">Step #1: Define the API Request Parameters</h3>



<p class="wp-block-paragraph">We begin by setting up imports and adjusting the request parameters. The parameters in an API request will depend on the API and the library used for making the request. Also, some parameters may be optional, while others are mandatory.</p>



<p class="wp-block-paragraph">The Yahoo Finance API allows us to limit the period we want to retrieve price data, an example of an optional parameter. Furthermore, we need to define the ticker symbol for the financial instrument if we wish to request the price data. This parameter is mandatory.</p>



<p class="wp-block-paragraph">The ticker symbol for the German stock market index is  <strong>^GDAXI</strong>. If you want to retrieve price data for other stocks or indices, you can search for the respective ticker symbols on <a href="https://de.finance.yahoo.com/quote/%5EGDAXI/?guccounter=1&amp;guce_referrer=aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8&amp;guce_referrer_sig=AQAAAJH4Onl0hOq1uOzUs7uiZWttbmU1Lw3XWqfXzhqMIUNypCiocw3d_hbUWI92G9TMZn3_M9q4RnaoNYjbWte3RM2iyGc1U_iPquEwan_ezsgKxiLDidFUB2R3zuF46IOvGIqueLikt8Znl-4yDCn_o_50qCUmCr3uZTJ8p8Eaf-MI" target="_blank" rel="noreferrer noopener">Yahoo finance</a>. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">import pandas_datareader as webreader
import pandas as pd
import matplotlib.pyplot as plt

# Set the API 
data_source = &quot;yahoo&quot;

# Set the API parameters
date_today = &quot;2020-01-01&quot; # period start date
date_start = &quot;2010-01-01&quot; # period end date
symbol = &quot;^GDAXI&quot; # asset symbol - For more symbols check yahoo.finance.com</pre></div>



<h3 class="wp-block-heading" id="h-step-2-send-the-request-to-the-rest-api-endpoint">Step #2: Send the Request to the REST API Endpoint</h3>



<p class="wp-block-paragraph">Once we have defined the request parameters, we can make the request via the DataReader function and print out the result. If you request a REST API, the response will come back in JSON format. However, DataReader will directly convert the API response into a DataFrame, which makes using APIs much simpler.</p>



<p class="wp-block-paragraph">This will retrieve the DAX stock market index from Yahoo Finance and print the first few rows of the resulting DataFrame. We have specified a date range to retrieve data for a specific period of time. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Send the request to the yahoo finance api endpoint
df = webreader.DataReader(symbol, start=date_start, end=date_today, data_source=data_source)
df.head(5)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">			High		Low			Open		Close		Volume		Adj Close
Date						
2010-01-04	6048.299805	5974.430176	5975.520020	6048.299805	104344400.0	6048.299805
2010-01-05	6058.020020	6015.669922	6043.939941	6031.859863	117572100.0	6031.859863
2010-01-06	6047.569824	5997.089844	6032.390137	6034.330078	108742400.0	6034.330078
2010-01-07	6037.569824	5961.250000	6016.799805	6019.359863	133704300.0	6019.359863
2010-01-08	6053.040039	5972.240234	6028.620117	6037.609863	126099000.0	6037.609863</pre></div>



<p class="wp-block-paragraph">Dataframe with the price data from yahoo finance.</p>



<h3 class="wp-block-heading" id="h-step-3-plot-the-data">Step #3 Plot the Data</h3>



<p class="wp-block-paragraph">Let&#8217;s quickly print the data to check if everything looks ok.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Plot the closing prices
fig, ax1 = plt.subplots(figsize=(12, 8))
plt.plot(df.index, df.Close)
plt.show()</pre></div>



<figure class="wp-block-image size-full"><img decoding="async" width="1003" height="659" data-attachment-id="10950" data-permalink="https://www.relataly.com/using-pandas-datareader-in-python/10934/image-38-3/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/12/image-38.png" data-orig-size="1003,659" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-38" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/12/image-38.png" src="https://www.relataly.com/wp-content/uploads/2022/12/image-38.png" alt="plot for financial data requested via the pandas datareader python library" class="wp-image-10950" srcset="https://www.relataly.com/wp-content/uploads/2022/12/image-38.png 1003w, https://www.relataly.com/wp-content/uploads/2022/12/image-38.png 300w, https://www.relataly.com/wp-content/uploads/2022/12/image-38.png 768w" sizes="(max-width: 1003px) 100vw, 1003px" /></figure>



<p class="wp-block-paragraph">Everything looks good, so let&#8217;s proceed.</p>



<h3 class="wp-block-heading" id="h-step-4-save-the-data-to-a-csv-file">Step #4: Save the Data to a CSV File</h3>



<p class="wp-block-paragraph">To save the data from a Pandas DataFrame to a CSV file, you can use the to_csv method. The to_csv method takes a few optional arguments that you can use to customize the output. For example, you can use the &#8220;sep&#8221; argument to specify a different delimiter to use in the CSV file or the &#8220;index&#8221; argument for including or excluding the DataFrame&#8217;s index in the output.</p>



<p class="wp-block-paragraph">Here&#8217;s an example of how you can use the to_csv method with the index parameter set to False:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Save the data to a CSV file
df.to_csv(&quot;price_quotes.csv&quot;, index=False)</pre></div>



<p class="wp-block-paragraph">Now you have the data on your local machine and can load it later. So unless you require more actual data, there is no need to call the API again.</p>



<figure class="wp-block-image size-full is-resized"><img decoding="async" data-attachment-id="11794" data-permalink="https://www.relataly.com/using-pandas-datareader-in-python/10934/image-1-4/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/image-1.png" data-orig-size="902,220" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/image-1.png" src="https://www.relataly.com/wp-content/uploads/2023/01/image-1.png" alt="price quotes csv file downloaded with Pandas DataReader library for Python" class="wp-image-11794" width="918" height="224" srcset="https://www.relataly.com/wp-content/uploads/2023/01/image-1.png 902w, https://www.relataly.com/wp-content/uploads/2023/01/image-1.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/image-1.png 768w" sizes="(max-width: 918px) 100vw, 918px" /></figure>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">This article has shown how to use the Pandas DataReader library. We learned how to use the library to request data from the Yahoo Finance API and save the data to a Pandas DataFrame. The Pandas DataReader library is a helpful tool for importing financial data into a Pandas DataFrame and working with it in Python. You can use it to retrieve data from a wide range of sources, including stock prices from major stock exchanges, economic data from the Federal Reserve, and cryptocurrency prices. Once you have the data in a DataFrame, you can use the various methods and functions provided by Pandas to analyze and manipulate the data, and save the results to a CSV file using the to_csv method.</p>



<p class="wp-block-paragraph">I hope this post was helpful. If you have any remarks or questions, let me know.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="504" height="502" data-attachment-id="12632" data-permalink="https://www.relataly.com/pandas-data-library-panda-midjourney-python-relataly-tutorial-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/pandas-data-library-panda-midjourney-python-relataly-tutorial-min.png" data-orig-size="504,502" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="pandas data library panda midjourney python relataly tutorial-min" data-image-description="&lt;p&gt;This panda just loaded a lot of data into his python project. &lt;/p&gt;
" data-image-caption="&lt;p&gt;This panda just loaded a lot of data into his python project. &lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/pandas-data-library-panda-midjourney-python-relataly-tutorial-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/pandas-data-library-panda-midjourney-python-relataly-tutorial-min.png" alt="This panda just loaded a lot of data into his python project. " class="wp-image-12632" srcset="https://www.relataly.com/wp-content/uploads/2023/03/pandas-data-library-panda-midjourney-python-relataly-tutorial-min.png 504w, https://www.relataly.com/wp-content/uploads/2023/03/pandas-data-library-panda-midjourney-python-relataly-tutorial-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/pandas-data-library-panda-midjourney-python-relataly-tutorial-min.png 140w" sizes="(max-width: 504px) 100vw, 504px" /><figcaption class="wp-element-caption">This panda looks happy because it just loaded data into his python project. Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a>.</figcaption></figure>
</div>
</div>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<p class="wp-block-paragraph"><a href="https://pandas-datareader.readthedocs.io/en/latest/index.html" target="_blank" rel="noreferrer noopener">pandas-datareader.readthedocs.io/</a></p>



<p class="wp-block-paragraph">Images created with Midjourney AI</p>



<h3 class="wp-block-heading">Further API Tutorials</h3>


<ul class="wp-block-kadence-posts kb-posts kadence-posts-list kb-posts-id-_69433d-4d content-wrap grid-cols kb-posts-style-boxed grid-sm-col-1 grid-lg-col-3 item-image-style-above"><li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-12143 post type-post status-publish format-standard has-post-thumbnail hentry category-language-generation category-machine-learning-marketing-automation category-natural-language-processing-nlp category-openai category-python-programming category-rest-apis tag-api-tutorials tag-beginner-tutorials tag-deep-learning">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-2-3" href="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/" aria-label="Generating Detailed Images with OpenAI DALL-E and ChatGPT in Python: A Step-By-Step API Tutorial">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="382" src="https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="OpenAI Dall-E ChatGPT Prompt Design Detailed Images Combining ChatGPT and Dall-E Midjourney" srcset="https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png 1530w, https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png 768w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="13511" data-permalink="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-copy-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png" data-orig-size="1530,762" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546 &amp;#8211; Copy-min" data-image-description="&lt;p&gt;OpenAI Dall-E ChatGPT Prompt Design Detailed Images Combining ChatGPT and Dall-E Midjourney&lt;/p&gt;
" data-image-caption="&lt;p&gt;OpenAI Dall-E ChatGPT Prompt Design Detailed Images Combining ChatGPT and Dall-E Midjourney&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/" rel="bookmark">Generating Detailed Images with OpenAI DALL-E and ChatGPT in Python: A Step-By-Step API Tutorial</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
<li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-12068 post type-post status-publish format-standard has-post-thumbnail hentry category-natural-language-processing-nlp category-openai category-rest-apis tag-api-tutorials tag-beginner-tutorials tag-chatgpt tag-deep-learning">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-2-3" href="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/" aria-label="Unleashing the Power of ChatGPT and Other OpenAI GPT Language Models in Python A Guide to Using APIs">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="300" src="https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="unleashing the power of openai super hero robot gpt python ai value proposition chatgpt" srcset="https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png 1614w, https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png 1536w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="13197" data-permalink="https://www.relataly.com/openai-gpt-chatgpt-in-a-business-context-whats-the-value-proposition/12282/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png" data-orig-size="1614,631" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="unleashing the power of openai super hero robot gpt python ai-min" data-image-description="&lt;p&gt;unleashing the power of openai super hero robot gpt python ai value proposition chatgpt&lt;/p&gt;
" data-image-caption="&lt;p&gt;unleashing the power of openai super hero robot gpt python ai value proposition chatgpt&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/" rel="bookmark">Unleashing the Power of ChatGPT and Other OpenAI GPT Language Models in Python A Guide to Using APIs</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
<li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-10351 post type-post status-publish format-standard has-post-thumbnail hentry category-cryptocompare-api category-facebook-prophet category-finance category-python-programming category-rest-apis category-seaborn category-stock-market-forecasting category-time-series-forecasting category-use-case category-yahoo-finance-api tag-ai-in-finance tag-intermediate-tutorials tag-supervised-learning">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-2-3" href="https://www.relataly.com/time-series-forecasting-using-facebook-prophet-in-python/10351/" aria-label="Univariate Stock Market Forecasting using Facebook Prophet in Python">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="307" src="https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="Univariate Stock Market Forecasting using Facebook Prophet in Python" srcset="https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png 1455w, https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png 768w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="13377" data-permalink="https://www.relataly.com/stock-market-forecasting-python-relataly-midjourney-3-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png" data-orig-size="1455,582" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="stock market forecasting python relataly midjourney 3-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/time-series-forecasting-using-facebook-prophet-in-python/10351/" rel="bookmark">Univariate Stock Market Forecasting using Facebook Prophet in Python</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
<li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-10098 post type-post status-publish format-standard has-post-thumbnail hentry category-blockchain-crypto-analytics category-correlation-machine-learning category-crypto-exchange-apis category-cryptocompare-api category-data-science category-finance category-python-programming category-rest-apis category-seaborn category-use-case tag-ai-in-finance tag-intermediate-tutorials">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-2-3" href="https://www.relataly.com/seven-metrics-for-on-chain-analysis-in-python/10098/" aria-label="On-Chain Analytics: Metrics for Analyzing Blockchains in Python">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="314" src="https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="onchain-analysis - tutorial blockchain data in python CryptoCompare api" srcset="https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png 1262w, https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png 1024w, https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png 768w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="12339" data-permalink="https://www.relataly.com/blockchain-analysis-python-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png" data-orig-size="1262,516" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="blockchain analysis python-min" data-image-description="&lt;p&gt;onchain-analysis &amp;#8211; tutorial blockchain data in python  CryptoCompare api&lt;/p&gt;
" data-image-caption="&lt;p&gt;onchain-analysis &amp;#8211; tutorial blockchain data in python  CryptoCompare api&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/seven-metrics-for-on-chain-analysis-in-python/10098/" rel="bookmark">On-Chain Analytics: Metrics for Analyzing Blockchains in Python</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
<li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-3982 post type-post status-publish format-standard has-post-thumbnail hentry category-finance category-gate-io-api category-python-programming category-rest-apis tag-ai-in-finance tag-api-tutorials tag-beginner-tutorials tag-bitcoin tag-cryptocurrencies">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-2-3" href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/" aria-label="Requesting Crypto Price Data from the Gate.io REST API in Python">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="305" src="https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="gatio cryptocurrency data api midjourney relataly-min" srcset="https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png 1358w, https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png 300w, https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png 512w, https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png 768w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="12769" data-permalink="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/gatio-cryptocurrency-data-api-midjourney-relataly-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png" data-orig-size="1358,540" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="gatio cryptocurrency data api midjourney relataly-min" data-image-description="&lt;p&gt;gatio cryptocurrency data api midjourney relataly-min&lt;/p&gt;
" data-image-caption="&lt;p&gt;gatio cryptocurrency data api midjourney relataly-min&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/" rel="bookmark">Requesting Crypto Price Data from the Gate.io REST API in Python</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
<li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-3925 post type-post status-publish format-standard has-post-thumbnail hentry category-rest-apis category-twitter-api tag-ai-in-e-commerce tag-api-tutorials tag-automated-twitter-posts tag-beginner-tutorials tag-social-media-data tag-tweepy">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-2-3" href="https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/" aria-label="Posting Tweets On Twitter using Python and Tweepy">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="306" src="https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="twitter api gate to social mediadata relataly tutorial python" srcset="https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png 1390w, https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png 768w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="12599" data-permalink="https://www.relataly.com/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png" data-orig-size="1390,554" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="twitter api gate to social mediadata relataly tutorial python" data-image-description="&lt;p&gt;twitter api gate to social mediadata relataly tutorial python&lt;/p&gt;
" data-image-caption="&lt;p&gt;twitter api gate to social mediadata relataly tutorial python&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/" rel="bookmark">Posting Tweets On Twitter using Python and Tweepy</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
</ul><p>The post <a href="https://www.relataly.com/using-pandas-datareader-in-python/10934/">Using Pandas DataReader to Access Online Data Sources in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/using-pandas-datareader-in-python/10934/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">10934</post-id>	</item>
		<item>
		<title>Automate Crypto Trading with a Python-Powered Twitter Bot and Gate.io Signals</title>
		<link>https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/</link>
					<comments>https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Wed, 19 May 2021 04:57:00 +0000</pubDate>
				<category><![CDATA[Algorithmic Trading]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[Gate.io API]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Stock Market Forecasting]]></category>
		<category><![CDATA[Time Series Forecasting]]></category>
		<category><![CDATA[Twitter API]]></category>
		<category><![CDATA[AI in E-Commerce]]></category>
		<category><![CDATA[API Tutorials]]></category>
		<category><![CDATA[Automated Twitter Posts]]></category>
		<category><![CDATA[Intermediate Tutorials]]></category>
		<category><![CDATA[Social Media Data]]></category>
		<category><![CDATA[Trading Signals]]></category>
		<category><![CDATA[Twitter Bots]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=3974</guid>

					<description><![CDATA[<p>This tutorial develops a Twitter bot in Python that will generate automated trading signals. The bot will pull real-time price data on various cryptocurrencies (Bitcoin, Ethereum, Doge, etc.) from the crypto exchange Gate.io and analyze it using predefined rules. Whenever the bot detects a relevant price change, it automatically posts a tweet via Twitter. Simple ... <a title="Automate Crypto Trading with a Python-Powered Twitter Bot and Gate.io Signals" class="read-more" href="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/" aria-label="Read more about Automate Crypto Trading with a Python-Powered Twitter Bot and Gate.io Signals">Read more</a></p>
<p>The post <a href="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/">Automate Crypto Trading with a Python-Powered Twitter Bot and Gate.io Signals</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">This tutorial develops a Twitter bot in Python that will generate automated trading signals. The bot will pull real-time price data on various cryptocurrencies (Bitcoin, Ethereum, Doge, etc.) from the <a href="http://www.gate.io/" target="_blank" rel="noreferrer noopener">crypto exchange</a> <em>Gate.io</em> and analyze it using predefined rules. Whenever the bot detects a relevant price change, it automatically posts a tweet via Twitter. Simple Twitter bots can proactively inform their audiences about relevant events in the market. Such an event can be a sharp rise or fall in price or a sudden spike in the trading volume. If we examine data for specific price movements, we can also store these events and use them later to train a predictive model.</p>



<p class="wp-block-paragraph">More advanced signal bots use predictive models to signal when it is appropriate to enter or exit the market. Or the bot executes the buy- and sell-orders directly itself. A well-defined signaling logic can therefore constitute the first step toward algorithmic trading. But one thing at a time. So in this article, we will begin by developing a simple signal bot.</p>



<p class="wp-block-paragraph">The rest of this article is structured as follows. First, we take a look at the different code modules of the Twitter bot. After that, we&#8217;ll implement the other code modules in Python. Finally, we will integrate the modules and run some tests. We will also quickly introduce the APIs used to build the bot.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full"><img decoding="async" width="748" height="506" data-attachment-id="12463" data-permalink="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/trading-bot-machine-learning-tutorial-gateio-trading-signals-python-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/02/trading-bot-machine-learning-tutorial-gateio-trading-signals-python-min.png" data-orig-size="748,506" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="trading-bot-machine-learning-tutorial-gateio-trading-signals-python-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/02/trading-bot-machine-learning-tutorial-gateio-trading-signals-python-min.png" src="https://www.relataly.com/wp-content/uploads/2023/02/trading-bot-machine-learning-tutorial-gateio-trading-signals-python-min.png" alt="trading bot machine learning tutorial gateio trading signals python. Midjourney. relataly.com" class="wp-image-12463" srcset="https://www.relataly.com/wp-content/uploads/2023/02/trading-bot-machine-learning-tutorial-gateio-trading-signals-python-min.png 748w, https://www.relataly.com/wp-content/uploads/2023/02/trading-bot-machine-learning-tutorial-gateio-trading-signals-python-min.png 300w" sizes="(max-width: 748px) 100vw, 748px" /><figcaption class="wp-element-caption">Bots can do a lot of cool things but should be used with caution. Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a></figcaption></figure>
</div>
</div>
</div>
</div>



<h2 class="wp-block-heading" id="h-different-modules-of-the-signal-bot">Different Modules of the Signal Bot </h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">This section briefly describes the conceptual architecture of the Crypto Twitter bot. Its architecture adheres to a modular design pattern and separates into four loosely coupled modules. Each module has a clear function.</p>



<ol class="wp-block-list">
<li>The <strong>Data Collection Module retrieves price data from the crypto exchange Gate.io. The module sends requests at </strong>regular intervals against the gate.io API. The module adds the data to separate data stores &#8211; one for each cryptocurrency. It then forwards the data to the preprocessing module.</li>



<li>The<strong> Data Preprocessing Module</strong> calculates the statistical indicators, such as moving averages or means, which become the basis for the signaling logic.</li>



<li>The <strong>Signaling Module </strong>searches for relevant events based on the indicator values provided. If a relevant event is detected, it is reported to the communication module.</li>



<li>The <strong>Communication Module</strong> connects to the Twitter API. As soon as it is informed about a new event, it tweets about this event on Twitter.</li>
</ol>



<p class="wp-block-paragraph">Now that you are familiar with the modules of our Crypto Twitter Bot, we can take a look at its underlying APIs.</p>



<figure class="wp-block-image size-large is-resized is-style-default"><img decoding="async" data-attachment-id="6092" data-permalink="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/image-124/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/03/image.png" data-orig-size="1342,865" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/03/image.png" src="https://www.relataly.com/wp-content/uploads/2022/03/image-1024x660.png" alt="" class="wp-image-6092" width="611" height="394" srcset="https://www.relataly.com/wp-content/uploads/2022/03/image.png 1024w, https://www.relataly.com/wp-content/uploads/2022/03/image.png 300w, https://www.relataly.com/wp-content/uploads/2022/03/image.png 768w, https://www.relataly.com/wp-content/uploads/2022/03/image.png 1342w" sizes="(max-width: 611px) 100vw, 611px" /><figcaption class="wp-element-caption">Components of the Relataly Crypto Signal Bot</figcaption></figure>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading" id="h-about-the-apis-used-in-this-tutorial">About the APIs Used in this Tutorial</h2>



<p class="wp-block-paragraph">In this tutorial, we will be using two APIs: </p>



<ul class="wp-block-list">
<li>The Gate.io API to fetch price data.</li>



<li>Twitter to post Tweets about Trading Signals</li>
</ul>



<h3 class="wp-block-heading" id="h-the-gate-io-api">The Gate.io API</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">Firstly, we will be using the Gate.io API to obtain prices for various cryptocurrencies. Gate.io is one of the smaller crypto exchanges in the crypto-verse. However, it offers a wide range of smaller cryptocurrencies, especially those you cannot trade anywhere else. As of now, the gate.io market endpoint does not require authentication to use its essential functions.</p>



<p class="wp-block-paragraph">Check out our <a href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/" target="_blank" rel="noreferrer noopener">recent relataly gate.io tutorial</a> to learn how to pull data via the gate.io API in Python.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h3 class="wp-block-heading" id="h-the-twitter-api">The Twitter API</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">The second API that our bot will use is the Twitter API. We will use this API via the Python package Tweepy to post crypto price signals. Check out this article if you are looking for a simple code example of submitting tweets via the Twitter API. If you don&#8217;t want to use Twitter, you can disable its use in the code.</p>



<p class="wp-block-paragraph">Posting tweets via the API requires authentication with a valid developer account. You can apply for a developer account for free on the Twitter <a href="https://developer.twitter.com/en/apply-for-access" target="_blank" rel="noreferrer noopener">developer website</a>. Just be aware that the confirmation can sometimes take several days. </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h3 class="wp-block-heading" id="storing-the-api-key">Storing the Twitter API Key</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">Storing API keys in your code can compromise the security of your application. If the code is made public, for example, by publishing it on a code-sharing website like GitHub, anyone who has access to the code can use the API key to make requests to the API and potentially access sensitive information or cause harm to your account or application. A better practice is to import and access the API key from a separate YAML file, from where you can import it into your project. To store the Twitter API Key, create a YAML file with the name “api_config_twitter.yml” and insert your API key into this file as follows:</p>



<p class="wp-block-paragraph">api_<em>key: “your api key”</em></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading" id="h-implementing-a-twitter-signal-bot-using-python">Implementing a Twitter Signal Bot using Python</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">In this article, we will walk through the process of creating a Twitter bot that automatically tweets updates about cryptocurrency prices. The bot will be designed to pull real-time data on cryptocurrency prices from an external API, and then automatically generate and post tweets on a regular basis. By the end of the article, you will have a fully functional Twitter bot that can keep your followers informed about the latest cryptocurrency prices.</p>



<p class="wp-block-paragraph">Note: You require a Twitter developer account if you want to use the Twitter functionality. Without an account, you can still print out trading signals to yourself, but you will not be able to post them via the Twitter API. </p>



<p class="wp-block-paragraph">The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_41cd8e-1f"><a class="kb-button kt-button button kb-btn_290c88-96 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials/blob/master/08%20Natural%20Language%20Processing/025%20Bots%20-%20Building%20a%20Twitter%20Bot%20with%20Python.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_de3f80-09 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<p class="has-accent-color has-blush-light-purple-gradient-background has-text-color has-background wp-block-paragraph"><strong>Disclaimer</strong>: This article does not constitute financial advice. Stock markets can be very volatile and are generally difficult to predict. Predictive models and other forms of analytics applied in this article only illustrate machine learning use cases.</p>
</div>
</div>



<h3 class="wp-block-heading" id="h-python-prerequisites">Python Prerequisites</h3>



<p class="wp-block-paragraph">Before starting the coding part, make sure that you have set up your Python 3 environment and required packages. If you don&#8217;t have an environment set up yet, you can follow&nbsp;this tutorial&nbsp;to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda environment</a>.</p>



<p class="wp-block-paragraph">Also, make sure you install all required packages. In this tutorial, we will be working with the following standard packages:&nbsp;</p>



<ul class="wp-block-list">
<li><em><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></em></li>



<li><em><a href="https://numpy.org/" target="_blank" rel="noreferrer noopener">NumPy</a></em></li>
</ul>



<p class="wp-block-paragraph">In addition, we will use the following two packages:</p>



<ul class="wp-block-list">
<li>Firstly, the gate.io package (<a href="https://github.com/gateio/gateapi-python" target="_blank" rel="noreferrer noopener">package name gate-API</a>) pulls crypto price data from gate.io.</li>



<li>Secondly, we will use the Twitter API library <a href="https://www.tweepy.org/" target="_blank" rel="noreferrer noopener">Tweepy</a> to post trading signals via the <a href="https://developer.twitter.com/en/docs/twitter-api" target="_blank" rel="noreferrer noopener">Twitter API</a>.</li>
</ul>



<p class="wp-block-paragraph">You can install packages using console commands:</p>



<ul class="wp-block-list">
<li><em>pip install &lt;package name&gt;</em></li>



<li><em>conda install &lt;package name&gt;</em>&nbsp;(if you are using the anaconda packet manager)</li>
</ul>



<h3 class="wp-block-heading" id="h-step-1-regular-retrieval-of-price-data">Step #1: Regular Retrieval of Price Data </h3>



<p class="wp-block-paragraph">First, we will define a &#8220;prices&#8221; class to handle the incoming data flow. The prices class contains a &#8220;get_latest_prices&#8221; attribute that retrieves price information from gate.io. The function regularly calls the gate.io list_ticker market endpoint.</p>



<p class="wp-block-paragraph">The list_ticker endpoint returns a list of data fields for cryptocurrency pairs. Examples of price pairs are BTC_USD, BTC_ETH, BTC_ADA, etc. We can limit the response to a single price pair by passing a single pair as a variable in the API call. However, it is not possible to restrict the response to multiple pairs. We either get data for a single pair or all pairs. The response contains a list of the following data fields:</p>



<figure class="wp-block-image is-resized"><img decoding="async" src="https://www.relataly.com/wp-content/uploads/2021/05/image-5-1024x581.png" alt="Response returned by the Gate.io API list_tickers operation" width="493" height="280"/><figcaption class="wp-element-caption">Overview of the data fields in the response</figcaption></figure>



<p class="wp-block-paragraph">The following code maintains a separate dictionary for each cryptocurrency pair. The dictionary contains the name of the cryptocurrency pair and a data frame that includes the price data history. Each time the crypto bot receives a new response from the API, it goes through the response, extracts the price data(Price, Volume, etc.), and appends this data to the Data Frame of the respective cryptocurrency pair. Then the information is passed to the preprocessing module.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">import pandas as pd
import numpy as np
import json
import requests
import datetime as dt
import logging
import threading
import time
from __future__ import print_function

import tweepy 
import gate_api
from gate_api.exceptions import ApiException, GateApiException
from twitter_secrets import twitter_secrets as ts # place the twitter_secrets file under &lt;User&gt;/anaconda3/Lib

class Prices:
    &quot;&quot;&quot;Class that uses the gate api to retrieve currency data.&quot;&quot;&quot;

    def __init__(self, config):
        self._config = config
        self._logger = logging.getLogger(__name__)
        configuration = gate_api.Configuration(host=&quot;https://api.gateio.ws/api/v4&quot;)
        api_client = gate_api.ApiClient(configuration)
        self._api_instance = gate_api.SpotApi(api_client)
        self._price_history = {}
        self._cont_update_thread = None
        self._stop_cont_update_thread = None
        self._price_history_lock = threading.Lock()

    def get_price_history(self):
        &quot;&quot;&quot;Returns a dictionary with the price histories for the currencies.&quot;&quot;&quot;
        return self._price_history, self._price_history_lock

    def get_latest_prices(self):
        &quot;&quot;&quot;Gets new price data and adds the values to a DataFrame.

        Returns the DataFrame in a dictionary with the currencies as keys.&quot;&quot;&quot;
        timestamp = dt.datetime.now()
        try:
            api_response = self._api_instance.list_tickers()
        except GateApiException as e:
            logging.warning(
                &quot;Gate api exception, label: %s, message: %s\n&quot; % (e.label, e.message)
            )
            return {}
        except ApiException as e:
            logging.warning(&quot;Exception when calling SpotApi-&gt;list_tickers: %s\n&quot; % e)
            return {}
        latest_prices = {}
        for response in api_response:
            currency = response.currency_pair
            if &quot;USDT&quot; not in currency or &quot;BEAR&quot; in currency:
                continue
            value_dict = {
                &quot;base_volume&quot;: pd.to_numeric(response.base_volume),
                &quot;change_percentage&quot;: pd.to_numeric(response.change_percentage),
                &quot;etf_leverage&quot;: pd.to_numeric(response.etf_leverage),
                &quot;etf_net_value&quot;: pd.to_numeric(response.etf_net_value),
                &quot;etf_pre_net_value&quot;: pd.to_numeric(response.etf_pre_net_value),
                &quot;etf_pre_timestamp&quot;: response.etf_pre_timestamp,
                &quot;high_24h&quot;: pd.to_numeric(response.high_24h),
                &quot;highest_bid&quot;: pd.to_numeric(response.highest_bid),
                &quot;high_bid&quot;: pd.to_numeric(response.highest_bid),
                &quot;last&quot;: pd.to_numeric(response.last),
                &quot;low_24h&quot;: pd.to_numeric(response.low_24h),
                &quot;lowest_ask&quot;: pd.to_numeric(response.lowest_ask),
                &quot;quote_volume&quot;: pd.to_numeric(response.quote_volume),
                &quot;timestamp&quot;: timestamp,
            }
            latest_prices[currency] = pd.DataFrame(value_dict, index=[1])
        return latest_prices

    def start_cont_update(self):
        self._stop_cont_update_thread = threading.Event()
        self._stop_cont_update_thread.clear()
        self._cont_update_thread = threading.Thread(
            target=self._cont_update,
            args=(
                self._stop_cont_update_thread,
                self._price_history_lock,
            ),
        )
        self._cont_update_thread.start()
        self._logger.info(&quot;Started continuous price logging&quot;)

    def _cont_update(self, stop_event, lock):
        &quot;&quot;&quot;Continuously adds new prices to the price history.&quot;&quot;&quot;
        while not stop_event.is_set():
            start_time = time.time()
            lock.acquire()
            for currency, df in self.get_latest_prices().items():
                if currency in self._price_history.keys():
                    self._price_history[currency] = self._price_history[
                        currency
                    ].append(df, ignore_index=True)
                else:
                    self._price_history[currency] = df
            lock.release()
            self._logger.debug(&quot;Currency_dfs updated&quot;)
            self._wait_before_update(start_time)

    def _wait_before_update(self, start_time):
        elapsed_time = time.time() - start_time
        self._logger.debug(f&quot;Elapsed time: {elapsed_time}&quot;)
        if elapsed_time &gt; self._config[&quot;price_update_delay&quot;]:
            delay = 0
            self._logger.warning(
                #&quot;It took longer to retrieve the price data than the update_delay!&quot;
            )
        else:
            delay = self._config[&quot;price_update_delay&quot;] - elapsed_time
        self._logger.debug(f&quot;Waiting {delay}s until next update&quot;)
        time.sleep(delay)
</pre></div>



<h3 class="wp-block-heading" id="h-step-2-calculate-indicator-values">Step #2: Calculate Indicator Values</h3>



<p class="wp-block-paragraph">Next, we will define a few functions that process the regular data inflow from gate.io and calculate indicator values for the different cryptocurrencies. </p>



<p class="wp-block-paragraph">Absolute price values signal the bot that the price moves up or down. However, our signaling logic will primarily work with thresholds on percentage values. These indicators have a p at the end of the name in the code below.</p>



<p class="wp-block-paragraph">In addition, we will avoid misleading signals by incorporating moving averages into the signaling logic. Moving averages work on historical data, so we have to hand over the price history when we call the &#8220;calc_indicators&#8221; function. Furthermore, we take over other indicators from the data frame, including the 24h_low and the 24h_high. These indicators give us additional information about the indicators of the preceding price points. We can use them to build more robust trading signals.</p>



<p class="wp-block-paragraph">All indicators are calculated separately for each crypto pair, passed to a dictionary, and then passed to the signaling logic. In the next step, we can use these indicator values in our signaling rules.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">def calc_indicators(price_history):
    indicators = {}
    indicators_over_all = calc_indicators_over_all(price_history)
    for currency, df in price_history.items():
        if len(df) &lt;= 2:
            logging.getLogger().debug(
                f&quot;Skipped '{currency} when calculating indicators due to a lack of information&quot;
            )
            continue
        volume = df[&quot;base_volume&quot;].iloc[-1]
        last_price = df[&quot;last&quot;].iloc[-1]
        moving_avg_price = df[&quot;last&quot;].mean()
        moving_average_volume = df[&quot;base_volume&quot;].mean()
        moving_average_deviation_percent = np.round(
            div(last_price, moving_avg_price) - 1, 2
        )

        price_before = df[&quot;last&quot;].iloc[-2]
        price_delta = last_price - price_before
        price_delta_p = div(price_delta, last_price)
        price_delta_before = price_before - df[&quot;last&quot;].iloc[-3]
        price_delta_p_before = div((price_before - df[&quot;last&quot;].iloc[-3]), price_before)
        low_24h = df[&quot;low_24h&quot;].iloc[-1]
        high_24h = df[&quot;high_24h&quot;].iloc[-1]
        low_high_diff_p = div(high_24h - low_24h, low_24h)
        change_percentage = df[&quot;change_percentage&quot;].iloc[-1]

        indicator_values = {
            &quot;last_price&quot;: last_price,
            &quot;price_before&quot;: price_before,
            &quot;volume&quot;: volume,
            &quot;moving_avg_price&quot;: moving_avg_price,
            &quot;moving_average_volume&quot;: moving_average_volume,
            &quot;moving_average_deviation_percent&quot;: moving_average_deviation_percent,
            &quot;price_delta_p&quot;: price_delta_p,
            &quot;price_delta&quot;: price_delta,
            &quot;price_delta_before&quot;: price_delta_before,
            &quot;price_delta_p_before&quot;: price_delta_p_before,
            &quot;high_24h&quot;: high_24h,
            &quot;low_24h&quot;: low_24h,
            &quot;low_high_diff_p&quot;: low_high_diff_p,
            &quot;change_percentage&quot;: change_percentage,
        }
        indicator_values.update(indicators_over_all)
        indicators[currency] = indicator_values
    return indicators


def calc_indicators_over_all(price_history):
    avg_change_p = 0
    for currency, df in price_history.items():
        avg_change_p += df[&quot;change_percentage&quot;].iloc[-1]
    nr_of_currencies = len(price_history)
    avg_change_p = div(avg_change_p, nr_of_currencies)
    values = {
        &quot;avg_change_p&quot;: avg_change_p,
    }
    return values


def div(dividend, divisor, alt_value=0.0):
    return dividend / divisor if divisor != 0 else alt_value</pre></div>



<h3 class="wp-block-heading" id="h-step-3-define-the-signaling-logic-of-the-twitter-bot">Step #3: Define the Signaling Logic of the Twitter Bot</h3>



<p class="wp-block-paragraph">Our bot will use a signaling logic that differentiates between the following price signals:</p>



<ul class="wp-block-list">
<li>A simple uptick: Price_delta_p must be higher than the threshold (10%) to trigger.</li>



<li>A simple downtick: Price_delta_p must be lower than the threshold (10%) to trigger.</li>



<li>The bot does also report on new 24-hour lows and highs</li>



<li>Another event on which the bot reports is when an up or down price trend begins to accelerate or slows down.</li>



<li>The bot reports that when a price performs a trend reversal (pullback and recovery)</li>
</ul>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="5034" data-permalink="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/image-71-2/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/06/image-71.png" data-orig-size="1168,639" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-71" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/06/image-71.png" src="https://www.relataly.com/wp-content/uploads/2021/06/image-71-1024x560.png" alt="Overview of the different trading signals generated by the signaling logic, twitter bot, algorithmic trading" class="wp-image-5034" width="755" height="413" srcset="https://www.relataly.com/wp-content/uploads/2021/06/image-71.png 1024w, https://www.relataly.com/wp-content/uploads/2021/06/image-71.png 300w, https://www.relataly.com/wp-content/uploads/2021/06/image-71.png 768w, https://www.relataly.com/wp-content/uploads/2021/06/image-71.png 1168w" sizes="(max-width: 755px) 100vw, 755px" /><figcaption class="wp-element-caption">Overview of the different trading signals generated by the signaling logic</figcaption></figure>



<p class="wp-block-paragraph">Be aware that the price_delta_p measures the percentage deviation from the previous price point. Thus, the signaling logic that our bot has in place is very dependent on the interval in which the bots request new price data. Shorter time intervals will have a lower chance of triggering because more considerable changes typically occur over a longer time. For more details regarding the signaling logic, please view the code below.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">def check_signal(currency, indicators, cs_config):
    ind = indicators[currency]
    signal = ''
    if (ind['moving_avg_price'] &gt; 0
            and ind['last_price'] &gt; 0.0
            and abs(ind['price_delta']) &gt; 0.0
            and abs(ind['price_delta_p']) &gt;= cs_config[&quot;delta_threshold_p&quot;]
            and ind['volume'] &gt; 0
    ):
        # up
        if ind['price_delta'] &gt; 0:
            movement_type = 'up +'
            if abs(ind['price_delta_p_before']) &gt; cs_config[&quot;delta_threshold_p&quot;]:
                if ind['price_delta_before'] &lt;= 0:
                    movement_type = 'recovery from ' + str(ind['price_before']) + ' to ' + str(ind['last_price'])
                else:
                    if ind['price_delta_p'] * (1-cs_config[&quot;delta_threshold_p&quot;]) &gt; ind['price_delta_p_before']:
                        movement_type = 'upward trend accelerates +'
                    elif ind['price_delta_p'] &lt; ind['price_delta_p_before'] * (1-cs_config[&quot;delta_threshold_p&quot;]):
                        movement_type = 'upward trend slows down +'
                    elif ind['price_delta_p'] * (1+cs_config[&quot;delta_threshold_p&quot;]) &gt;= ind['price_delta_p_before'] &gt;= ind['price_delta_p'] * (1-cs_config[&quot;delta_threshold_p&quot;]):
                        movement_type = 'upward trend continues +'
        # down
        elif ind['price_delta'] &lt; 0:
            movement_type = 'down '
            if abs(ind['price_delta_p_before']) &gt; cs_config[&quot;delta_threshold_p&quot;]:
                if ind['price_delta_before'] &gt; 0:
                    movement_type = 'pullback from ' + str(ind['price_before']) + ' to ' + str(ind['last_price'])
                else:
                    if ind['price_delta_p'] * (1-cs_config[&quot;delta_threshold_p&quot;]) &gt; ind['price_delta_p_before']:
                        movement_type = 'down trend accelerates '
                    elif ind['price_delta_p'] * (1+cs_config[&quot;delta_threshold_p&quot;]) &gt;= ind['price_delta_p_before'] &gt;= ind['price_delta_p'] * (1-cs_config[&quot;delta_threshold_p&quot;]):
                        movement_type = 'down trend continues '
                    elif ind['price_delta_p'] &lt; ind['price_delta_p_before'] * (1+cs_config[&quot;delta_threshold_p&quot;]):
                        movement_type = 'downward trend slows down '

        signal = get_signal_log(movement_type, currency, ind['price_delta_p'], ind['last_price'],
                                ind['moving_avg_price'], ind['volume'], ind['price_delta'], ind['change_percentage'],
                                ind['high_24h'], ind['low_24h'], ind['low_high_diff_p'])

        check_24h_peak(currency, ind['last_price'], ind['low_24h'], ind['high_24h'])

    return signal
    # trade_signal


def check_24h_peak(currency, last_price, low_24h, high_24h):
    if last_price &lt; low_24h:
        print(currency + ' new 24h low $' + str(last_price))
    elif last_price &gt; high_24h:
        print(currency + ' new 24h high $' + str(last_price))


def get_signal_log(movement_type, currency, price_delta_p, last_price, moving_avg_price, volume, price_delta,
                   daily_up_p, high_24h, low_24h, low_high_diff_p):
    signal = f'{currency} {movement_type} ' \
             f'{np.round(price_delta_p * 100, 5)}% ' \
             f'MA:${np.round(moving_avg_price, 6)} ' \
             f'last_price:${np.round(last_price, 6)} ' \
             f'price delta:{np.round(price_delta, 6)} ' \
             f'volume:${np.round(volume, 1)} ' \
             f'daily_change:{np.round(daily_up_p, 2)}% ' \
             f'high_24h:${high_24h} ' \
             f'low_24h:${low_24h} ' \
             f'low_high_diff_p:{np.round(low_high_diff_p * 100, 2)}%'
    return signal</pre></div>



<h3 class="wp-block-heading" id="h-step-4-send-tweets-via-twitter">Step #4: Send Tweets via Twitter</h3>



<p class="wp-block-paragraph">Next, we define a simple function that calls the Twitter API and tweets our price signal. Because the Twitter API requires authentication, you must provide the API authentication credentials from a valid Twitter developer account. </p>



<p class="wp-block-paragraph">It&#8217;s best not to store the API credentials directly in code. Still not perfect, but slightly better is to keep the data in a separate python file (for example, called &#8220;twitter_secrets&#8221;) that you put into your package folder (for example, under /anaconda3/Lib), from where you can import it directly into your code. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Twitter Consumer API keys
CONSUMER_KEY    = &quot;api123&quot;
CONSUMER_SECRET = &quot;api123&quot;

# Twitter Access token &amp; access token secret
ACCESS_TOKEN    = &quot;api123&quot;
ACCESS_SECRET   = &quot;api123&quot;

BEARER_TOKEN = &quot;api123&quot;

class TwitterSecrets:
    &quot;&quot;&quot;Class that holds Twitter Secrets&quot;&quot;&quot;

    def __init__(self):
        self.CONSUMER_KEY    = CONSUMER_KEY
        self.CONSUMER_SECRET = CONSUMER_SECRET
        self.ACCESS_TOKEN    = ACCESS_TOKEN
        self.ACCESS_SECRET   = ACCESS_SECRET
        self.BEARER_TOKEN   = BEARER_TOKEN
        
        # Tests if keys are present
        for key, secret in self.__dict__.items():
            assert secret != &quot;&quot;, f&quot;Please provide a valid secret for: {key}&quot;

twitter_secrets = TwitterSecrets()</pre></div>



<p class="wp-block-paragraph">Once you have imported the file, you can then load the API credentials from the file in the following way: </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">consumer_key = ts.CONSUMER_KEY
consumer_secret = ts.CONSUMER_SECRET
access_token = ts.ACCESS_TOKEN
access_secret = ts.ACCESS_SECRET

### Print API Auth Data (leave disabled for security reasons)
# print(f'consumer_key: {consumer_key}')
# print(f'consumer_secret: {consumer_secret}')
# print(f'access_token: {access_token}')
# print(f'access_secret: {access_token}')

#authenticating to access the twitter API
auth=tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_secret)
api=tweepy.API(auth)

def send_pricechange_tweet(signal):
    api.update_status(f&quot;{signal} \n {relataly_url}&quot;)</pre></div>



<h3 class="wp-block-heading" id="h-step-5-starting-the-crypto-signal-bot">Step #5 Starting the Crypto Signal Bot</h3>



<p class="wp-block-paragraph">Finally, we can hit the start button of our crypto signal bot. But before we do this, take a look at some configuration options of the bot.</p>



<ul class="wp-block-list">
<li>CYCLE_DELAY is the standard interval in seconds in which the bot will call the gate.io API. </li>



<li>CURRENCY_PAIR is another API parameter limiting the cryptocurrency pairs to specific currency pairs. The bot will scan the entire market with all currency pairs in the standard setting, including all USDT pairs.</li>



<li>TWITTER_ACTIVE defines whether the bot posts signals on Twitter. Be aware that your bot may instantly report any signal on your Twitter account if you enable it. </li>



<li>RUNS defines the max number of prices that the bot will retrieve before the bot stops. </li>
</ul>



<p class="wp-block-paragraph">Now, let&#8217;s test the bot:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">RUNS = 50 # the bot will stop after 50 price points
CYCLE_DELAY = 20 # the interval for checking the data and retrieving another price point
EVAL_PRICES_DELAY = 10
CURRENCY_PAIR = &quot;&quot; # the bot will retrieve data for all currency pairs listed on gate.io
PRICES_CONFIG = {&quot;price_update_delay&quot;: 20}
TWITTER_ACTIVE = False

CHECK_SIGNAL_CONFIG = {
    &quot;moving_avg_threshold_down_p&quot;: 0.10,
    &quot;moving_avg_threshold_up_p&quot;: 0.10,
    &quot;delta_threshold_p&quot;: 0.07,
    'enable_twitter': TWITTER_ACTIVE,
}

if __name__ == &quot;__main__&quot;:
    logging.basicConfig(
        level=logging.INFO, format=&quot;\033[02m%(asctime)s %(levelname)s: %(message)s&quot;
    )
    logger = logging.getLogger(__name__)
    prices = Prices(PRICES_CONFIG)
    prices.start_cont_update()
    currency_dfs = {}
    logging.info(f&quot;Crypto bot is starting - please wait&quot;)
    logger.info(f&quot;Collecting crypto data from gate.io for {EVAL_PRICES_DELAY}s&quot;)
    time.sleep(EVAL_PRICES_DELAY)
    logger.info(f&quot;\n&lt;&lt; Crypto signal bot started :-) &gt;&gt;&quot;)
    logger.info(f&quot;&lt;&lt; Checking prices every {CYCLE_DELAY} seconds &gt;&gt;&quot;)
    logger.info(f&quot;Now checking for signals - please wait\n&quot;)
    for i in range(RUNS):
        price_history, lock = prices.get_price_history()
        lock.acquire()
        indicators = calc_indicators(price_history)
        lock.release()
        for currency in indicators.keys():
            if not indicators[currency]:
                continue
            signal = check_signal(
                currency,
                indicators,
                CHECK_SIGNAL_CONFIG,
            )
            if signal:
                logger.info(signal)
                if CHECK_SIGNAL_CONFIG['enable_twitter']:
                    send_pricechange_tweet(signal)
                    print('send via twitter')
        time.sleep(CYCLE_DELAY)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">2022-03-09 11:40:38,939 INFO: Started continuous price logging
2022-03-09 11:40:38,940 INFO: Crypto bot is starting - please wait
2022-03-09 11:40:38,940 INFO: Collecting crypto data from gate.io for 10s
2022-03-09 11:40:48,941 INFO: 
&lt;&lt; Crypto signal bot started :-) &gt;&gt;
2022-03-09 11:40:48,942 INFO: &lt;&lt; Checking prices every 20 seconds &gt;&gt;
2022-03-09 11:40:48,942 INFO: Now checking for signals - please wait

2022-03-09 11:52:06,800 INFO: EOSBULL_USDT up + 19.42446% MA:$1.1e-05 last_price:$1.4e-05 price delta:3e-06 volume:$1272326905.1 daily_change:33.65% high_24h:$1.16e-05 low_24h:$9.8e-06low_high_diff_p:18.37%
EOSBULL_USDT new 24h high $1.39e-05
send via twitter</pre></div>



<p class="wp-block-paragraph"> And this is what the tweets will look like on Twitter:</p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="4060" data-permalink="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/image-11-10/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/05/image-11.png" data-orig-size="788,724" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-11" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/05/image-11.png" src="https://www.relataly.com/wp-content/uploads/2021/05/image-11.png" alt="output of our twitter bot, signalling logic, algorithmic trading, crypto price bot, gateio" class="wp-image-4060" width="512" height="470" srcset="https://www.relataly.com/wp-content/uploads/2021/05/image-11.png 788w, https://www.relataly.com/wp-content/uploads/2021/05/image-11.png 300w, https://www.relataly.com/wp-content/uploads/2021/05/image-11.png 768w" sizes="(max-width: 512px) 100vw, 512px" /></figure>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p class="wp-block-paragraph">Congratulations on completing this tutorial! In this article, you learned how to build a Python-based Twitter crypto signal bot. When run, the bot will regularly retrieve cryptocurrency quotes from the Gate.io exchange and tweet about any price movements based on a simple signaling logic.</p>



<p class="wp-block-paragraph">While the signaling logic in this tutorial is kept simple, this basic framework provides a foundation for you to further develop and enhance the signaling rules. For example, you could consider using volume or price volatility changes as the basis for defining signals. Have fun experimenting and expanding upon this project!</p>



<p class="wp-block-paragraph">If you found this article helpful, please show your appreciation by leaving a comment. Cheers</p>



<h2 class="wp-block-heading" id="h-sources-and-further-reading">Sources and Further Reading</h2>



<ol class="wp-block-list"><li><a href="https://amzn.to/3MyU6Tj" target="_blank" rel="noreferrer noopener">Charu C. Aggarwal (2018) Neural Networks and Deep Learning</a></li><li><a href="https://amzn.to/3yIQdWi" target="_blank" rel="noreferrer noopener">Jansen (2020) Machine Learning for Algorithmic Trading: Predictive models to extract signals from market and alternative data for systematic trading strategies with Python</a></li><li><a href="https://amzn.to/3S9Nfkl" target="_blank" rel="noreferrer noopener">Aurélien Géron (2019) Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems </a></li><li><a href="https://amzn.to/3EKidwE" target="_blank" rel="noreferrer noopener">David Forsyth (2019) Applied Machine Learning Springer</a></li><li><a href="https://amzn.to/3MAy8j5" target="_blank" rel="noreferrer noopener">Andriy Burkov (2020) Machine Learning Engineering</a></li></ol>



<p class="has-contrast-2-color has-base-3-background-color has-text-color has-background wp-block-paragraph"><em>The links above to Amazon are affiliate links. By buying through these links, you support the Relataly.com blog and help to cover the hosting costs. Using the links does not affect the price.</em></p>
<p>The post <a href="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/">Automate Crypto Trading with a Python-Powered Twitter Bot and Gate.io Signals</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3974</post-id>	</item>
		<item>
		<title>Requesting Crypto Price Data from the Gate.io REST API in Python</title>
		<link>https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/</link>
					<comments>https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Tue, 11 May 2021 09:17:14 +0000</pubDate>
				<category><![CDATA[Finance]]></category>
		<category><![CDATA[Gate.io API]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[REST APIs]]></category>
		<category><![CDATA[AI in Finance]]></category>
		<category><![CDATA[API Tutorials]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<category><![CDATA[Bitcoin]]></category>
		<category><![CDATA[Cryptocurrencies]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=3982</guid>

					<description><![CDATA[<p>In this tutorial, we will demonstrate how to use the Gate.io spot market API to stream cryptocurrency prices in real-time using Python. Streaming prices is crucial for implementing use cases such as analyzing an incoming stream of price data in real-time for generating trading signals or conducting price analytics. One of the benefits of using ... <a title="Requesting Crypto Price Data from the Gate.io REST API in Python" class="read-more" href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/" aria-label="Read more about Requesting Crypto Price Data from the Gate.io REST API in Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/">Requesting Crypto Price Data from the Gate.io REST API in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">In this tutorial, we will demonstrate how to use the Gate.io spot market API to stream cryptocurrency prices in real-time using Python. Streaming prices is crucial for implementing use cases such as analyzing an incoming stream of price data in real-time for generating trading signals or conducting price analytics. One of the benefits of using Gate.io for streaming prices is that it features many smaller cryptocurrencies that may not be available on larger exchanges like Coinbase or Binance. These smaller, more volatile cryptocurrencies can make for an interesting platform for price analysis and algorithmic trading. Despite being a smaller player in the cryptocurrency exchange market, ranking within the top 20, Gate.io offers a unique set of assets for traders to consider.</p>



<p class="wp-block-paragraph">In the following, we take a quick look at the Gate.io <a href="https://www.gate.io/docs/apiv4/en/index.html#gate-api-v4" target="_blank" rel="noreferrer noopener">API documentation</a>. Then we will write a short Python script that pulls price information in regular intervals. We store the price data for each cryptocurrency in a Pandas DataFrame, with which you can then continue to work on your projects. </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="7186" data-permalink="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/gate-io-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png" data-orig-size="1600,719" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="gate.io-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png" src="https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min-1024x460.png" alt="Crypto REST API Python Gate.io Tutorial" class="wp-image-7186" width="355" height="159" srcset="https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png 1024w, https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png 300w, https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png 768w, https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png 1536w, https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png 1600w" sizes="(max-width: 355px) 100vw, 355px" /><figcaption class="wp-element-caption">Gate.io API provides access to historical prices for a wide range of cryptocurrencies.</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading" id="h-about-the-gate-io-spotmarket-api">About the Gate.io Spotmarket API</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">Before we look at the market endpoint, it is crucial to understand that Gate.io offers multiple markets for different ways of trading cryptocurrencies. For example, there is a futures market, a spot market, and a margin market. Each of these markets has its HTTP REST API endpoint, which provides different operations. For example, there are operations for submitting buy and sell orders at the marketplace and retrieving price and order data. The <a href="https://www.gate.io/docs/apiv4/en/index.html#gate-api-v4" target="_blank" rel="noreferrer noopener">official API documentation</a> provides a complete list of these operations.</p>



<p class="wp-block-paragraph" id="h-gate-io-offers-several-apis">This tutorial will only work with the spot market API endpoint and the list_tickers operation. Unlike most other functions, the list_tickers operation does not require authentication. So, we don&#8217;t need to register as long we only want to retrieve price data. Another advantage is that there is no limit to API requests due to the lack of authentication.</p>



<p class="wp-block-paragraph">The list_ticker operation returns a list of data fields for cryptocurrency pairs. Examples of price pairs are BTC_USD, BTC_ETH, BTC_ADA, etc. If we limit the returned data to a specific price pair (e.g., BTC_USD), we can pass a single pair as a variable in the API call. However, it is not possible to restrict multiple pairs. So, we either retrieve data for a single pair or all pairs. For each request, the API returns a list with the following data fields:</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"><div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" data-attachment-id="3994" data-permalink="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/image-5-12/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/05/image-5.png" data-orig-size="1030,584" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-5" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/05/image-5.png" src="https://www.relataly.com/wp-content/uploads/2021/05/image-5-1024x581.png" alt="Crypto REST API Python Gate.io Tutorial: Response returned by the Gate.io API list_tickers operation" class="wp-image-3994" width="362" height="205" srcset="https://www.relataly.com/wp-content/uploads/2021/05/image-5.png 1024w, https://www.relataly.com/wp-content/uploads/2021/05/image-5.png 300w, https://www.relataly.com/wp-content/uploads/2021/05/image-5.png 768w, https://www.relataly.com/wp-content/uploads/2021/05/image-5.png 1030w" sizes="(max-width: 362px) 100vw, 362px" /><figcaption class="wp-element-caption">The response returned by the Gate.io API list_tickers operation</figcaption></figure>
</div></div>
</div>



<h2 class="wp-block-heading" id="h-implementation-retrieving-regular-price-ticker-data-from-gate-io-with-python">Implementation: Retrieving Regular Price Ticker Data from Gate.io with Python</h2>



<p class="wp-block-paragraph">Let&#8217;s start by implementing a short Python script that will periodically call the gate.io spot market endpoint and return a response. Each time we receive a response, we will process it. We will extract multiple price fields and append them as new records to a set of DataFrames. To do this, we use a separate DataFrame per crypto price pair. </p>



<p class="wp-block-paragraph">We use a separate DataFrame per price pair to ease working with the data later. An alternative would be to store all price data in a single DataFrame. However, we usually want to work with price data for specific price pairs and do Analytics on them. It is easier to have all the corresponding data in one place and not have to filter it beforehand.</p>



<p class="wp-block-paragraph">The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_ea7ba1-49"><a class="kb-button kt-button button kb-btn_79d52f-b1 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials/blob/main/126%20Getting%20Real-Time%20Price%20Data%20via%20the%20Gate.io%20API.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_a0bdc1-04 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>



<h3 class="wp-block-heading" id="h-prerequisites">Prerequisites</h3>



<p class="wp-block-paragraph">Also, make sure you install all required packages. In this tutorial, we will be working with the following standard packages:&nbsp;</p>



<ul class="wp-block-list">
<li><em><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></em></li>
</ul>



<p class="wp-block-paragraph">In addition, we will be using the gate.io package (<a href="https://github.com/gateio/gateapi-python" target="_blank" rel="noreferrer noopener">package name gate-API</a>) to pull price data from the crypto exchange gate.io.</p>



<p class="wp-block-paragraph">You can install packages using console commands:</p>



<ul class="wp-block-list">
<li><em>pip install &lt;package name&gt;</em></li>



<li><em>conda install &lt;package name&gt;</em>&nbsp;(if you are using the anaconda packet manager)</li>
</ul>



<h3 class="wp-block-heading" id="h-step-1-connect-to-the-gate-io-api">Step #1: Connect to the Gate.io API</h3>



<p class="wp-block-paragraph">First, we establish a connection to the API. We do this by creating a new api_client object and then using it as an argument to the spot API function. As a result, the gate_api library returns an api_instance that provides access to several API functions.  </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">import gate_api
from gate_api.exceptions import ApiException, GateApiException
import pandas as pd
import time
import datetime as dt

# Defining the host is optional and defaults to https://api.gateio.ws/api/v4
# See configuration.py for a list of all supported configuration parameters.
configuration = gate_api.Configuration(host = &quot;https://api.gateio.ws/api/v4&quot;)
api_client = gate_api.ApiClient(configuration)

# Create an instance of the API class
api_instance = gate_api.SpotApi(api_client)</pre></div>



<h3 class="wp-block-heading" id="h-step-2-define-functions-for-calling-the-api-and-handling-the-response">Step #2: Define Functions for Calling the API and Handling the Response</h3>



<p class="wp-block-paragraph">Next, we create two functions. The first function contains a loop that calls the gate.io spot market list_tickers API. Every time we contact this endpoint, it will return a list with price information. We handle this data in a dictionary that contains a separate DataFrame for each cryptocurrency price pair. Managing the data means iterating through the response and extracting the price data per cryptocurrency pair. Each price data is handed over to our second function, &#8220;append_data_to_df,&#8221; which stores the data in its respective DataFrame.</p>



<p class="wp-block-paragraph">The request_data function takes three arguments:</p>



<ul class="wp-block-list">
<li><strong>runs: </strong>this is how often we should call the API. </li>



<li>s: the interval in seconds in which we call the API</li>



<li>currency_pair: you can alternatively define a specific currency pair for which you want to retrieve price information. If none is specified, the API endpoint will return the complete list of all price pairs (currently ~ 270).</li>
</ul>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># this function starts calling the Gate.io API
# the response will contains price data for multiple cryptocurrencies
# the price information of each cryptocurrency will be stored in its own dataframe
def request_data(runs, currency_pair, s):
    currency_dfs = {}
    for t in range(runs):

        try:
            api_response = api_instance.list_tickers(currency_pair=currency_pair)
        except GateApiException as ex:
            print(&quot;Gate api exception, label: %s, message: %s\n&quot; % (ex.label, ex.message))
        except ApiException as e:
            print(&quot;Exception when calling SpotApi-&gt;list_tickers: %s\n&quot; % e)

        ts = dt.datetime.now()
        currency_response_dict = {resp.currency_pair: resp for resp in api_response
                                if &quot;USDT&quot; in resp.currency_pair and &quot;BEAR&quot; not in resp.currency_pair}
                  
        for currency_name, response in currency_response_dict.items():
            try:
                currency_dfs[currency_name]
            except KeyError:
                # Create new dataframe if currency does not have one yet
                currency_dfs[currency_name] = pd.DataFrame(columns=[
                    'Symbol', 
                    'Timestamp', 
                    'Volume', 
                    'Price', 
                    'Price_Delta', 
                    'Price_Delta_Percent'])
            
            # get the price of the currency at the last price point
            if len(currency_dfs[currency_name]) &gt; 1:
                #print(currency_dfs[currency_name])
                price_before = currency_dfs[currency_name]['Price'].iloc[-1]
            else:
                price_before = 0
            
            # append a new record the dataframe of this currency
            new_data_as_dict = append_data_to_df(price_before, response, ts)
            
            # add this dataframe to the list of currency_dataframe. there are separate dfs per currency.
            currency_dfs[currency_name] = currency_dfs[currency_name].append(new_data_as_dict, ignore_index=True)
                
        # wait s seconds until the next request
        time.sleep(s)
    return currency_dfs

# this function is called for each cryptocurrency and everytime the gate.io API returns price data
# the function extracts price information from a single API response and adds it to a dataframe 
# example: the API response contains data for 270 cryptocurrency price pairs -&gt; the function is called 270 time per API response
def append_data_to_df(price_before, data, ts):
    volume = data.base_volume
    price = pd.to_numeric(data.last)
    price_delta = price - price_before
    
    if price &gt; 0:
        price_delta_p = price_delta / price 
    else:
        price_delta_p = 0
    
    new_record = {
                  'Symbol': data.currency_pair, 
                  'Timestamp': ts, 
                  'Volume': volume, 
                  'Price': price,
                  'Price_Delta': price_delta,
                  'Price_Delta_Percent': price_delta_p
                 }
    return new_record</pre></div>



<h3 class="wp-block-heading" id="h-step-3-start-calling-the-gate-io-market-api">Step #3: Start Calling the Gate.io Market API</h3>



<p class="wp-block-paragraph">Once we have defined the functions to request and handle the price data, we can start calling the API. In the code below, we use a request interval of 10 seconds. We stop calling the API for test purposes stop after four runs. Afterward, we print the list of DataFrames to inspect the collected data.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">s = 10 # API request interval in seconds
currency_pair = '' # currency pair (optional)
runs = 4 # number of data points to fetch

df_list = request_data(runs, currency_pair, s)

df_list # list that contains one dataframe per currency</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Output exceeds the size limit. Open the full output data in a text editor
{'MKR3S_USDT':        Symbol                  Timestamp             Volume    Price  \
 0  MKR3S_USDT 2021-05-15 15:36:59.449017  240761.4473870418  0.03816   
 1  MKR3S_USDT 2021-05-15 15:37:13.762682  240830.5653870418  0.03820   
 2  MKR3S_USDT 2021-05-15 15:37:27.148195  240830.5653870418  0.03820   
 3  MKR3S_USDT 2021-05-15 15:37:40.406192  240830.5653870418  0.03820   
 
    Price_Delta  Price_Delta_Percent  
 0      0.03816                  1.0  
 1      0.03820                  1.0  
 2      0.00000                  0.0  
 3      0.00000                  0.0  ,
 'BANK_USDT':       Symbol                  Timestamp           Volume   Price  Price_Delta  \
 0  BANK_USDT 2021-05-15 15:36:59.449017  162.21144309298  719.97       719.97   
 1  BANK_USDT 2021-05-15 15:37:13.762682  162.21144309298  720.92       720.92   
 2  BANK_USDT 2021-05-15 15:37:27.148195  162.22547024346  720.92         0.00   
 3  BANK_USDT 2021-05-15 15:37:40.406192  162.22547024346  720.92         0.00   
 
    Price_Delta_Percent  
 0                  1.0  
 1                  1.0  
 2                  0.0  
 3                  0.0  ,
 'COOK_USDT':       Symbol                  Timestamp           Volume    Price  \
 0  COOK_USDT 2021-05-15 15:36:59.449017  5336969.0918761  0.05500   
 1  COOK_USDT 2021-05-15 15:37:13.762682  5338396.2698761  0.05517   
...
    Price_Delta_Percent  
 0                  1.0  
 1                  1.0  
 2                  0.0  
 3                  0.0  }</pre></div>



<p class="wp-block-paragraph">As shown above, we have created a list of DataFrames. It contains one DataFrame with price points per cryptocurrency price pair. You can now use these historical price data to conduct analytics or visualize price movements in real time. </p>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p class="wp-block-paragraph">This tutorial demonstrated how to query cryptocurrency price data via the Gate.io API. We have queried the API and stored historical crypto prices in a DataFrame. Now that you are familiar with the concepts of the Gate.io API, you can tackle exciting projects. For example, you could use the data to display price information on a website or create analytics applications. </p>



<p class="wp-block-paragraph">In another relataly tutorial, we trained a crypto trading bot that acts upon automated trading signals. If you are interested in developing trading bots, consider my recent <a href="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/" target="_blank" rel="noreferrer noopener">tutorials on Gate.io crypto trading bots</a>.</p>



<p class="wp-block-paragraph">Of course, Gate.io is not the only crypto API in the market. So if you are looking for an API for crypto market data, you might also consider the Coinmarketcap API. I have recently covered it in <a href="https://www.relataly.com/category/apis/coinmarketcap-api/" target="_blank" rel="noreferrer noopener">a separate coinmarket API tutorial</a>.</p>



<p class="wp-block-paragraph">I hope you liked this post. If you have questions, let me know in the comments.</p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<p class="wp-block-paragraph">If you are interested in stock-market Prediction, check out the following articles:</p>



<ul class="wp-block-list">
<li><a href="https://www.relataly.com/stock-market-prediction-using-multivariate-time-series-in-python/1815/" target="_blank" rel="noreferrer noopener">Stock Market Prediction using Multivariate Time Series and Recurrent Neural Networks in Python</a></li>



<li><a href="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/" target="_blank" rel="noreferrer noopener">Building a Twitter Bot for Crypto Trading Signals using Python and Gate.io</a></li>
</ul>



<p class="wp-block-paragraph"></p>
<p>The post <a href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/">Requesting Crypto Price Data from the Gate.io REST API in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3982</post-id>	</item>
		<item>
		<title>Posting Tweets On Twitter using Python and Tweepy</title>
		<link>https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/</link>
					<comments>https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Sun, 09 May 2021 15:14:45 +0000</pubDate>
				<category><![CDATA[REST APIs]]></category>
		<category><![CDATA[Twitter API]]></category>
		<category><![CDATA[AI in E-Commerce]]></category>
		<category><![CDATA[API Tutorials]]></category>
		<category><![CDATA[Automated Twitter Posts]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<category><![CDATA[Social Media Data]]></category>
		<category><![CDATA[Tweepy]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=3925</guid>

					<description><![CDATA[<p>In a previous article, we have shown how to retrieve social media data via the Twitter API in Python. However, we can do many more cool things with the Twitter API. Another cool thing is interacting with the Twitter user account and posting automated tweets. This article shows how this works. We will use the ... <a title="Posting Tweets On Twitter using Python and Tweepy" class="read-more" href="https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/" aria-label="Read more about Posting Tweets On Twitter using Python and Tweepy">Read more</a></p>
<p>The post <a href="https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/">Posting Tweets On Twitter using Python and Tweepy</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">In a previous article, we have shown how to <a href="https://www.relataly.com/accessing-twitter-data-via-the-twitter-rest-api/1976/" target="_blank" rel="noreferrer noopener">retrieve social media data via the Twitter API in Python</a>. However, we can do many more cool things with the Twitter API. Another cool thing is interacting with the Twitter user account and posting automated tweets. This article shows how this works. We will use the Twitter API and the Tweepy library to submit tweets to our Twitter account. </p>



<p class="wp-block-paragraph">A common use case for submitting tweets via the Twitter API is a <a href="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/" target="_blank" rel="noreferrer noopener">Twitter bot</a>. Today, many bots on Twitter send automated tweets, for example, about unusual movements in the stock market or other types of events. However, it is worth mentioning that bots are also used for evil purposes, for example, to lure people into scams or influence political opinions.</p>



<p class="wp-block-paragraph">This tutorial lays the foundation for building a simple Twitter bot with Python and Tweepy. The remainder of this article is structured as follows: We&#8217;ll begin by briefly looking at the tweet object on Twitter. Then, we will write some code that requests authentication via the Twitter API and submit some test tweets to the API.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow"></div>
</div>



<h2 class="wp-block-heading" id="h-the-tweet-object-of-the-twitter-api">The Tweet Object of the Twitter API</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p class="wp-block-paragraph">Tweets are the basic building blocks of Twitter. They have several customization options, such as media, hashtags, and emojis. We can use all of these options by specifying respective parameters in our requests to the Twitter API.</p>



<p class="wp-block-paragraph">First of all, a tweet contains up to 280 characters of text. The text can include hashtags or emojis, which also occupy space in terms of characters.</p>



<p class="wp-block-paragraph">While hashtags are indicated via the #-sign, emojis are displayed via standard Unicode. Most emojis occupy two characters of the maximum text length, but some may require more. Here you can find an overview of the emoji Unicode. </p>



<p class="wp-block-paragraph">Optionally, tweets can contain media objects such as images, GIFs, or Polls. We can attach these elements via a separate API function.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="294" data-attachment-id="3949" data-permalink="https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/image-2-14/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/05/image-2.png" data-orig-size="1493,428" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-2" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/05/image-2.png" src="https://www.relataly.com/wp-content/uploads/2021/05/image-2-1024x294.png" alt="Submitting a Twitter Tweet" class="wp-image-3949" srcset="https://www.relataly.com/wp-content/uploads/2021/05/image-2.png 1024w, https://www.relataly.com/wp-content/uploads/2021/05/image-2.png 300w, https://www.relataly.com/wp-content/uploads/2021/05/image-2.png 768w, https://www.relataly.com/wp-content/uploads/2021/05/image-2.png 1493w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Submitting a Twitter Tweet</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading" id="h-implementation-posting-tweets-via-the-twitter-api-in-python">Implementation: Posting Tweets via the Twitter API in Python </h2>



<p class="wp-block-paragraph">This tutorial shows how to write a short Python script that authenticates against Twitter. Then we will submit some test Tweets using your Twitter account. We will look at two different cases:</p>



<ul class="wp-block-list">
<li>Submitting a simple text-only tweet </li>



<li>Submitting a tweet that contains text and a media file</li>
</ul>



<p class="wp-block-paragraph">The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_c22607-1b"><a class="kb-button kt-button button kb-btn_c436b2-88 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials/blob/main/111%20Posting%20Tweets%20via%20the%20Twitter%20API%20v2.0.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_c55bfd-d7 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-true wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>



<h3 class="wp-block-heading" id="h-prerequisites">Prerequisites</h3>



<p class="wp-block-paragraph">Using the Twitter API requires a Twitter <a href="https://developer.twitter.com/en" target="_blank" rel="noreferrer noopener">developer account</a>. If you don&#8217;t have one yet, you can follow the steps described in <a href="https://www.relataly.com/wp-admin/post.php?post=1976&amp;action=edit" target="_blank" rel="noreferrer noopener">this tutorial</a> to create an account for free.</p>



<p class="wp-block-paragraph">Before starting the coding part, make sure that you have set up your Python 3 environment and required packages. If you don&#8217;t have an environment set up yet, you can follow&nbsp;this tutorial&nbsp;to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda environment</a>.</p>



<p class="wp-block-paragraph">Also, make sure you install all required packages. In this article, we will be working with the following standard packages:&nbsp;</p>



<ul class="wp-block-list">
<li><em><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></em></li>
</ul>



<p class="wp-block-paragraph">In addition, we will be using <a href="https://www.tweepy.org/" target="_blank" rel="noreferrer noopener">Tweepy</a>. Tweepy is an easy-to-use Python library for accessing the Twitter API.</p>



<p class="wp-block-paragraph">You can install packages using console commands:</p>



<ul class="wp-block-list">
<li><em>pip install &lt;package name&gt;</em></li>
</ul>



<h3 class="wp-block-heading" id="h-step-1-load-twitter-account-credentials-for-authentication">Step #1: Load Twitter Account Credentials for Authentication</h3>



<p class="wp-block-paragraph">Before interacting with the Twitter API, we must authenticate with our developer account credentials. The developer account is linked to the Twitter account specified during registration. So, when you execute an API request, it will use the associated Twitter user.</p>



<h4 class="wp-block-heading" id="h-storing-the-account-credentials-in-a-python-file">Storing the Account Credentials in a Python File</h4>



<p class="wp-block-paragraph">We should not store the user credentials directly in our Python notebooks. Instead, we should use a Python file and import it into our notebook. You can use the following sample file and replace the values with your Twitter API keys, secrets, and tokens.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}"># Twitter Consumer API keys
CONSUMER_KEY    = &quot;api123&quot;
CONSUMER_SECRET = &quot;api123&quot;

# Twitter Access token &amp; access token secret
ACCESS_TOKEN    = &quot;api123&quot;
ACCESS_SECRET   = &quot;api123&quot;

BEARER_TOKEN = &quot;api123&quot;

class TwitterSecrets:
    &quot;&quot;&quot;Class that holds Twitter Secrets&quot;&quot;&quot;

    def __init__(self):
        self.CONSUMER_KEY    = CONSUMER_KEY
        self.CONSUMER_SECRET = CONSUMER_SECRET
        self.ACCESS_TOKEN    = ACCESS_TOKEN
        self.ACCESS_SECRET   = ACCESS_SECRET
        self.BEARER_TOKEN   = BEARER_TOKEN
        
        # Tests if keys are present
        for key, secret in self.__dict__.items():
            assert secret != &quot;&quot;, f&quot;Please provide a valid secret for: {key}&quot;

twitter_secrets = TwitterSecrets()</pre></div>



<p class="wp-block-paragraph">Once you have stored the API keys in the file and the file in the right folder, you can load the API keys into your Python project with the following code.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">import pandas as pd
import tweepy 

# place the twitter_secrets file under &lt;User&gt;/anaconda3/Lib
from twitter_secrets import twitter_secrets as ts

consumer_key = ts.CONSUMER_KEY
consumer_secret = ts.CONSUMER_SECRET
access_token = ts.ACCESS_TOKEN
access_secret = ts.ACCESS_SECRET

### Print API Auth Data (leave disabled for security reasons)
# print(f'consumer_key: {consumer_key}')
# print(f'consumer_secret: {consumer_secret}')
# print(f'access_token: {access_token}')
# print(f'access_secret: {access_token}')</pre></div>



<h4 class="wp-block-heading" id="h-alternative-storing-the-account-credentials-in-a-yaml-file">Alternative: Storing the Account Credentials in a YAML File</h4>



<p class="wp-block-paragraph">Alternatively, you can also put the credentials into a YAML file (called &#8220;api_config_twitter.yml.&#8221; The file should then look as follows, and you can place it in a subfolder &#8220;API Keys&#8221; in your working directory:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">api_key: api123 
api_secret: api123
access_token: api123
access_secret: api123</pre></div>



<p class="wp-block-paragraph">You can then import the token and access keys with the code below. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">## In case you prefer to load the auth data from a local yaml file, use the following code
import yaml
# load the API keys and further data from your local yaml file
# place the api_config_twitter.yml file under &lt;python notebook&gt;/API_Keys/
yaml_file = open('API Keys/api_config_twitter.yml', 'r')  
p = yaml.load(yaml_file, Loader=yaml.FullLoader)

try:
    consumer_key = p['api_key']
    consumer_secret = p['api_secret']
    access_token = p['access_token']
    access_secret = p['access_secret']
except ValueError: 
        print('error')</pre></div>



<h3 class="wp-block-heading" id="h-step-2-request-user-authentication-via-the-api">Step #2: Request User Authentication via the API</h3>



<p class="wp-block-paragraph">When you have the auth data available in your project, you can authenticate against the Twitter API. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">#authenticating to access the twitter API
auth=tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_secret)
api=tweepy.API(auth)</pre></div>



<h3 class="wp-block-heading" id="h-step-3-post-a-text-only-tweet-on-twitter">Step #3: Post a Text-only Tweet on Twitter</h3>



<p class="wp-block-paragraph">Once we successfully authenticate at the Twitter API, we can interact with our Twitter user account. The code below will submit a test tweet via Twitter API. As you can see, we also indicated two hashtags.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Define the tweet text
tweet='this is an automated test tweet using #Python $BTC $ETH'

# Generate text tweet
api.update_status(tweet)</pre></div>



<p class="wp-block-paragraph">Once you run the code, the tweet will immediately appear in the feed of our Twitter account:</p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="3956" data-permalink="https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/image-4-13/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/05/image-4.png" data-orig-size="746,146" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-4" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/05/image-4.png" src="https://www.relataly.com/wp-content/uploads/2021/05/image-4.png" alt="A simple test tweet sent via the Twitter API" class="wp-image-3956" width="588" height="115" srcset="https://www.relataly.com/wp-content/uploads/2021/05/image-4.png 746w, https://www.relataly.com/wp-content/uploads/2021/05/image-4.png 300w" sizes="(max-width: 588px) 100vw, 588px" /><figcaption class="wp-element-caption">A simple test tweet sent via the Twitter API</figcaption></figure>



<h3 class="wp-block-heading" id="h-step-4-include-mediafiles-in-tweets-via-the-api">Step #4: Include Mediafiles in Tweets via the API</h3>



<p class="wp-block-paragraph">We can also include media files such as photos and videos in our tweets. For this case, Tweety provides a separate function called &#8220;update_with_media.&#8221; This function takes two arguments: the image path and tweet_text. </p>



<p class="wp-block-paragraph">Before running the code below, you need to change the image_path to reference an image file on your computer.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Define the tweet text
tweet_text='This is another automated test tweet using #Python'
image_path ='Test Images/ETH_price.png'

# Generate text tweet with media (image)
status = api.update_with_media(image_path, tweet_text)</pre></div>



<p class="wp-block-paragraph">Et voilà: Another Tweet has appeared on our Twitter Account. This time, the post includes the sample text and a media file.</p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="3955" data-permalink="https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/image-3-13/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/05/image-3.png" data-orig-size="757,431" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-3" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/05/image-3.png" src="https://www.relataly.com/wp-content/uploads/2021/05/image-3.png" alt="Twitter tweet with an image attached" class="wp-image-3955" width="646" height="367" srcset="https://www.relataly.com/wp-content/uploads/2021/05/image-3.png 757w, https://www.relataly.com/wp-content/uploads/2021/05/image-3.png 300w" sizes="(max-width: 646px) 100vw, 646px" /><figcaption class="wp-element-caption">Twitter tweet with an image attached</figcaption></figure>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p class="wp-block-paragraph">This article has shown how you can use Tweepy and Python to submit tweets via the Twitter API. You have learned to authenticate against the Twitter API and submit tweets containing text and media files.</p>



<p class="wp-block-paragraph">Understanding how to interact with Twitter via the API is essential when creating a Twitter bot. I have written another article about creating a Twitter signaling bot that analyzes financial data and tweets about relevant price movements. If you want to learn more about this topic, check out this article on<a href="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/" target="_blank" rel="noreferrer noopener"> Generating crypto trading signals in Python</a></p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<div style="display: inline-block;">
  <iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=3030181162&amp;asins=3030181162&amp;linkId=669e46025028259138fbb5ccec12dfbe&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1999579577&amp;asins=1999579577&amp;linkId=91d862698bf9010ff4c09539e4c49bf4&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1839217715&amp;asins=1839217715&amp;linkId=356ba074068849ff54393f527190825d&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1492032646&amp;asins=1492032646&amp;linkId=2214804dd039e7103577abd08722abac&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
</div>



<p class="has-contrast-2-color has-base-3-background-color has-text-color has-background wp-block-paragraph"><em>The links above to Amazon are affiliate links. By buying through these links, you support the Relataly.com blog and help to cover the hosting costs. Using the links does not affect the price.</em></p>
<p>The post <a href="https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/">Posting Tweets On Twitter using Python and Tweepy</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3925</post-id>	</item>
	</channel>
</rss>
