Home > Back-end >  How to plot a graph with own data created by a (for) loop?
How to plot a graph with own data created by a (for) loop?

Time:11-08

Before I worked with predefined data sets, this time I decided to create my own. This led me to a problem with plotting a graph with variable n and S_T. Based on a defined S_T which is a strike price and n number of observations I created a for loop with the following conditions.

I want my loop to work in the range (0,n) when S_T exceeds 169 then return 1000, when S_T is between 84.5 and 169 use the formula, when it's less then 84.5 return 0

I want to check if S_T's starting at 139 follows the condition and print the result. Then S_T=140 check and print result etc.

Which gives correct results: (0,0,0,....,1000,1000). However, If I want to plot both values, I don't see the desired result.

My question is: How to do it correctly, is the answer related to storying data in DataDrame? How to store all of the results from S_T that would produce a valid graph?

My code:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

S_T = 139
n = 300 

for S_T in range(0,n):
if S_T > 169:
    print(1000)
elif 84.5 < S_T <169:
    print(1000-max(0,1000*(169/S_T -1)))
else: print(0)
S_T  = 1 

plt.plot(n,S_T);
plt.xlabel('Number of iterations')
plt.ylabel('ICON');
print(S_T)
300

Which is a mistake, I would like to print every value

What the code produces: https://i.stack.imgur.com/kFBOG.png

CodePudding user response:

i don't really understand what you want to do in your for loop but you can just use 2 lists for your desired x and y values like so:

import plotly.graph_objects as go
x = []
y = []
for i in range(start, end):
    if i > some value:
        x.append(do something with i)
        y.append(do something with i)
    else:
        x.append(do something else with i)
        y.append(do something else with i)
fig = go.Scatter(x=x, y=y)
fig.show()
  • Related